4 # Copyright (C) 2006, 2007, 2008 Google Inc.
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.
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.
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
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
38 class FakeHypervisor(hv_base.BaseHypervisor):
39 """Fake hypervisor interface.
41 This can be used for testing the ganeti code without having to have
42 a real virtualisation software installed.
47 _ROOT_DIR = pathutils.RUN_DIR + "/fake-hypervisor"
50 hv_base.BaseHypervisor.__init__(self)
51 utils.EnsureDirs([(self._ROOT_DIR, constants.RUN_DIRS_MODE)])
53 def ListInstances(self, hvparams=None):
54 """Get the list of running instances.
57 return os.listdir(self._ROOT_DIR)
59 def GetInstanceInfo(self, instance_name):
60 """Get instance properties.
62 @param instance_name: the instance name
64 @return: tuple of (name, id, memory, vcpus, stat, times)
67 file_name = self._InstanceFile(instance_name)
68 if not os.path.exists(file_name):
71 fh = open(file_name, "r")
73 inst_id = fh.readline().strip()
74 memory = utils.TryConvert(int, fh.readline().strip())
75 vcpus = utils.TryConvert(int, fh.readline().strip())
78 return (instance_name, inst_id, memory, vcpus, stat, times)
82 raise errors.HypervisorError("Failed to list instance %s: %s" %
85 def GetAllInstancesInfo(self):
86 """Get properties of all instances.
88 @return: list of tuples (name, id, memory, vcpus, stat, times)
92 for file_name in os.listdir(self._ROOT_DIR):
94 fh = open(utils.PathJoin(self._ROOT_DIR, file_name), "r")
101 inst_id = fh.readline().strip()
102 memory = utils.TryConvert(int, fh.readline().strip())
103 vcpus = utils.TryConvert(int, fh.readline().strip())
108 data.append((file_name, inst_id, memory, vcpus, stat, times))
110 raise errors.HypervisorError("Failed to list instances: %s" % err)
114 def _InstanceFile(cls, instance_name):
115 """Compute the instance file for an instance name.
118 return utils.PathJoin(cls._ROOT_DIR, instance_name)
120 def _IsAlive(self, instance_name):
121 """Checks if an instance is alive.
124 file_name = self._InstanceFile(instance_name)
125 return os.path.exists(file_name)
127 def _MarkUp(self, instance, memory):
128 """Mark the instance as running.
130 This does no checks, which should be done by its callers.
133 file_name = self._InstanceFile(instance.name)
134 fh = file(file_name, "w")
136 fh.write("0\n%d\n%d\n" %
138 instance.beparams[constants.BE_VCPUS]))
142 def _MarkDown(self, instance_name):
143 """Mark the instance as running.
145 This does no checks, which should be done by its callers.
148 file_name = self._InstanceFile(instance_name)
149 utils.RemoveFile(file_name)
151 def StartInstance(self, instance, block_devices, startup_paused):
152 """Start an instance.
154 For the fake hypervisor, it just creates a file in the base dir,
155 creating an exception if it already exists. We don't actually
156 handle race conditions properly, since these are *FAKE* instances.
159 if self._IsAlive(instance.name):
160 raise errors.HypervisorError("Failed to start instance %s: %s" %
161 (instance.name, "already running"))
163 self._MarkUp(instance, self._InstanceStartupMemory(instance))
165 raise errors.HypervisorError("Failed to start instance %s: %s" %
166 (instance.name, err))
168 def StopInstance(self, instance, force=False, retry=False, name=None):
171 For the fake hypervisor, this just removes the file in the base
172 dir, if it exist, otherwise we raise an exception.
177 if not self._IsAlive(name):
178 raise errors.HypervisorError("Failed to stop instance %s: %s" %
179 (name, "not running"))
182 def RebootInstance(self, instance):
183 """Reboot an instance.
185 For the fake hypervisor, this does nothing.
190 def BalloonInstanceMemory(self, instance, mem):
191 """Balloon an instance memory to a certain value.
193 @type instance: L{objects.Instance}
194 @param instance: instance to be accepted
196 @param mem: actual memory size to use for instance runtime
199 if not self._IsAlive(instance.name):
200 raise errors.HypervisorError("Failed to balloon memory for %s: %s" %
201 (instance.name, "not running"))
203 self._MarkUp(instance, mem)
204 except EnvironmentError, err:
205 raise errors.HypervisorError("Failed to balloon memory for %s: %s" %
206 (instance.name, utils.ErrnoOrStr(err)))
208 def GetNodeInfo(self):
209 """Return information about the node.
211 This is just a wrapper over the base GetLinuxNodeInfo method.
213 @return: a dict with the following keys (values in MiB):
214 - memory_total: the total memory size on the node
215 - memory_free: the available memory on the node for instances
216 - memory_dom0: the memory used by the node itself, if available
219 result = self.GetLinuxNodeInfo()
220 # substract running instances
221 all_instances = self.GetAllInstancesInfo()
222 result["memory_free"] -= min(result["memory_free"],
223 sum([row[2] for row in all_instances]))
227 def GetInstanceConsole(cls, instance, hvparams, beparams):
228 """Return information for connecting to the console of an instance.
231 return objects.InstanceConsole(instance=instance.name,
232 kind=constants.CONS_MESSAGE,
233 message=("Console not available for fake"
236 def Verify(self, hvparams=None):
237 """Verify the hypervisor.
239 For the fake hypervisor, it just checks the existence of the base
242 @type hvparams: dict of strings
243 @param hvparams: hypervisor parameters to be verified against; not used
246 @return: Problem description if something is wrong, C{None} otherwise
249 if os.path.exists(self._ROOT_DIR):
252 return "The required directory '%s' does not exist" % self._ROOT_DIR
255 def PowercycleNode(cls):
256 """Fake hypervisor powercycle, just a wrapper over Linux powercycle.
259 cls.LinuxPowercycle()
261 def AcceptInstance(self, instance, info, target):
262 """Prepare to accept an instance.
264 @type instance: L{objects.Instance}
265 @param instance: instance to be accepted
267 @param info: instance info, not used
269 @param target: target host (usually ip), on this node
272 if self._IsAlive(instance.name):
273 raise errors.HypervisorError("Can't accept instance, already running")
275 def MigrateInstance(self, instance, target, live):
276 """Migrate an instance.
278 @type instance: L{objects.Instance}
279 @param instance: the instance to be migrated
281 @param target: hostname (usually ip) of the target node
283 @param live: whether to do a live or non-live migration
286 logging.debug("Fake hypervisor migrating %s to %s (live=%s)",
287 instance, target, live)
289 def FinalizeMigrationDst(self, instance, info, success):
290 """Finalize the instance migration on the target node.
292 For the fake hv, this just marks the instance up.
294 @type instance: L{objects.Instance}
295 @param instance: instance whose migration is being finalized
296 @type info: string/data (opaque)
297 @param info: migration information, from the source node
298 @type success: boolean
299 @param success: whether the migration was a success or a failure
303 self._MarkUp(instance, self._InstanceStartupMemory(instance))
306 self._MarkDown(instance.name)
308 def PostMigrationCleanup(self, instance):
309 """Clean-up after a migration.
311 To be executed on the source node.
313 @type instance: L{objects.Instance}
314 @param instance: the instance that was migrated
319 def FinalizeMigrationSource(self, instance, success, live):
320 """Finalize the instance migration on the source node.
322 @type instance: L{objects.Instance}
323 @param instance: the instance that was migrated
325 @param success: whether the migration succeeded or not
327 @param live: whether the user requested a live migration or not
330 # pylint: disable=W0613
332 self._MarkDown(instance.name)
334 def GetMigrationStatus(self, instance):
335 """Get the migration status
337 The fake hypervisor migration always succeeds.
339 @type instance: L{objects.Instance}
340 @param instance: the instance that is being migrated
341 @rtype: L{objects.MigrationStatus}
342 @return: the status of the current migration (one of
343 L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
344 progress info that can be retrieved from the hypervisor
347 return objects.MigrationStatus(status=constants.HV_MIGRATION_COMPLETED)