Statistics
| Branch: | Tag: | Revision:

root / lib / hypervisor / hv_fake.py @ d76880d8

History | View | Annotate | Download (11.1 kB)

1
#
2
#
3

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

    
21

    
22
"""Fake hypervisor
23

24
"""
25

    
26
import os
27
import os.path
28
import logging
29

    
30
from ganeti import utils
31
from ganeti import constants
32
from ganeti import errors
33
from ganeti import objects
34
from ganeti import pathutils
35
from ganeti.hypervisor import hv_base
36

    
37

    
38
class FakeHypervisor(hv_base.BaseHypervisor):
39
  """Fake hypervisor interface.
40

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

44
  """
45
  PARAMETERS = {
46
    constants.HV_MIGRATION_MODE: hv_base.MIGRATION_MODE_CHECK,
47
    }
48

    
49
  CAN_MIGRATE = True
50

    
51
  _ROOT_DIR = pathutils.RUN_DIR + "/fake-hypervisor"
52

    
53
  def __init__(self):
54
    hv_base.BaseHypervisor.__init__(self)
55
    utils.EnsureDirs([(self._ROOT_DIR, constants.RUN_DIRS_MODE)])
56

    
57
  def ListInstances(self, hvparams=None):
58
    """Get the list of running instances.
59

60
    """
61
    return os.listdir(self._ROOT_DIR)
62

    
63
  def GetInstanceInfo(self, instance_name, hvparams=None):
64
    """Get instance properties.
65

66
    @type instance_name: string
67
    @param instance_name: the instance name
68
    @type hvparams: dict of strings
69
    @param hvparams: hvparams to be used with this instance
70

71
    @return: tuple of (name, id, memory, vcpus, stat, times)
72

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

    
92
  def GetAllInstancesInfo(self, hvparams=None):
93
    """Get properties of all instances.
94

95
    @type hvparams: dict of strings
96
    @param hvparams: hypervisor parameter
97
    @return: list of tuples (name, id, memory, vcpus, stat, times)
98

99
    """
100
    data = []
101
    for file_name in os.listdir(self._ROOT_DIR):
102
      try:
103
        fh = open(utils.PathJoin(self._ROOT_DIR, file_name), "r")
104
        inst_id = "-1"
105
        memory = 0
106
        vcpus = 1
107
        stat = "-----"
108
        times = "-1"
109
        try:
110
          inst_id = fh.readline().strip()
111
          memory = utils.TryConvert(int, fh.readline().strip())
112
          vcpus = utils.TryConvert(int, fh.readline().strip())
113
          stat = "---b-"
114
          times = "0"
115
        finally:
116
          fh.close()
117
        data.append((file_name, inst_id, memory, vcpus, stat, times))
118
      except IOError, err:
119
        raise errors.HypervisorError("Failed to list instances: %s" % err)
120
    return data
121

    
122
  @classmethod
123
  def _InstanceFile(cls, instance_name):
124
    """Compute the instance file for an instance name.
125

126
    """
127
    return utils.PathJoin(cls._ROOT_DIR, instance_name)
128

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

132
    """
133
    file_name = self._InstanceFile(instance_name)
134
    return os.path.exists(file_name)
135

    
136
  def _MarkUp(self, instance, memory):
137
    """Mark the instance as running.
138

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

141
    """
142
    file_name = self._InstanceFile(instance.name)
143
    fh = file(file_name, "w")
144
    try:
145
      fh.write("0\n%d\n%d\n" %
146
               (memory,
147
                instance.beparams[constants.BE_VCPUS]))
148
    finally:
149
      fh.close()
150

    
151
  def _MarkDown(self, instance_name):
152
    """Mark the instance as running.
153

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

156
    """
157
    file_name = self._InstanceFile(instance_name)
158
    utils.RemoveFile(file_name)
159

    
160
  def StartInstance(self, instance, block_devices, startup_paused):
161
    """Start an instance.
162

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

167
    """
168
    if self._IsAlive(instance.name):
169
      raise errors.HypervisorError("Failed to start instance %s: %s" %
170
                                   (instance.name, "already running"))
171
    try:
172
      self._MarkUp(instance, self._InstanceStartupMemory(instance))
173
    except IOError, err:
174
      raise errors.HypervisorError("Failed to start instance %s: %s" %
175
                                   (instance.name, err))
176

    
177
  def StopInstance(self, instance, force=False, retry=False, name=None):
178
    """Stop an instance.
179

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

183
    """
184
    if name is None:
185
      name = instance.name
186
    if not self._IsAlive(name):
187
      raise errors.HypervisorError("Failed to stop instance %s: %s" %
188
                                   (name, "not running"))
189
    self._MarkDown(name)
190

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

194
    For the fake hypervisor, this does nothing.
195

196
    """
197
    return
198

    
199
  def BalloonInstanceMemory(self, instance, mem):
200
    """Balloon an instance memory to a certain value.
201

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

207
    """
208
    if not self._IsAlive(instance.name):
209
      raise errors.HypervisorError("Failed to balloon memory for %s: %s" %
210
                                   (instance.name, "not running"))
211
    try:
212
      self._MarkUp(instance, mem)
213
    except EnvironmentError, err:
214
      raise errors.HypervisorError("Failed to balloon memory for %s: %s" %
215
                                   (instance.name, utils.ErrnoOrStr(err)))
216

    
217
  def GetNodeInfo(self, hvparams=None):
218
    """Return information about the node.
219

220
    This is just a wrapper over the base GetLinuxNodeInfo method.
221

222
    @type hvparams: dict of strings
223
    @param hvparams: hypervisor parameters, not used in this class
224

225
    @return: a dict with the following keys (values in MiB):
226
          - memory_total: the total memory size on the node
227
          - memory_free: the available memory on the node for instances
228
          - memory_dom0: the memory used by the node itself, if available
229

230
    """
231
    result = self.GetLinuxNodeInfo()
232
    # substract running instances
233
    all_instances = self.GetAllInstancesInfo()
234
    result["memory_free"] -= min(result["memory_free"],
235
                                 sum([row[2] for row in all_instances]))
236
    return result
237

    
238
  @classmethod
239
  def GetInstanceConsole(cls, instance, primary_node, hvparams, beparams):
240
    """Return information for connecting to the console of an instance.
241

242
    """
243
    return objects.InstanceConsole(instance=instance.name,
244
                                   kind=constants.CONS_MESSAGE,
245
                                   message=("Console not available for fake"
246
                                            " hypervisor"))
247

    
248
  def Verify(self, hvparams=None):
249
    """Verify the hypervisor.
250

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

254
    @type hvparams: dict of strings
255
    @param hvparams: hypervisor parameters to be verified against; not used
256
      for fake hypervisors
257

258
    @return: Problem description if something is wrong, C{None} otherwise
259

260
    """
261
    if os.path.exists(self._ROOT_DIR):
262
      return None
263
    else:
264
      return "The required directory '%s' does not exist" % self._ROOT_DIR
265

    
266
  @classmethod
267
  def PowercycleNode(cls, hvparams=None):
268
    """Fake hypervisor powercycle, just a wrapper over Linux powercycle.
269

270
    @type hvparams: dict of strings
271
    @param hvparams: hypervisor params to be used on this node
272

273
    """
274
    cls.LinuxPowercycle()
275

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

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

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

    
290
  def MigrateInstance(self, cluster_name, instance, target, live):
291
    """Migrate an instance.
292

293
    @type cluster_name: string
294
    @param cluster_name: name of the cluster
295
    @type instance: L{objects.Instance}
296
    @param instance: the instance to be migrated
297
    @type target: string
298
    @param target: hostname (usually ip) of the target node
299
    @type live: boolean
300
    @param live: whether to do a live or non-live migration
301

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

    
306
  def FinalizeMigrationDst(self, instance, info, success):
307
    """Finalize the instance migration on the target node.
308

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

311
    @type instance: L{objects.Instance}
312
    @param instance: instance whose migration is being finalized
313
    @type info: string/data (opaque)
314
    @param info: migration information, from the source node
315
    @type success: boolean
316
    @param success: whether the migration was a success or a failure
317

318
    """
319
    if success:
320
      self._MarkUp(instance, self._InstanceStartupMemory(instance))
321
    else:
322
      # ensure it's down
323
      self._MarkDown(instance.name)
324

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

328
    To be executed on the source node.
329

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

333
    """
334
    pass
335

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

339
    @type instance: L{objects.Instance}
340
    @param instance: the instance that was migrated
341
    @type success: bool
342
    @param success: whether the migration succeeded or not
343
    @type live: bool
344
    @param live: whether the user requested a live migration or not
345

346
    """
347
    # pylint: disable=W0613
348
    if success:
349
      self._MarkDown(instance.name)
350

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

354
    The fake hypervisor migration always succeeds.
355

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

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