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.hypervisor import hv_base
37 class FakeHypervisor(hv_base.BaseHypervisor):
38 """Fake hypervisor interface.
40 This can be used for testing the ganeti code without having to have
41 a real virtualisation software installed.
46 _ROOT_DIR = constants.RUN_GANETI_DIR + "/fake-hypervisor"
49 hv_base.BaseHypervisor.__init__(self)
50 utils.EnsureDirs([(self._ROOT_DIR, constants.RUN_DIRS_MODE)])
52 def ListInstances(self):
53 """Get the list of running instances.
56 return os.listdir(self._ROOT_DIR)
58 def GetInstanceInfo(self, instance_name):
59 """Get instance properties.
61 @param instance_name: the instance name
63 @return: tuple of (name, id, memory, vcpus, stat, times)
66 file_name = self._InstanceFile(instance_name)
67 if not os.path.exists(file_name):
70 fh = open(file_name, "r")
72 inst_id = fh.readline().strip()
73 memory = utils.TryConvert(int, fh.readline().strip())
74 vcpus = utils.TryConvert(int, fh.readline().strip())
77 return (instance_name, inst_id, memory, vcpus, stat, times)
81 raise errors.HypervisorError("Failed to list instance %s: %s" %
84 def GetAllInstancesInfo(self):
85 """Get properties of all instances.
87 @return: list of tuples (name, id, memory, vcpus, stat, times)
91 for file_name in os.listdir(self._ROOT_DIR):
93 fh = open(utils.PathJoin(self._ROOT_DIR, file_name), "r")
100 inst_id = fh.readline().strip()
101 memory = utils.TryConvert(int, fh.readline().strip())
102 vcpus = utils.TryConvert(int, fh.readline().strip())
107 data.append((file_name, inst_id, memory, vcpus, stat, times))
109 raise errors.HypervisorError("Failed to list instances: %s" % err)
113 def _InstanceFile(cls, instance_name):
114 """Compute the instance file for an instance name.
117 return utils.PathJoin(cls._ROOT_DIR, instance_name)
119 def _IsAlive(self, instance_name):
120 """Checks if an instance is alive.
123 file_name = self._InstanceFile(instance_name)
124 return os.path.exists(file_name)
126 def _MarkUp(self, instance, memory):
127 """Mark the instance as running.
129 This does no checks, which should be done by its callers.
132 file_name = self._InstanceFile(instance.name)
133 fh = file(file_name, "w")
135 fh.write("0\n%d\n%d\n" %
137 instance.beparams[constants.BE_VCPUS]))
141 def _MarkDown(self, instance_name):
142 """Mark the instance as running.
144 This does no checks, which should be done by its callers.
147 file_name = self._InstanceFile(instance_name)
148 utils.RemoveFile(file_name)
150 def StartInstance(self, instance, block_devices, startup_paused):
151 """Start an instance.
153 For the fake hypervisor, it just creates a file in the base dir,
154 creating an exception if it already exists. We don't actually
155 handle race conditions properly, since these are *FAKE* instances.
158 if self._IsAlive(instance.name):
159 raise errors.HypervisorError("Failed to start instance %s: %s" %
160 (instance.name, "already running"))
162 self._MarkUp(instance, self._InstanceStartupMemory(instance))
164 raise errors.HypervisorError("Failed to start instance %s: %s" %
165 (instance.name, err))
167 def StopInstance(self, instance, force=False, retry=False, name=None):
170 For the fake hypervisor, this just removes the file in the base
171 dir, if it exist, otherwise we raise an exception.
176 if not self._IsAlive(name):
177 raise errors.HypervisorError("Failed to stop instance %s: %s" %
178 (name, "not running"))
181 def RebootInstance(self, instance):
182 """Reboot an instance.
184 For the fake hypervisor, this does nothing.
189 def BalloonInstanceMemory(self, instance, mem):
190 """Balloon an instance memory to a certain value.
192 @type instance: L{objects.Instance}
193 @param instance: instance to be accepted
195 @param mem: actual memory size to use for instance runtime
198 if not self._IsAlive(instance.name):
199 raise errors.HypervisorError("Failed to balloon memory for %s: %s" %
200 (instance.name, "not running"))
202 self._MarkUp(instance, mem)
203 except EnvironmentError, err:
204 raise errors.HypervisorError("Failed to balloon memory for %s: %s" %
205 (instance.name, utils.ErrnoOrStr(err)))
207 def GetNodeInfo(self):
208 """Return information about the node.
210 This is just a wrapper over the base GetLinuxNodeInfo method.
212 @return: a dict with the following keys (values in MiB):
213 - memory_total: the total memory size on the node
214 - memory_free: the available memory on the node for instances
215 - memory_dom0: the memory used by the node itself, if available
218 result = self.GetLinuxNodeInfo()
219 # substract running instances
220 all_instances = self.GetAllInstancesInfo()
221 result["memory_free"] -= min(result["memory_free"],
222 sum([row[2] for row in all_instances]))
226 def GetInstanceConsole(cls, instance, hvparams, beparams):
227 """Return information for connecting to the console of an instance.
230 return objects.InstanceConsole(instance=instance.name,
231 kind=constants.CONS_MESSAGE,
232 message=("Console not available for fake"
236 """Verify the hypervisor.
238 For the fake hypervisor, it just checks the existence of the base
242 if not os.path.exists(self._ROOT_DIR):
243 return "The required directory '%s' does not exist." % self._ROOT_DIR
246 def PowercycleNode(cls):
247 """Fake hypervisor powercycle, just a wrapper over Linux powercycle.
250 cls.LinuxPowercycle()
252 def AcceptInstance(self, instance, info, target):
253 """Prepare to accept an instance.
255 @type instance: L{objects.Instance}
256 @param instance: instance to be accepted
258 @param info: instance info, not used
260 @param target: target host (usually ip), on this node
263 if self._IsAlive(instance.name):
264 raise errors.HypervisorError("Can't accept instance, already running")
266 def MigrateInstance(self, instance, target, live):
267 """Migrate an instance.
269 @type instance: L{objects.Instance}
270 @param instance: the instance to be migrated
272 @param target: hostname (usually ip) of the target node
274 @param live: whether to do a live or non-live migration
277 logging.debug("Fake hypervisor migrating %s to %s (live=%s)",
278 instance, target, live)
280 def FinalizeMigrationDst(self, instance, info, success):
281 """Finalize the instance migration on the target node.
283 For the fake hv, this just marks the instance up.
285 @type instance: L{objects.Instance}
286 @param instance: instance whose migration is being finalized
287 @type info: string/data (opaque)
288 @param info: migration information, from the source node
289 @type success: boolean
290 @param success: whether the migration was a success or a failure
294 self._MarkUp(instance, self._InstanceStartupMemory(instance))
297 self._MarkDown(instance.name)
299 def PostMigrationCleanup(self, instance):
300 """Clean-up after a migration.
302 To be executed on the source node.
304 @type instance: L{objects.Instance}
305 @param instance: the instance that was migrated
310 def FinalizeMigrationSource(self, instance, success, live):
311 """Finalize the instance migration on the source node.
313 @type instance: L{objects.Instance}
314 @param instance: the instance that was migrated
316 @param success: whether the migration succeeded or not
318 @param live: whether the user requested a live migration or not
321 # pylint: disable=W0613
323 self._MarkDown(instance.name)
325 def GetMigrationStatus(self, instance):
326 """Get the migration status
328 The fake hypervisor migration always succeeds.
330 @type instance: L{objects.Instance}
331 @param instance: the instance that is being migrated
332 @rtype: L{objects.MigrationStatus}
333 @return: the status of the current migration (one of
334 L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
335 progress info that can be retrieved from the hypervisor
338 return objects.MigrationStatus(status=constants.HV_MIGRATION_COMPLETED)