hv_fake.py 10.2 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#
#

# Copyright (C) 2006, 2007, 2008 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.


"""Fake hypervisor

"""

import os
import os.path
28
import logging
29
30
31
32

from ganeti import utils
from ganeti import constants
from ganeti import errors
33
from ganeti import objects
34
from ganeti.hypervisor import hv_base
35
36


37
class FakeHypervisor(hv_base.BaseHypervisor):
38
39
40
41
42
43
  """Fake hypervisor interface.

  This can be used for testing the ganeti code without having to have
  a real virtualisation software installed.

  """
44
45
  CAN_MIGRATE = True

46
  _ROOT_DIR = constants.RUN_GANETI_DIR + "/fake-hypervisor"
47
48

  def __init__(self):
49
    hv_base.BaseHypervisor.__init__(self)
50
    utils.EnsureDirs([(self._ROOT_DIR, constants.RUN_DIRS_MODE)])
51
52
53
54
55
56
57
58
59
60

  def ListInstances(self):
    """Get the list of running instances.

    """
    return os.listdir(self._ROOT_DIR)

  def GetInstanceInfo(self, instance_name):
    """Get instance properties.

Iustin Pop's avatar
Iustin Pop committed
61
62
63
    @param instance_name: the instance name

    @return: tuple of (name, id, memory, vcpus, stat, times)
64
65

    """
66
    file_name = self._InstanceFile(instance_name)
67
68
69
    if not os.path.exists(file_name):
      return None
    try:
70
      fh = open(file_name, "r")
71
72
      try:
        inst_id = fh.readline().strip()
73
        memory = utils.TryConvert(int, fh.readline().strip())
74
        vcpus = utils.TryConvert(int, fh.readline().strip())
75
76
77
78
79
80
81
82
83
84
85
86
        stat = "---b-"
        times = "0"
        return (instance_name, inst_id, memory, vcpus, stat, times)
      finally:
        fh.close()
    except IOError, err:
      raise errors.HypervisorError("Failed to list instance %s: %s" %
                                   (instance_name, err))

  def GetAllInstancesInfo(self):
    """Get properties of all instances.

Iustin Pop's avatar
Iustin Pop committed
87
88
    @return: list of tuples (name, id, memory, vcpus, stat, times)

89
90
91
92
    """
    data = []
    for file_name in os.listdir(self._ROOT_DIR):
      try:
93
        fh = open(utils.PathJoin(self._ROOT_DIR, file_name), "r")
94
        inst_id = "-1"
95
96
        memory = 0
        vcpus = 1
97
98
99
100
        stat = "-----"
        times = "-1"
        try:
          inst_id = fh.readline().strip()
101
102
          memory = utils.TryConvert(int, fh.readline().strip())
          vcpus = utils.TryConvert(int, fh.readline().strip())
103
104
105
106
107
108
109
110
111
          stat = "---b-"
          times = "0"
        finally:
          fh.close()
        data.append((file_name, inst_id, memory, vcpus, stat, times))
      except IOError, err:
        raise errors.HypervisorError("Failed to list instances: %s" % err)
    return data

112
113
  @classmethod
  def _InstanceFile(cls, instance_name):
114
115
116
    """Compute the instance file for an instance name.

    """
117
    return utils.PathJoin(cls._ROOT_DIR, instance_name)
118
119
120
121
122
123
124
125

  def _IsAlive(self, instance_name):
    """Checks if an instance is alive.

    """
    file_name = self._InstanceFile(instance_name)
    return os.path.exists(file_name)

126
  def _MarkUp(self, instance, memory):
127
128
129
130
131
132
133
134
135
    """Mark the instance as running.

    This does no checks, which should be done by its callers.

    """
    file_name = self._InstanceFile(instance.name)
    fh = file(file_name, "w")
    try:
      fh.write("0\n%d\n%d\n" %
136
               (memory,
137
138
139
140
                instance.beparams[constants.BE_VCPUS]))
    finally:
      fh.close()

141
  def _MarkDown(self, instance_name):
142
143
144
145
146
    """Mark the instance as running.

    This does no checks, which should be done by its callers.

    """
147
    file_name = self._InstanceFile(instance_name)
148
149
    utils.RemoveFile(file_name)

150
  def StartInstance(self, instance, block_devices, startup_paused):
151
152
153
154
155
156
157
    """Start an instance.

    For the fake hypervisor, it just creates a file in the base dir,
    creating an exception if it already exists. We don't actually
    handle race conditions properly, since these are *FAKE* instances.

    """
158
    if self._IsAlive(instance.name):
159
160
161
      raise errors.HypervisorError("Failed to start instance %s: %s" %
                                   (instance.name, "already running"))
    try:
162
      self._MarkUp(instance, instance.beparams[constants.BE_MAXMEM])
163
164
165
166
    except IOError, err:
      raise errors.HypervisorError("Failed to start instance %s: %s" %
                                   (instance.name, err))

167
  def StopInstance(self, instance, force=False, retry=False, name=None):
168
169
170
171
172
173
    """Stop an instance.

    For the fake hypervisor, this just removes the file in the base
    dir, if it exist, otherwise we raise an exception.

    """
174
175
176
    if name is None:
      name = instance.name
    if not self._IsAlive(name):
177
      raise errors.HypervisorError("Failed to stop instance %s: %s" %
178
179
                                   (name, "not running"))
    self._MarkDown(name)
180
181
182
183
184
185
186
187
188

  def RebootInstance(self, instance):
    """Reboot an instance.

    For the fake hypervisor, this does nothing.

    """
    return

189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
  def BalloonInstanceMemory(self, instance, mem):
    """Balloon an instance memory to a certain value.

    @type instance: L{objects.Instance}
    @param instance: instance to be accepted
    @type mem: int
    @param mem: actual memory size to use for instance runtime

    """
    if not self._IsAlive(instance.name):
      raise errors.HypervisorError("Failed to balloon memory for %s: %s" %
                                   (instance.name, "not running"))
    try:
      self._MarkUp(instance, mem)
    except EnvironmentError, err:
      raise errors.HypervisorError("Failed to balloon memory for %s: %s" %
                                   (instance.name, utils.ErrnoOrStr(err)))

207
208
209
  def GetNodeInfo(self):
    """Return information about the node.

210
211
    This is just a wrapper over the base GetLinuxNodeInfo method.

Iustin Pop's avatar
Iustin Pop committed
212
213
214
215
    @return: a dict with the following keys (values in MiB):
          - memory_total: the total memory size on the node
          - memory_free: the available memory on the node for instances
          - memory_dom0: the memory used by the node itself, if available
216
217

    """
218
    result = self.GetLinuxNodeInfo()
219
220
    # substract running instances
    all_instances = self.GetAllInstancesInfo()
Iustin Pop's avatar
Iustin Pop committed
221
    result["memory_free"] -= min(result["memory_free"],
222
                                 sum([row[2] for row in all_instances]))
223
224
    return result

225
  @classmethod
226
227
  def GetInstanceConsole(cls, instance, hvparams, beparams):
    """Return information for connecting to the console of an instance.
228
229

    """
230
231
232
233
    return objects.InstanceConsole(instance=instance.name,
                                   kind=constants.CONS_MESSAGE,
                                   message=("Console not available for fake"
                                            " hypervisor"))
234
235
236
237
238
239
240
241
242
243

  def Verify(self):
    """Verify the hypervisor.

    For the fake hypervisor, it just checks the existence of the base
    dir.

    """
    if not os.path.exists(self._ROOT_DIR):
      return "The required directory '%s' does not exist." % self._ROOT_DIR
Iustin Pop's avatar
Iustin Pop committed
244
245
246
247
248
249
250

  @classmethod
  def PowercycleNode(cls):
    """Fake hypervisor powercycle, just a wrapper over Linux powercycle.

    """
    cls.LinuxPowercycle()
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268

  def AcceptInstance(self, instance, info, target):
    """Prepare to accept an instance.

    @type instance: L{objects.Instance}
    @param instance: instance to be accepted
    @type info: string
    @param info: instance info, not used
    @type target: string
    @param target: target host (usually ip), on this node

    """
    if self._IsAlive(instance.name):
      raise errors.HypervisorError("Can't accept instance, already running")

  def MigrateInstance(self, instance, target, live):
    """Migrate an instance.

Iustin Pop's avatar
Iustin Pop committed
269
    @type instance: L{objects.Instance}
270
271
272
273
274
275
276
277
278
279
    @param instance: the instance to be migrated
    @type target: string
    @param target: hostname (usually ip) of the target node
    @type live: boolean
    @param live: whether to do a live or non-live migration

    """
    logging.debug("Fake hypervisor migrating %s to %s (live=%s)",
                  instance, target, live)

280
281
  def FinalizeMigrationDst(self, instance, info, success):
    """Finalize the instance migration on the target node.
282
283
284
285
286

    For the fake hv, this just marks the instance up.

    @type instance: L{objects.Instance}
    @param instance: instance whose migration is being finalized
287
288
289
290
    @type info: string/data (opaque)
    @param info: migration information, from the source node
    @type success: boolean
    @param success: whether the migration was a success or a failure
291
292
293

    """
    if success:
294
      self._MarkUp(instance, instance.beparams[constants.BE_MAXMEM])
295
296
    else:
      # ensure it's down
297
      self._MarkDown(instance.name)
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338

  def PostMigrationCleanup(self, instance):
    """Clean-up after a migration.

    To be executed on the source node.

    @type instance: L{objects.Instance}
    @param instance: the instance that was migrated

    """
    pass

  def FinalizeMigrationSource(self, instance, success, live):
    """Finalize the instance migration on the source node.

    @type instance: L{objects.Instance}
    @param instance: the instance that was migrated
    @type success: bool
    @param success: whether the migration succeeded or not
    @type live: bool
    @param live: whether the user requested a live migration or not

    """
    # pylint: disable=W0613
    if success:
      self._MarkDown(instance.name)

  def GetMigrationStatus(self, instance):
    """Get the migration status

    The fake hypervisor migration always succeeds.

    @type instance: L{objects.Instance}
    @param instance: the instance that is being migrated
    @rtype: L{objects.MigrationStatus}
    @return: the status of the current migration (one of
             L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
             progress info that can be retrieved from the hypervisor

    """
    return objects.MigrationStatus(status=constants.HV_MIGRATION_COMPLETED)