4 # Copyright (C) 2006, 2007 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
22 """Functions used by the node daemon"""
39 from ganeti import errors
40 from ganeti import utils
41 from ganeti import ssh
42 from ganeti import hypervisor
43 from ganeti import constants
44 from ganeti import bdev
45 from ganeti import objects
46 from ganeti import ssconf
49 class RPCFail(Exception):
50 """Class denoting RPC failure.
52 Its argument is the error message.
56 def _Fail(msg, *args, **kwargs):
57 """Log an error and the raise an RPCFail exception.
59 This exception is then handled specially in the ganeti daemon and
60 turned into a 'failed' return type. As such, this function is a
61 useful shortcut for logging the error and returning it to the master
65 @param msg: the text of the exception
71 if "log" not in kwargs or kwargs["log"]: # if we should log this error
72 if "exc" in kwargs and kwargs["exc"]:
73 logging.exception(msg)
80 """Simple wrapper to return a SimpleStore.
82 @rtype: L{ssconf.SimpleStore}
83 @return: a SimpleStore instance
86 return ssconf.SimpleStore()
89 def _GetSshRunner(cluster_name):
90 """Simple wrapper to return an SshRunner.
92 @type cluster_name: str
93 @param cluster_name: the cluster name, which is needed
94 by the SshRunner constructor
95 @rtype: L{ssh.SshRunner}
96 @return: an SshRunner instance
99 return ssh.SshRunner(cluster_name)
102 def _Decompress(data):
103 """Unpacks data compressed by the RPC client.
105 @type data: list or tuple
106 @param data: Data sent by RPC client
108 @return: Decompressed data
111 assert isinstance(data, (list, tuple))
112 assert len(data) == 2
113 (encoding, content) = data
114 if encoding == constants.RPC_ENCODING_NONE:
116 elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
117 return zlib.decompress(base64.b64decode(content))
119 raise AssertionError("Unknown data encoding")
122 def _CleanDirectory(path, exclude=None):
123 """Removes all regular files in a directory.
126 @param path: the directory to clean
128 @param exclude: list of files to be excluded, defaults
132 if not os.path.isdir(path):
137 # Normalize excluded paths
138 exclude = [os.path.normpath(i) for i in exclude]
140 for rel_name in utils.ListVisibleFiles(path):
141 full_name = os.path.normpath(os.path.join(path, rel_name))
142 if full_name in exclude:
144 if os.path.isfile(full_name) and not os.path.islink(full_name):
145 utils.RemoveFile(full_name)
149 """Removes job queue files and archived jobs.
155 _CleanDirectory(constants.QUEUE_DIR, exclude=[constants.JOB_QUEUE_LOCK_FILE])
156 _CleanDirectory(constants.JOB_QUEUE_ARCHIVE_DIR)
160 """Returns master information.
162 This is an utility function to compute master information, either
163 for consumption here or from the node daemon.
166 @return: master_netdev, master_ip, master_name
167 @raise RPCFail: in case of errors
172 master_netdev = cfg.GetMasterNetdev()
173 master_ip = cfg.GetMasterIP()
174 master_node = cfg.GetMasterNode()
175 except errors.ConfigurationError, err:
176 _Fail("Cluster configuration incomplete: %s", err, exc=True)
177 return (master_netdev, master_ip, master_node)
180 def StartMaster(start_daemons):
181 """Activate local node as master node.
183 The function will always try activate the IP address of the master
184 (unless someone else has it). It will also start the master daemons,
185 based on the start_daemons parameter.
187 @type start_daemons: boolean
188 @param start_daemons: whether to also start the master
189 daemons (ganeti-masterd and ganeti-rapi)
193 # GetMasterInfo will raise an exception if not able to return data
194 master_netdev, master_ip, _ = GetMasterInfo()
197 if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
198 if utils.OwnIpAddress(master_ip):
199 # we already have the ip:
200 logging.debug("Master IP already configured, doing nothing")
202 msg = "Someone else has the master ip, not activating"
206 result = utils.RunCmd(["ip", "address", "add", "%s/32" % master_ip,
207 "dev", master_netdev, "label",
208 "%s:0" % master_netdev])
210 msg = "Can't activate master IP: %s" % result.output
214 result = utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev,
215 "-s", master_ip, master_ip])
216 # we'll ignore the exit code of arping
218 # and now start the master and rapi daemons
220 for daemon in 'ganeti-masterd', 'ganeti-rapi':
221 result = utils.RunCmd([daemon])
223 msg = "Can't start daemon %s: %s" % (daemon, result.output)
228 _Fail("; ".join(err_msgs))
231 def StopMaster(stop_daemons):
232 """Deactivate this node as master.
234 The function will always try to deactivate the IP address of the
235 master. It will also stop the master daemons depending on the
236 stop_daemons parameter.
238 @type stop_daemons: boolean
239 @param stop_daemons: whether to also stop the master daemons
240 (ganeti-masterd and ganeti-rapi)
244 # TODO: log and report back to the caller the error failures; we
245 # need to decide in which case we fail the RPC for this
247 # GetMasterInfo will raise an exception if not able to return data
248 master_netdev, master_ip, _ = GetMasterInfo()
250 result = utils.RunCmd(["ip", "address", "del", "%s/32" % master_ip,
251 "dev", master_netdev])
253 logging.error("Can't remove the master IP, error: %s", result.output)
254 # but otherwise ignore the failure
257 # stop/kill the rapi and the master daemon
258 for daemon in constants.RAPI_PID, constants.MASTERD_PID:
259 utils.KillProcess(utils.ReadPidFile(utils.DaemonPidFileName(daemon)))
262 def AddNode(dsa, dsapub, rsa, rsapub, sshkey, sshpub):
263 """Joins this node to the cluster.
265 This does the following:
266 - updates the hostkeys of the machine (rsa and dsa)
267 - adds the ssh private key to the user
268 - adds the ssh public key to the users' authorized_keys file
271 @param dsa: the DSA private key to write
273 @param dsapub: the DSA public key to write
275 @param rsa: the RSA private key to write
277 @param rsapub: the RSA public key to write
279 @param sshkey: the SSH private key to write
281 @param sshpub: the SSH public key to write
283 @return: the success of the operation
286 sshd_keys = [(constants.SSH_HOST_RSA_PRIV, rsa, 0600),
287 (constants.SSH_HOST_RSA_PUB, rsapub, 0644),
288 (constants.SSH_HOST_DSA_PRIV, dsa, 0600),
289 (constants.SSH_HOST_DSA_PUB, dsapub, 0644)]
290 for name, content, mode in sshd_keys:
291 utils.WriteFile(name, data=content, mode=mode)
294 priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS,
296 except errors.OpExecError, err:
297 _Fail("Error while processing user ssh files: %s", err, exc=True)
299 for name, content in [(priv_key, sshkey), (pub_key, sshpub)]:
300 utils.WriteFile(name, data=content, mode=0600)
302 utils.AddAuthorizedKey(auth_keys, sshpub)
304 utils.RunCmd([constants.SSH_INITD_SCRIPT, "restart"])
308 """Cleans up and remove the current node.
310 This function cleans up and prepares the current node to be removed
313 If processing is successful, then it raises an
314 L{errors.QuitGanetiException} which is used as a special case to
315 shutdown the node daemon.
318 _CleanDirectory(constants.DATA_DIR)
322 priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
324 f = open(pub_key, 'r')
326 utils.RemoveAuthorizedKey(auth_keys, f.read(8192))
330 utils.RemoveFile(priv_key)
331 utils.RemoveFile(pub_key)
332 except errors.OpExecError:
333 logging.exception("Error while processing ssh files")
335 # Raise a custom exception (handled in ganeti-noded)
336 raise errors.QuitGanetiException(True, 'Shutdown scheduled')
339 def GetNodeInfo(vgname, hypervisor_type):
340 """Gives back a hash with different information about the node.
342 @type vgname: C{string}
343 @param vgname: the name of the volume group to ask for disk space information
344 @type hypervisor_type: C{str}
345 @param hypervisor_type: the name of the hypervisor to ask for
348 @return: dictionary with the following keys:
349 - vg_size is the size of the configured volume group in MiB
350 - vg_free is the free size of the volume group in MiB
351 - memory_dom0 is the memory allocated for domain0 in MiB
352 - memory_free is the currently available (free) ram in MiB
353 - memory_total is the total number of ram in MiB
357 vginfo = _GetVGInfo(vgname)
358 outputarray['vg_size'] = vginfo['vg_size']
359 outputarray['vg_free'] = vginfo['vg_free']
361 hyper = hypervisor.GetHypervisor(hypervisor_type)
362 hyp_info = hyper.GetNodeInfo()
363 if hyp_info is not None:
364 outputarray.update(hyp_info)
366 f = open("/proc/sys/kernel/random/boot_id", 'r')
368 outputarray["bootid"] = f.read(128).rstrip("\n")
375 def VerifyNode(what, cluster_name):
376 """Verify the status of the local node.
378 Based on the input L{what} parameter, various checks are done on the
381 If the I{filelist} key is present, this list of
382 files is checksummed and the file/checksum pairs are returned.
384 If the I{nodelist} key is present, we check that we have
385 connectivity via ssh with the target nodes (and check the hostname
388 If the I{node-net-test} key is present, we check that we have
389 connectivity to the given nodes via both primary IP and, if
390 applicable, secondary IPs.
393 @param what: a dictionary of things to check:
394 - filelist: list of files for which to compute checksums
395 - nodelist: list of nodes we should check ssh communication with
396 - node-net-test: list of nodes we should check node daemon port
398 - hypervisor: list with hypervisors to run the verify for
400 @return: a dictionary with the same keys as the input dict, and
401 values representing the result of the checks
406 if constants.NV_HYPERVISOR in what:
407 result[constants.NV_HYPERVISOR] = tmp = {}
408 for hv_name in what[constants.NV_HYPERVISOR]:
409 tmp[hv_name] = hypervisor.GetHypervisor(hv_name).Verify()
411 if constants.NV_FILELIST in what:
412 result[constants.NV_FILELIST] = utils.FingerprintFiles(
413 what[constants.NV_FILELIST])
415 if constants.NV_NODELIST in what:
416 result[constants.NV_NODELIST] = tmp = {}
417 random.shuffle(what[constants.NV_NODELIST])
418 for node in what[constants.NV_NODELIST]:
419 success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
423 if constants.NV_NODENETTEST in what:
424 result[constants.NV_NODENETTEST] = tmp = {}
425 my_name = utils.HostInfo().name
426 my_pip = my_sip = None
427 for name, pip, sip in what[constants.NV_NODENETTEST]:
433 tmp[my_name] = ("Can't find my own primary/secondary IP"
436 port = utils.GetNodeDaemonPort()
437 for name, pip, sip in what[constants.NV_NODENETTEST]:
439 if not utils.TcpPing(pip, port, source=my_pip):
440 fail.append("primary")
442 if not utils.TcpPing(sip, port, source=my_sip):
443 fail.append("secondary")
445 tmp[name] = ("failure using the %s interface(s)" %
448 if constants.NV_LVLIST in what:
449 result[constants.NV_LVLIST] = GetVolumeList(what[constants.NV_LVLIST])
451 if constants.NV_INSTANCELIST in what:
452 result[constants.NV_INSTANCELIST] = GetInstanceList(
453 what[constants.NV_INSTANCELIST])
455 if constants.NV_VGLIST in what:
456 result[constants.NV_VGLIST] = utils.ListVolumeGroups()
458 if constants.NV_VERSION in what:
459 result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
460 constants.RELEASE_VERSION)
462 if constants.NV_HVINFO in what:
463 hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
464 result[constants.NV_HVINFO] = hyper.GetNodeInfo()
466 if constants.NV_DRBDLIST in what:
468 used_minors = bdev.DRBD8.GetUsedDevs().keys()
469 except errors.BlockDeviceError, err:
470 logging.warning("Can't get used minors list", exc_info=True)
471 used_minors = str(err)
472 result[constants.NV_DRBDLIST] = used_minors
477 def GetVolumeList(vg_name):
478 """Compute list of logical volumes and their size.
481 @param vg_name: the volume group whose LVs we should list
484 dictionary of all partions (key) with value being a tuple of
485 their size (in MiB), inactive and online status::
487 {'test1': ('20.06', True, True)}
489 in case of errors, a string is returned with the error
495 result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
496 "--separator=%s" % sep,
497 "-olv_name,lv_size,lv_attr", vg_name])
499 _Fail("Failed to list logical volumes, lvs output: %s", result.output)
501 valid_line_re = re.compile("^ *([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
502 for line in result.stdout.splitlines():
504 match = valid_line_re.match(line)
506 logging.error("Invalid line returned from lvs output: '%s'", line)
508 name, size, attr = match.groups()
509 inactive = attr[4] == '-'
510 online = attr[5] == 'o'
511 lvs[name] = (size, inactive, online)
516 def ListVolumeGroups():
517 """List the volume groups and their size.
520 @return: dictionary with keys volume name and values the
524 return utils.ListVolumeGroups()
528 """List all volumes on this node.
532 A list of dictionaries, each having four keys:
533 - name: the logical volume name,
534 - size: the size of the logical volume
535 - dev: the physical device on which the LV lives
536 - vg: the volume group to which it belongs
538 In case of errors, we return an empty list and log the
541 Note that since a logical volume can live on multiple physical
542 volumes, the resulting list might include a logical volume
546 result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
548 "--options=lv_name,lv_size,devices,vg_name"])
550 _Fail("Failed to list logical volumes, lvs output: %s",
555 return dev.split('(')[0]
561 'name': line[0].strip(),
562 'size': line[1].strip(),
563 'dev': parse_dev(line[2].strip()),
564 'vg': line[3].strip(),
567 return [map_line(line.split('|')) for line in result.stdout.splitlines()
568 if line.count('|') >= 3]
571 def BridgesExist(bridges_list):
572 """Check if a list of bridges exist on the current node.
575 @return: C{True} if all of them exist, C{False} otherwise
579 for bridge in bridges_list:
580 if not utils.BridgeExists(bridge):
581 missing.append(bridge)
584 _Fail("Missing bridges %s", ", ".join(missing))
587 def GetInstanceList(hypervisor_list):
588 """Provides a list of instances.
590 @type hypervisor_list: list
591 @param hypervisor_list: the list of hypervisors to query information
594 @return: a list of all running instances on the current node
595 - instance1.example.com
596 - instance2.example.com
600 for hname in hypervisor_list:
602 names = hypervisor.GetHypervisor(hname).ListInstances()
603 results.extend(names)
604 except errors.HypervisorError, err:
605 _Fail("Error enumerating instances (hypervisor %s): %s",
606 hname, err, exc=True)
611 def GetInstanceInfo(instance, hname):
612 """Gives back the information about an instance as a dictionary.
614 @type instance: string
615 @param instance: the instance name
617 @param hname: the hypervisor type of the instance
620 @return: dictionary with the following keys:
621 - memory: memory size of instance (int)
622 - state: xen state of instance (string)
623 - time: cpu time of instance (float)
628 iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
629 if iinfo is not None:
630 output['memory'] = iinfo[2]
631 output['state'] = iinfo[4]
632 output['time'] = iinfo[5]
637 def GetInstanceMigratable(instance):
638 """Gives whether an instance can be migrated.
640 @type instance: L{objects.Instance}
641 @param instance: object representing the instance to be checked.
644 @return: tuple of (result, description) where:
645 - result: whether the instance can be migrated or not
646 - description: a description of the issue, if relevant
649 hyper = hypervisor.GetHypervisor(instance.hypervisor)
650 iname = instance.name
651 if iname not in hyper.ListInstances():
652 _Fail("Instance %s is not running", iname)
654 for idx in range(len(instance.disks)):
655 link_name = _GetBlockDevSymlinkPath(iname, idx)
656 if not os.path.islink(link_name):
657 _Fail("Instance %s was not restarted since ganeti 1.2.5", iname)
660 def GetAllInstancesInfo(hypervisor_list):
661 """Gather data about all instances.
663 This is the equivalent of L{GetInstanceInfo}, except that it
664 computes data for all instances at once, thus being faster if one
665 needs data about more than one instance.
667 @type hypervisor_list: list
668 @param hypervisor_list: list of hypervisors to query for instance data
671 @return: dictionary of instance: data, with data having the following keys:
672 - memory: memory size of instance (int)
673 - state: xen state of instance (string)
674 - time: cpu time of instance (float)
675 - vcpus: the number of vcpus
680 for hname in hypervisor_list:
681 iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
683 for name, _, memory, vcpus, state, times in iinfo:
691 # we only check static parameters, like memory and vcpus,
692 # and not state and time which can change between the
693 # invocations of the different hypervisors
694 for key in 'memory', 'vcpus':
695 if value[key] != output[name][key]:
696 _Fail("Instance %s is running twice"
697 " with different parameters", name)
703 def InstanceOsAdd(instance, reinstall):
704 """Add an OS to an instance.
706 @type instance: L{objects.Instance}
707 @param instance: Instance whose OS is to be installed
708 @type reinstall: boolean
709 @param reinstall: whether this is an instance reinstall
713 inst_os = OSFromDisk(instance.os)
715 create_env = OSEnvironment(instance, inst_os)
717 create_env['INSTANCE_REINSTALL'] = "1"
719 logfile = "%s/add-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
720 instance.name, int(time.time()))
722 result = utils.RunCmd([inst_os.create_script], env=create_env,
723 cwd=inst_os.path, output=logfile,)
725 logging.error("os create command '%s' returned error: %s, logfile: %s,"
726 " output: %s", result.cmd, result.fail_reason, logfile,
728 lines = [utils.SafeEncode(val)
729 for val in utils.TailFile(logfile, lines=20)]
730 _Fail("OS create script failed (%s), last lines in the"
731 " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
734 def RunRenameInstance(instance, old_name):
735 """Run the OS rename script for an instance.
737 @type instance: L{objects.Instance}
738 @param instance: Instance whose OS is to be installed
739 @type old_name: string
740 @param old_name: previous instance name
742 @return: the success of the operation
745 inst_os = OSFromDisk(instance.os)
747 rename_env = OSEnvironment(instance, inst_os)
748 rename_env['OLD_INSTANCE_NAME'] = old_name
750 logfile = "%s/rename-%s-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
752 instance.name, int(time.time()))
754 result = utils.RunCmd([inst_os.rename_script], env=rename_env,
755 cwd=inst_os.path, output=logfile)
758 logging.error("os create command '%s' returned error: %s output: %s",
759 result.cmd, result.fail_reason, result.output)
760 lines = [utils.SafeEncode(val)
761 for val in utils.TailFile(logfile, lines=20)]
762 _Fail("OS rename script failed (%s), last lines in the"
763 " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
766 def _GetVGInfo(vg_name):
767 """Get information about the volume group.
770 @param vg_name: the volume group which we query
773 A dictionary with the following keys:
774 - C{vg_size} is the total size of the volume group in MiB
775 - C{vg_free} is the free size of the volume group in MiB
776 - C{pv_count} are the number of physical disks in that VG
778 If an error occurs during gathering of data, we return the same dict
779 with keys all set to None.
782 retdic = dict.fromkeys(["vg_size", "vg_free", "pv_count"])
784 retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings",
785 "--nosuffix", "--units=m", "--separator=:", vg_name])
788 logging.error("volume group %s not present", vg_name)
790 valarr = retval.stdout.strip().rstrip(':').split(':')
794 "vg_size": int(round(float(valarr[0]), 0)),
795 "vg_free": int(round(float(valarr[1]), 0)),
796 "pv_count": int(valarr[2]),
798 except ValueError, err:
799 logging.exception("Fail to parse vgs output: %s", err)
801 logging.error("vgs output has the wrong number of fields (expected"
802 " three): %s", str(valarr))
806 def _GetBlockDevSymlinkPath(instance_name, idx):
807 return os.path.join(constants.DISK_LINKS_DIR,
808 "%s:%d" % (instance_name, idx))
811 def _SymlinkBlockDev(instance_name, device_path, idx):
812 """Set up symlinks to a instance's block device.
814 This is an auxiliary function run when an instance is start (on the primary
815 node) or when an instance is migrated (on the target node).
818 @param instance_name: the name of the target instance
819 @param device_path: path of the physical block device, on the node
820 @param idx: the disk index
821 @return: absolute path to the disk's symlink
824 link_name = _GetBlockDevSymlinkPath(instance_name, idx)
826 os.symlink(device_path, link_name)
828 if err.errno == errno.EEXIST:
829 if (not os.path.islink(link_name) or
830 os.readlink(link_name) != device_path):
832 os.symlink(device_path, link_name)
839 def _RemoveBlockDevLinks(instance_name, disks):
840 """Remove the block device symlinks belonging to the given instance.
843 for idx, _ in enumerate(disks):
844 link_name = _GetBlockDevSymlinkPath(instance_name, idx)
845 if os.path.islink(link_name):
849 logging.exception("Can't remove symlink '%s'", link_name)
852 def _GatherAndLinkBlockDevs(instance):
853 """Set up an instance's block device(s).
855 This is run on the primary node at instance startup. The block
856 devices must be already assembled.
858 @type instance: L{objects.Instance}
859 @param instance: the instance whose disks we shoul assemble
861 @return: list of (disk_object, device_path)
865 for idx, disk in enumerate(instance.disks):
866 device = _RecursiveFindBD(disk)
868 raise errors.BlockDeviceError("Block device '%s' is not set up." %
872 link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
874 raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
877 block_devices.append((disk, link_name))
882 def StartInstance(instance):
883 """Start an instance.
885 @type instance: L{objects.Instance}
886 @param instance: the instance object
890 running_instances = GetInstanceList([instance.hypervisor])
892 if instance.name in running_instances:
893 logging.info("Instance %s already running, not starting", instance.name)
897 block_devices = _GatherAndLinkBlockDevs(instance)
898 hyper = hypervisor.GetHypervisor(instance.hypervisor)
899 hyper.StartInstance(instance, block_devices)
900 except errors.BlockDeviceError, err:
901 _Fail("Block device error: %s", err, exc=True)
902 except errors.HypervisorError, err:
903 _RemoveBlockDevLinks(instance.name, instance.disks)
904 _Fail("Hypervisor error: %s", err, exc=True)
907 def InstanceShutdown(instance):
908 """Shut an instance down.
910 @note: this functions uses polling with a hardcoded timeout.
912 @type instance: L{objects.Instance}
913 @param instance: the instance object
917 hv_name = instance.hypervisor
918 running_instances = GetInstanceList([hv_name])
919 iname = instance.name
921 if iname not in running_instances:
922 logging.info("Instance %s not running, doing nothing", iname)
925 hyper = hypervisor.GetHypervisor(hv_name)
927 hyper.StopInstance(instance)
928 except errors.HypervisorError, err:
929 _Fail("Failed to stop instance %s: %s", iname, err)
931 # test every 10secs for 2min
935 if instance.name not in GetInstanceList([hv_name]):
939 # the shutdown did not succeed
940 logging.error("Shutdown of '%s' unsuccessful, using destroy", iname)
943 hyper.StopInstance(instance, force=True)
944 except errors.HypervisorError, err:
945 _Fail("Failed to force stop instance %s: %s", iname, err)
948 if instance.name in GetInstanceList([hv_name]):
949 _Fail("Could not shutdown instance %s even by destroy", iname)
951 _RemoveBlockDevLinks(iname, instance.disks)
954 def InstanceReboot(instance, reboot_type):
955 """Reboot an instance.
957 @type instance: L{objects.Instance}
958 @param instance: the instance object to reboot
959 @type reboot_type: str
960 @param reboot_type: the type of reboot, one the following
962 - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
963 instance OS, do not recreate the VM
964 - L{constants.INSTANCE_REBOOT_HARD}: tear down and
965 restart the VM (at the hypervisor level)
966 - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
967 not accepted here, since that mode is handled differently, in
968 cmdlib, and translates into full stop and start of the
969 instance (instead of a call_instance_reboot RPC)
973 running_instances = GetInstanceList([instance.hypervisor])
975 if instance.name not in running_instances:
976 _Fail("Cannot reboot instance %s that is not running", instance.name)
978 hyper = hypervisor.GetHypervisor(instance.hypervisor)
979 if reboot_type == constants.INSTANCE_REBOOT_SOFT:
981 hyper.RebootInstance(instance)
982 except errors.HypervisorError, err:
983 _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
984 elif reboot_type == constants.INSTANCE_REBOOT_HARD:
986 InstanceShutdown(instance)
987 return StartInstance(instance)
988 except errors.HypervisorError, err:
989 _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
991 _Fail("Invalid reboot_type received: %s", reboot_type)
994 def MigrationInfo(instance):
995 """Gather information about an instance to be migrated.
997 @type instance: L{objects.Instance}
998 @param instance: the instance definition
1001 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1003 info = hyper.MigrationInfo(instance)
1004 except errors.HypervisorError, err:
1005 _Fail("Failed to fetch migration information: %s", err, exc=True)
1009 def AcceptInstance(instance, info, target):
1010 """Prepare the node to accept an instance.
1012 @type instance: L{objects.Instance}
1013 @param instance: the instance definition
1014 @type info: string/data (opaque)
1015 @param info: migration information, from the source node
1016 @type target: string
1017 @param target: target host (usually ip), on this node
1020 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1022 hyper.AcceptInstance(instance, info, target)
1023 except errors.HypervisorError, err:
1024 _Fail("Failed to accept instance: %s", err, exc=True)
1027 def FinalizeMigration(instance, info, success):
1028 """Finalize any preparation to accept an instance.
1030 @type instance: L{objects.Instance}
1031 @param instance: the instance definition
1032 @type info: string/data (opaque)
1033 @param info: migration information, from the source node
1034 @type success: boolean
1035 @param success: whether the migration was a success or a failure
1038 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1040 hyper.FinalizeMigration(instance, info, success)
1041 except errors.HypervisorError, err:
1042 _Fail("Failed to finalize migration: %s", err, exc=True)
1045 def MigrateInstance(instance, target, live):
1046 """Migrates an instance to another node.
1048 @type instance: L{objects.Instance}
1049 @param instance: the instance definition
1050 @type target: string
1051 @param target: the target node name
1053 @param live: whether the migration should be done live or not (the
1054 interpretation of this parameter is left to the hypervisor)
1056 @return: a tuple of (success, msg) where:
1057 - succes is a boolean denoting the success/failure of the operation
1058 - msg is a string with details in case of failure
1061 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1064 hyper.MigrateInstance(instance.name, target, live)
1065 except errors.HypervisorError, err:
1066 _Fail("Failed to migrate instance: %s", err, exc=True)
1069 def BlockdevCreate(disk, size, owner, on_primary, info):
1070 """Creates a block device for an instance.
1072 @type disk: L{objects.Disk}
1073 @param disk: the object describing the disk we should create
1075 @param size: the size of the physical underlying device, in MiB
1077 @param owner: the name of the instance for which disk is created,
1078 used for device cache data
1079 @type on_primary: boolean
1080 @param on_primary: indicates if it is the primary node or not
1082 @param info: string that will be sent to the physical device
1083 creation, used for example to set (LVM) tags on LVs
1085 @return: the new unique_id of the device (this can sometime be
1086 computed only after creation), or None. On secondary nodes,
1087 it's not required to return anything.
1092 for child in disk.children:
1094 crdev = _RecursiveAssembleBD(child, owner, on_primary)
1095 except errors.BlockDeviceError, err:
1096 _Fail("Can't assemble device %s: %s", child, err)
1097 if on_primary or disk.AssembleOnSecondary():
1098 # we need the children open in case the device itself has to
1102 except errors.BlockDeviceError, err:
1103 _Fail("Can't make child '%s' read-write: %s", child, err)
1107 device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
1108 except errors.BlockDeviceError, err:
1109 _Fail("Can't create block device: %s", err)
1111 if on_primary or disk.AssembleOnSecondary():
1114 except errors.BlockDeviceError, err:
1115 _Fail("Can't assemble device after creation, unusual event: %s", err)
1116 device.SetSyncSpeed(constants.SYNC_SPEED)
1117 if on_primary or disk.OpenOnSecondary():
1119 device.Open(force=True)
1120 except errors.BlockDeviceError, err:
1121 _Fail("Can't make device r/w after creation, unusual event: %s", err)
1122 DevCacheManager.UpdateCache(device.dev_path, owner,
1123 on_primary, disk.iv_name)
1125 device.SetInfo(info)
1127 return device.unique_id
1130 def BlockdevRemove(disk):
1131 """Remove a block device.
1133 @note: This is intended to be called recursively.
1135 @type disk: L{objects.Disk}
1136 @param disk: the disk object we should remove
1138 @return: the success of the operation
1143 rdev = _RecursiveFindBD(disk)
1144 except errors.BlockDeviceError, err:
1145 # probably can't attach
1146 logging.info("Can't attach to device %s in remove", disk)
1148 if rdev is not None:
1149 r_path = rdev.dev_path
1152 except errors.BlockDeviceError, err:
1153 msgs.append(str(err))
1155 DevCacheManager.RemoveCache(r_path)
1158 for child in disk.children:
1160 BlockdevRemove(child)
1161 except RPCFail, err:
1162 msgs.append(str(err))
1165 _Fail("; ".join(msgs))
1168 def _RecursiveAssembleBD(disk, owner, as_primary):
1169 """Activate a block device for an instance.
1171 This is run on the primary and secondary nodes for an instance.
1173 @note: this function is called recursively.
1175 @type disk: L{objects.Disk}
1176 @param disk: the disk we try to assemble
1178 @param owner: the name of the instance which owns the disk
1179 @type as_primary: boolean
1180 @param as_primary: if we should make the block device
1183 @return: the assembled device or None (in case no device
1185 @raise errors.BlockDeviceError: in case there is an error
1186 during the activation of the children or the device
1192 mcn = disk.ChildrenNeeded()
1194 mcn = 0 # max number of Nones allowed
1196 mcn = len(disk.children) - mcn # max number of Nones
1197 for chld_disk in disk.children:
1199 cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1200 except errors.BlockDeviceError, err:
1201 if children.count(None) >= mcn:
1204 logging.error("Error in child activation (but continuing): %s",
1206 children.append(cdev)
1208 if as_primary or disk.AssembleOnSecondary():
1209 r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
1210 r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1212 if as_primary or disk.OpenOnSecondary():
1214 DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1215 as_primary, disk.iv_name)
1222 def BlockdevAssemble(disk, owner, as_primary):
1223 """Activate a block device for an instance.
1225 This is a wrapper over _RecursiveAssembleBD.
1227 @rtype: str or boolean
1228 @return: a C{/dev/...} path for primary nodes, and
1229 C{True} for secondary nodes
1233 result = _RecursiveAssembleBD(disk, owner, as_primary)
1234 if isinstance(result, bdev.BlockDev):
1235 result = result.dev_path
1236 except errors.BlockDeviceError, err:
1237 _Fail("Error while assembling disk: %s", err, exc=True)
1242 def BlockdevShutdown(disk):
1243 """Shut down a block device.
1245 First, if the device is assembled (Attach() is successful), then
1246 the device is shutdown. Then the children of the device are
1249 This function is called recursively. Note that we don't cache the
1250 children or such, as oppossed to assemble, shutdown of different
1251 devices doesn't require that the upper device was active.
1253 @type disk: L{objects.Disk}
1254 @param disk: the description of the disk we should
1260 r_dev = _RecursiveFindBD(disk)
1261 if r_dev is not None:
1262 r_path = r_dev.dev_path
1265 DevCacheManager.RemoveCache(r_path)
1266 except errors.BlockDeviceError, err:
1267 msgs.append(str(err))
1270 for child in disk.children:
1272 BlockdevShutdown(child)
1273 except RPCFail, err:
1274 msgs.append(str(err))
1277 _Fail("; ".join(msgs))
1280 def BlockdevAddchildren(parent_cdev, new_cdevs):
1281 """Extend a mirrored block device.
1283 @type parent_cdev: L{objects.Disk}
1284 @param parent_cdev: the disk to which we should add children
1285 @type new_cdevs: list of L{objects.Disk}
1286 @param new_cdevs: the list of children which we should add
1290 parent_bdev = _RecursiveFindBD(parent_cdev)
1291 if parent_bdev is None:
1292 _Fail("Can't find parent device '%s' in add children", parent_cdev)
1293 new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1294 if new_bdevs.count(None) > 0:
1295 _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1296 parent_bdev.AddChildren(new_bdevs)
1299 def BlockdevRemovechildren(parent_cdev, new_cdevs):
1300 """Shrink a mirrored block device.
1302 @type parent_cdev: L{objects.Disk}
1303 @param parent_cdev: the disk from which we should remove children
1304 @type new_cdevs: list of L{objects.Disk}
1305 @param new_cdevs: the list of children which we should remove
1309 parent_bdev = _RecursiveFindBD(parent_cdev)
1310 if parent_bdev is None:
1311 _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1313 for disk in new_cdevs:
1314 rpath = disk.StaticDevPath()
1316 bd = _RecursiveFindBD(disk)
1318 _Fail("Can't find device %s while removing children", disk)
1320 devs.append(bd.dev_path)
1323 parent_bdev.RemoveChildren(devs)
1326 def BlockdevGetmirrorstatus(disks):
1327 """Get the mirroring status of a list of devices.
1329 @type disks: list of L{objects.Disk}
1330 @param disks: the list of disks which we should query
1333 a list of (mirror_done, estimated_time) tuples, which
1334 are the result of L{bdev.BlockDev.CombinedSyncStatus}
1335 @raise errors.BlockDeviceError: if any of the disks cannot be
1341 rbd = _RecursiveFindBD(dsk)
1343 _Fail("Can't find device %s", dsk)
1344 stats.append(rbd.CombinedSyncStatus())
1348 def _RecursiveFindBD(disk):
1349 """Check if a device is activated.
1351 If so, return information about the real device.
1353 @type disk: L{objects.Disk}
1354 @param disk: the disk object we need to find
1356 @return: None if the device can't be found,
1357 otherwise the device instance
1362 for chdisk in disk.children:
1363 children.append(_RecursiveFindBD(chdisk))
1365 return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1368 def BlockdevFind(disk):
1369 """Check if a device is activated.
1371 If it is, return information about the real device.
1373 @type disk: L{objects.Disk}
1374 @param disk: the disk to find
1375 @rtype: None or tuple
1376 @return: None if the disk cannot be found, otherwise a
1377 tuple (device_path, major, minor, sync_percent,
1378 estimated_time, is_degraded)
1382 rbd = _RecursiveFindBD(disk)
1383 except errors.BlockDeviceError, err:
1384 _Fail("Failed to find device: %s", err, exc=True)
1387 return (rbd.dev_path, rbd.major, rbd.minor) + rbd.GetSyncStatus()
1390 def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1391 """Write a file to the filesystem.
1393 This allows the master to overwrite(!) a file. It will only perform
1394 the operation if the file belongs to a list of configuration files.
1396 @type file_name: str
1397 @param file_name: the target file name
1399 @param data: the new contents of the file
1401 @param mode: the mode to give the file (can be None)
1403 @param uid: the owner of the file (can be -1 for default)
1405 @param gid: the group of the file (can be -1 for default)
1407 @param atime: the atime to set on the file (can be None)
1409 @param mtime: the mtime to set on the file (can be None)
1413 if not os.path.isabs(file_name):
1414 _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
1416 allowed_files = set([
1417 constants.CLUSTER_CONF_FILE,
1418 constants.ETC_HOSTS,
1419 constants.SSH_KNOWN_HOSTS_FILE,
1420 constants.VNC_PASSWORD_FILE,
1421 constants.RAPI_CERT_FILE,
1422 constants.RAPI_USERS_FILE,
1425 for hv_name in constants.HYPER_TYPES:
1426 hv_class = hypervisor.GetHypervisor(hv_name)
1427 allowed_files.update(hv_class.GetAncillaryFiles())
1429 if file_name not in allowed_files:
1430 _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
1433 raw_data = _Decompress(data)
1435 utils.WriteFile(file_name, data=raw_data, mode=mode, uid=uid, gid=gid,
1436 atime=atime, mtime=mtime)
1439 def WriteSsconfFiles(values):
1440 """Update all ssconf files.
1442 Wrapper around the SimpleStore.WriteFiles.
1445 ssconf.SimpleStore().WriteFiles(values)
1448 def _ErrnoOrStr(err):
1449 """Format an EnvironmentError exception.
1451 If the L{err} argument has an errno attribute, it will be looked up
1452 and converted into a textual C{E...} description. Otherwise the
1453 string representation of the error will be returned.
1455 @type err: L{EnvironmentError}
1456 @param err: the exception to format
1459 if hasattr(err, 'errno'):
1460 detail = errno.errorcode[err.errno]
1466 def _OSOndiskAPIVersion(name, os_dir):
1467 """Compute and return the API version of a given OS.
1469 This function will try to read the API version of the OS given by
1470 the 'name' parameter and residing in the 'os_dir' directory.
1473 @param name: the OS name we should look for
1475 @param os_dir: the directory inwhich we should look for the OS
1477 @return: tuple (status, data) with status denoting the validity and
1478 data holding either the vaid versions or an error message
1481 api_file = os.path.sep.join([os_dir, "ganeti_api_version"])
1484 st = os.stat(api_file)
1485 except EnvironmentError, err:
1486 return False, ("Required file 'ganeti_api_version' file not"
1487 " found under path %s: %s" % (os_dir, _ErrnoOrStr(err)))
1489 if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1490 return False, ("File 'ganeti_api_version' file at %s is not"
1491 " a regular file" % os_dir)
1494 api_versions = utils.ReadFile(api_file).splitlines()
1495 except EnvironmentError, err:
1496 return False, ("Error while reading the API version file at %s: %s" %
1497 (api_file, _ErrnoOrStr(err)))
1500 api_versions = [int(version.strip()) for version in api_versions]
1501 except (TypeError, ValueError), err:
1502 return False, ("API version(s) can't be converted to integer: %s" %
1505 return True, api_versions
1508 def DiagnoseOS(top_dirs=None):
1509 """Compute the validity for all OSes.
1511 @type top_dirs: list
1512 @param top_dirs: the list of directories in which to
1513 search (if not given defaults to
1514 L{constants.OS_SEARCH_PATH})
1515 @rtype: list of L{objects.OS}
1516 @return: a list of tuples (name, path, status, diagnose)
1517 for all (potential) OSes under all search paths, where:
1518 - name is the (potential) OS name
1519 - path is the full path to the OS
1520 - status True/False is the validity of the OS
1521 - diagnose is the error message for an invalid OS, otherwise empty
1524 if top_dirs is None:
1525 top_dirs = constants.OS_SEARCH_PATH
1528 for dir_name in top_dirs:
1529 if os.path.isdir(dir_name):
1531 f_names = utils.ListVisibleFiles(dir_name)
1532 except EnvironmentError, err:
1533 logging.exception("Can't list the OS directory %s: %s", dir_name, err)
1535 for name in f_names:
1536 os_path = os.path.sep.join([dir_name, name])
1537 status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
1542 result.append((name, os_path, status, diagnose))
1547 def _TryOSFromDisk(name, base_dir=None):
1548 """Create an OS instance from disk.
1550 This function will return an OS instance if the given name is a
1553 @type base_dir: string
1554 @keyword base_dir: Base directory containing OS installations.
1555 Defaults to a search in all the OS_SEARCH_PATH dirs.
1557 @return: success and either the OS instance if we find a valid one,
1561 if base_dir is None:
1562 os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1564 return False, "Directory for OS %s not found in search path" % name
1566 os_dir = os.path.sep.join([base_dir, name])
1568 status, api_versions = _OSOndiskAPIVersion(name, os_dir)
1571 return status, api_versions
1573 if not constants.OS_API_VERSIONS.intersection(api_versions):
1574 return False, ("API version mismatch for path '%s': found %s, want %s." %
1575 (os_dir, api_versions, constants.OS_API_VERSIONS))
1577 # OS Scripts dictionary, we will populate it with the actual script names
1578 os_scripts = dict.fromkeys(constants.OS_SCRIPTS)
1580 for script in os_scripts:
1581 os_scripts[script] = os.path.sep.join([os_dir, script])
1584 st = os.stat(os_scripts[script])
1585 except EnvironmentError, err:
1586 return False, ("Script '%s' under path '%s' is missing (%s)" %
1587 (script, os_dir, _ErrnoOrStr(err)))
1589 if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1590 return False, ("Script '%s' under path '%s' is not executable" %
1593 if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1594 return False, ("Script '%s' under path '%s' is not a regular file" %
1597 os_obj = objects.OS(name=name, path=os_dir,
1598 create_script=os_scripts[constants.OS_SCRIPT_CREATE],
1599 export_script=os_scripts[constants.OS_SCRIPT_EXPORT],
1600 import_script=os_scripts[constants.OS_SCRIPT_IMPORT],
1601 rename_script=os_scripts[constants.OS_SCRIPT_RENAME],
1602 api_versions=api_versions)
1606 def OSFromDisk(name, base_dir=None):
1607 """Create an OS instance from disk.
1609 This function will return an OS instance if the given name is a
1610 valid OS name. Otherwise, it will raise an appropriate
1611 L{RPCFail} exception, detailing why this is not a valid OS.
1613 This is just a wrapper over L{_TryOSFromDisk}, which doesn't raise
1614 an exception but returns true/false status data.
1616 @type base_dir: string
1617 @keyword base_dir: Base directory containing OS installations.
1618 Defaults to a search in all the OS_SEARCH_PATH dirs.
1619 @rtype: L{objects.OS}
1620 @return: the OS instance if we find a valid one
1621 @raise RPCFail: if we don't find a valid OS
1624 status, payload = _TryOSFromDisk(name, base_dir)
1632 def OSEnvironment(instance, os, debug=0):
1633 """Calculate the environment for an os script.
1635 @type instance: L{objects.Instance}
1636 @param instance: target instance for the os script run
1637 @type os: L{objects.OS}
1638 @param os: operating system for which the environment is being built
1639 @type debug: integer
1640 @param debug: debug level (0 or 1, for OS Api 10)
1642 @return: dict of environment variables
1643 @raise errors.BlockDeviceError: if the block device
1648 api_version = max(constants.OS_API_VERSIONS.intersection(os.api_versions))
1649 result['OS_API_VERSION'] = '%d' % api_version
1650 result['INSTANCE_NAME'] = instance.name
1651 result['INSTANCE_OS'] = instance.os
1652 result['HYPERVISOR'] = instance.hypervisor
1653 result['DISK_COUNT'] = '%d' % len(instance.disks)
1654 result['NIC_COUNT'] = '%d' % len(instance.nics)
1655 result['DEBUG_LEVEL'] = '%d' % debug
1656 for idx, disk in enumerate(instance.disks):
1657 real_disk = _RecursiveFindBD(disk)
1658 if real_disk is None:
1659 raise errors.BlockDeviceError("Block device '%s' is not set up" %
1662 result['DISK_%d_PATH' % idx] = real_disk.dev_path
1663 result['DISK_%d_ACCESS' % idx] = disk.mode
1664 if constants.HV_DISK_TYPE in instance.hvparams:
1665 result['DISK_%d_FRONTEND_TYPE' % idx] = \
1666 instance.hvparams[constants.HV_DISK_TYPE]
1667 if disk.dev_type in constants.LDS_BLOCK:
1668 result['DISK_%d_BACKEND_TYPE' % idx] = 'block'
1669 elif disk.dev_type == constants.LD_FILE:
1670 result['DISK_%d_BACKEND_TYPE' % idx] = \
1671 'file:%s' % disk.physical_id[0]
1672 for idx, nic in enumerate(instance.nics):
1673 result['NIC_%d_MAC' % idx] = nic.mac
1675 result['NIC_%d_IP' % idx] = nic.ip
1676 result['NIC_%d_MODE' % idx] = nic.nicparams[constants.NIC_MODE]
1677 if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
1678 result['NIC_%d_BRIDGE' % idx] = nic.nicparams[constants.NIC_LINK]
1679 if nic.nicparams[constants.NIC_LINK]:
1680 result['NIC_%d_LINK' % idx] = nic.nicparams[constants.NIC_LINK]
1681 if constants.HV_NIC_TYPE in instance.hvparams:
1682 result['NIC_%d_FRONTEND_TYPE' % idx] = \
1683 instance.hvparams[constants.HV_NIC_TYPE]
1685 for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
1686 for key, value in source.items():
1687 result["INSTANCE_%s_%s" % (kind, key)] = str(value)
1691 def BlockdevGrow(disk, amount):
1692 """Grow a stack of block devices.
1694 This function is called recursively, with the childrens being the
1695 first ones to resize.
1697 @type disk: L{objects.Disk}
1698 @param disk: the disk to be grown
1699 @rtype: (status, result)
1700 @return: a tuple with the status of the operation
1701 (True/False), and the errors message if status
1705 r_dev = _RecursiveFindBD(disk)
1707 _Fail("Cannot find block device %s", disk)
1711 except errors.BlockDeviceError, err:
1712 _Fail("Failed to grow block device: %s", err, exc=True)
1715 def BlockdevSnapshot(disk):
1716 """Create a snapshot copy of a block device.
1718 This function is called recursively, and the snapshot is actually created
1719 just for the leaf lvm backend device.
1721 @type disk: L{objects.Disk}
1722 @param disk: the disk to be snapshotted
1724 @return: snapshot disk path
1728 if len(disk.children) == 1:
1729 # only one child, let's recurse on it
1730 return BlockdevSnapshot(disk.children[0])
1732 # more than one child, choose one that matches
1733 for child in disk.children:
1734 if child.size == disk.size:
1735 # return implies breaking the loop
1736 return BlockdevSnapshot(child)
1737 elif disk.dev_type == constants.LD_LV:
1738 r_dev = _RecursiveFindBD(disk)
1739 if r_dev is not None:
1740 # let's stay on the safe side and ask for the full size, for now
1741 return r_dev.Snapshot(disk.size)
1743 _Fail("Cannot find block device %s", disk)
1745 _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
1746 disk.unique_id, disk.dev_type)
1749 def ExportSnapshot(disk, dest_node, instance, cluster_name, idx):
1750 """Export a block device snapshot to a remote node.
1752 @type disk: L{objects.Disk}
1753 @param disk: the description of the disk to export
1754 @type dest_node: str
1755 @param dest_node: the destination node to export to
1756 @type instance: L{objects.Instance}
1757 @param instance: the instance object to whom the disk belongs
1758 @type cluster_name: str
1759 @param cluster_name: the cluster name, needed for SSH hostalias
1761 @param idx: the index of the disk in the instance's disk list,
1762 used to export to the OS scripts environment
1766 inst_os = OSFromDisk(instance.os)
1767 export_env = OSEnvironment(instance, inst_os)
1769 export_script = inst_os.export_script
1771 logfile = "%s/exp-%s-%s-%s.log" % (constants.LOG_OS_DIR, inst_os.name,
1772 instance.name, int(time.time()))
1773 if not os.path.exists(constants.LOG_OS_DIR):
1774 os.mkdir(constants.LOG_OS_DIR, 0750)
1775 real_disk = _RecursiveFindBD(disk)
1776 if real_disk is None:
1777 _Fail("Block device '%s' is not set up", disk)
1781 export_env['EXPORT_DEVICE'] = real_disk.dev_path
1782 export_env['EXPORT_INDEX'] = str(idx)
1784 destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1785 destfile = disk.physical_id[1]
1787 # the target command is built out of three individual commands,
1788 # which are joined by pipes; we check each individual command for
1790 expcmd = utils.BuildShellCmd("cd %s; %s 2>%s", inst_os.path,
1791 export_script, logfile)
1795 destcmd = utils.BuildShellCmd("mkdir -p %s && cat > %s/%s",
1796 destdir, destdir, destfile)
1797 remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1798 constants.GANETI_RUNAS,
1801 # all commands have been checked, so we're safe to combine them
1802 command = '|'.join([expcmd, comprcmd, utils.ShellQuoteArgs(remotecmd)])
1804 result = utils.RunCmd(command, env=export_env)
1807 _Fail("OS snapshot export command '%s' returned error: %s"
1808 " output: %s", command, result.fail_reason, result.output)
1811 def FinalizeExport(instance, snap_disks):
1812 """Write out the export configuration information.
1814 @type instance: L{objects.Instance}
1815 @param instance: the instance which we export, used for
1816 saving configuration
1817 @type snap_disks: list of L{objects.Disk}
1818 @param snap_disks: list of snapshot block devices, which
1819 will be used to get the actual name of the dump file
1824 destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1825 finaldestdir = os.path.join(constants.EXPORT_DIR, instance.name)
1827 config = objects.SerializableConfigParser()
1829 config.add_section(constants.INISECT_EXP)
1830 config.set(constants.INISECT_EXP, 'version', '0')
1831 config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
1832 config.set(constants.INISECT_EXP, 'source', instance.primary_node)
1833 config.set(constants.INISECT_EXP, 'os', instance.os)
1834 config.set(constants.INISECT_EXP, 'compression', 'gzip')
1836 config.add_section(constants.INISECT_INS)
1837 config.set(constants.INISECT_INS, 'name', instance.name)
1838 config.set(constants.INISECT_INS, 'memory', '%d' %
1839 instance.beparams[constants.BE_MEMORY])
1840 config.set(constants.INISECT_INS, 'vcpus', '%d' %
1841 instance.beparams[constants.BE_VCPUS])
1842 config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
1845 for nic_count, nic in enumerate(instance.nics):
1847 config.set(constants.INISECT_INS, 'nic%d_mac' %
1848 nic_count, '%s' % nic.mac)
1849 config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
1850 config.set(constants.INISECT_INS, 'nic%d_bridge' % nic_count,
1852 # TODO: redundant: on load can read nics until it doesn't exist
1853 config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_total)
1856 for disk_count, disk in enumerate(snap_disks):
1859 config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
1860 ('%s' % disk.iv_name))
1861 config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
1862 ('%s' % disk.physical_id[1]))
1863 config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
1866 config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_total)
1868 utils.WriteFile(os.path.join(destdir, constants.EXPORT_CONF_FILE),
1869 data=config.Dumps())
1870 shutil.rmtree(finaldestdir, True)
1871 shutil.move(destdir, finaldestdir)
1874 def ExportInfo(dest):
1875 """Get export configuration information.
1878 @param dest: directory containing the export
1880 @rtype: L{objects.SerializableConfigParser}
1881 @return: a serializable config file containing the
1885 cff = os.path.join(dest, constants.EXPORT_CONF_FILE)
1887 config = objects.SerializableConfigParser()
1890 if (not config.has_section(constants.INISECT_EXP) or
1891 not config.has_section(constants.INISECT_INS)):
1892 _Fail("Export info file doesn't have the required fields")
1894 return config.Dumps()
1897 def ImportOSIntoInstance(instance, src_node, src_images, cluster_name):
1898 """Import an os image into an instance.
1900 @type instance: L{objects.Instance}
1901 @param instance: instance to import the disks into
1902 @type src_node: string
1903 @param src_node: source node for the disk images
1904 @type src_images: list of string
1905 @param src_images: absolute paths of the disk images
1906 @rtype: list of boolean
1907 @return: each boolean represent the success of importing the n-th disk
1910 inst_os = OSFromDisk(instance.os)
1911 import_env = OSEnvironment(instance, inst_os)
1912 import_script = inst_os.import_script
1914 logfile = "%s/import-%s-%s-%s.log" % (constants.LOG_OS_DIR, instance.os,
1915 instance.name, int(time.time()))
1916 if not os.path.exists(constants.LOG_OS_DIR):
1917 os.mkdir(constants.LOG_OS_DIR, 0750)
1920 impcmd = utils.BuildShellCmd("(cd %s; %s >%s 2>&1)", inst_os.path,
1921 import_script, logfile)
1924 for idx, image in enumerate(src_images):
1926 destcmd = utils.BuildShellCmd('cat %s', image)
1927 remotecmd = _GetSshRunner(cluster_name).BuildCmd(src_node,
1928 constants.GANETI_RUNAS,
1930 command = '|'.join([utils.ShellQuoteArgs(remotecmd), comprcmd, impcmd])
1931 import_env['IMPORT_DEVICE'] = import_env['DISK_%d_PATH' % idx]
1932 import_env['IMPORT_INDEX'] = str(idx)
1933 result = utils.RunCmd(command, env=import_env)
1935 logging.error("Disk import command '%s' returned error: %s"
1936 " output: %s", command, result.fail_reason,
1938 final_result.append("error importing disk %d: %s, %s" %
1939 (idx, result.fail_reason, result.output[-100]))
1942 _Fail("; ".join(final_result), log=False)
1946 """Return a list of exports currently available on this machine.
1949 @return: list of the exports
1952 if os.path.isdir(constants.EXPORT_DIR):
1953 return utils.ListVisibleFiles(constants.EXPORT_DIR)
1955 _Fail("No exports directory")
1958 def RemoveExport(export):
1959 """Remove an existing export from the node.
1962 @param export: the name of the export to remove
1966 target = os.path.join(constants.EXPORT_DIR, export)
1969 shutil.rmtree(target)
1970 except EnvironmentError, err:
1971 _Fail("Error while removing the export: %s", err, exc=True)
1974 def BlockdevRename(devlist):
1975 """Rename a list of block devices.
1977 @type devlist: list of tuples
1978 @param devlist: list of tuples of the form (disk,
1979 new_logical_id, new_physical_id); disk is an
1980 L{objects.Disk} object describing the current disk,
1981 and new logical_id/physical_id is the name we
1984 @return: True if all renames succeeded, False otherwise
1989 for disk, unique_id in devlist:
1990 dev = _RecursiveFindBD(disk)
1992 msgs.append("Can't find device %s in rename" % str(disk))
1996 old_rpath = dev.dev_path
1997 dev.Rename(unique_id)
1998 new_rpath = dev.dev_path
1999 if old_rpath != new_rpath:
2000 DevCacheManager.RemoveCache(old_rpath)
2001 # FIXME: we should add the new cache information here, like:
2002 # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2003 # but we don't have the owner here - maybe parse from existing
2004 # cache? for now, we only lose lvm data when we rename, which
2005 # is less critical than DRBD or MD
2006 except errors.BlockDeviceError, err:
2007 msgs.append("Can't rename device '%s' to '%s': %s" %
2008 (dev, unique_id, err))
2009 logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2012 _Fail("; ".join(msgs))
2015 def _TransformFileStorageDir(file_storage_dir):
2016 """Checks whether given file_storage_dir is valid.
2018 Checks wheter the given file_storage_dir is within the cluster-wide
2019 default file_storage_dir stored in SimpleStore. Only paths under that
2020 directory are allowed.
2022 @type file_storage_dir: str
2023 @param file_storage_dir: the path to check
2025 @return: the normalized path if valid, None otherwise
2029 file_storage_dir = os.path.normpath(file_storage_dir)
2030 base_file_storage_dir = cfg.GetFileStorageDir()
2031 if (not os.path.commonprefix([file_storage_dir, base_file_storage_dir]) ==
2032 base_file_storage_dir):
2033 _Fail("File storage directory '%s' is not under base file"
2034 " storage directory '%s'", file_storage_dir, base_file_storage_dir)
2035 return file_storage_dir
2038 def CreateFileStorageDir(file_storage_dir):
2039 """Create file storage directory.
2041 @type file_storage_dir: str
2042 @param file_storage_dir: directory to create
2045 @return: tuple with first element a boolean indicating wheter dir
2046 creation was successful or not
2049 file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2050 if os.path.exists(file_storage_dir):
2051 if not os.path.isdir(file_storage_dir):
2052 _Fail("Specified storage dir '%s' is not a directory",
2056 os.makedirs(file_storage_dir, 0750)
2057 except OSError, err:
2058 _Fail("Cannot create file storage directory '%s': %s",
2059 file_storage_dir, err, exc=True)
2062 def RemoveFileStorageDir(file_storage_dir):
2063 """Remove file storage directory.
2065 Remove it only if it's empty. If not log an error and return.
2067 @type file_storage_dir: str
2068 @param file_storage_dir: the directory we should cleanup
2069 @rtype: tuple (success,)
2070 @return: tuple of one element, C{success}, denoting
2071 whether the operation was successful
2074 file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2075 if os.path.exists(file_storage_dir):
2076 if not os.path.isdir(file_storage_dir):
2077 _Fail("Specified Storage directory '%s' is not a directory",
2079 # deletes dir only if empty, otherwise we want to fail the rpc call
2081 os.rmdir(file_storage_dir)
2082 except OSError, err:
2083 _Fail("Cannot remove file storage directory '%s': %s",
2084 file_storage_dir, err)
2087 def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2088 """Rename the file storage directory.
2090 @type old_file_storage_dir: str
2091 @param old_file_storage_dir: the current path
2092 @type new_file_storage_dir: str
2093 @param new_file_storage_dir: the name we should rename to
2094 @rtype: tuple (success,)
2095 @return: tuple of one element, C{success}, denoting
2096 whether the operation was successful
2099 old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2100 new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2101 if not os.path.exists(new_file_storage_dir):
2102 if os.path.isdir(old_file_storage_dir):
2104 os.rename(old_file_storage_dir, new_file_storage_dir)
2105 except OSError, err:
2106 _Fail("Cannot rename '%s' to '%s': %s",
2107 old_file_storage_dir, new_file_storage_dir, err)
2109 _Fail("Specified storage dir '%s' is not a directory",
2110 old_file_storage_dir)
2112 if os.path.exists(old_file_storage_dir):
2113 _Fail("Cannot rename '%s' to '%s': both locations exist",
2114 old_file_storage_dir, new_file_storage_dir)
2117 def _EnsureJobQueueFile(file_name):
2118 """Checks whether the given filename is in the queue directory.
2120 @type file_name: str
2121 @param file_name: the file name we should check
2123 @raises RPCFail: if the file is not valid
2126 queue_dir = os.path.normpath(constants.QUEUE_DIR)
2127 result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2130 _Fail("Passed job queue file '%s' does not belong to"
2131 " the queue directory '%s'", file_name, queue_dir)
2134 def JobQueueUpdate(file_name, content):
2135 """Updates a file in the queue directory.
2137 This is just a wrapper over L{utils.WriteFile}, with proper
2140 @type file_name: str
2141 @param file_name: the job file name
2143 @param content: the new job contents
2145 @return: the success of the operation
2148 _EnsureJobQueueFile(file_name)
2150 # Write and replace the file atomically
2151 utils.WriteFile(file_name, data=_Decompress(content))
2154 def JobQueueRename(old, new):
2155 """Renames a job queue file.
2157 This is just a wrapper over os.rename with proper checking.
2160 @param old: the old (actual) file name
2162 @param new: the desired file name
2164 @return: the success of the operation and payload
2167 _EnsureJobQueueFile(old)
2168 _EnsureJobQueueFile(new)
2170 utils.RenameFile(old, new, mkdir=True)
2173 def JobQueueSetDrainFlag(drain_flag):
2174 """Set the drain flag for the queue.
2176 This will set or unset the queue drain flag.
2178 @type drain_flag: boolean
2179 @param drain_flag: if True, will set the drain flag, otherwise reset it.
2181 @return: always True, None
2182 @warning: the function always returns True
2186 utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True)
2188 utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
2191 def BlockdevClose(instance_name, disks):
2192 """Closes the given block devices.
2194 This means they will be switched to secondary mode (in case of
2197 @param instance_name: if the argument is not empty, the symlinks
2198 of this instance will be removed
2199 @type disks: list of L{objects.Disk}
2200 @param disks: the list of disks to be closed
2201 @rtype: tuple (success, message)
2202 @return: a tuple of success and message, where success
2203 indicates the succes of the operation, and message
2204 which will contain the error details in case we
2210 rd = _RecursiveFindBD(cf)
2212 _Fail("Can't find device %s", cf)
2219 except errors.BlockDeviceError, err:
2220 msg.append(str(err))
2222 _Fail("Can't make devices secondary: %s", ",".join(msg))
2225 _RemoveBlockDevLinks(instance_name, disks)
2228 def ValidateHVParams(hvname, hvparams):
2229 """Validates the given hypervisor parameters.
2231 @type hvname: string
2232 @param hvname: the hypervisor name
2233 @type hvparams: dict
2234 @param hvparams: the hypervisor parameters to be validated
2239 hv_type = hypervisor.GetHypervisor(hvname)
2240 hv_type.ValidateParameters(hvparams)
2241 except errors.HypervisorError, err:
2242 _Fail(str(err), log=False)
2246 """Demotes the current node from master candidate role.
2249 # try to ensure we're not the master by mistake
2250 master, myself = ssconf.GetMasterAndMyself()
2251 if master == myself:
2252 _Fail("ssconf status shows I'm the master node, will not demote")
2253 pid_file = utils.DaemonPidFileName(constants.MASTERD_PID)
2254 if utils.IsProcessAlive(utils.ReadPidFile(pid_file)):
2255 _Fail("The master daemon is running, will not demote")
2257 if os.path.isfile(constants.CLUSTER_CONF_FILE):
2258 utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2259 except EnvironmentError, err:
2260 if err.errno != errno.ENOENT:
2261 _Fail("Error while backing up cluster file: %s", err, exc=True)
2262 utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2265 def _FindDisks(nodes_ip, disks):
2266 """Sets the physical ID on disks and returns the block devices.
2269 # set the correct physical ID
2270 my_name = utils.HostInfo().name
2272 cf.SetPhysicalID(my_name, nodes_ip)
2277 rd = _RecursiveFindBD(cf)
2279 _Fail("Can't find device %s", cf)
2284 def DrbdDisconnectNet(nodes_ip, disks):
2285 """Disconnects the network on a list of drbd devices.
2288 bdevs = _FindDisks(nodes_ip, disks)
2294 except errors.BlockDeviceError, err:
2295 _Fail("Can't change network configuration to standalone mode: %s",
2299 def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
2300 """Attaches the network on a list of drbd devices.
2303 bdevs = _FindDisks(nodes_ip, disks)
2306 for idx, rd in enumerate(bdevs):
2308 _SymlinkBlockDev(instance_name, rd.dev_path, idx)
2309 except EnvironmentError, err:
2310 _Fail("Can't create symlink: %s", err)
2311 # reconnect disks, switch to new master configuration and if
2312 # needed primary mode
2315 rd.AttachNet(multimaster)
2316 except errors.BlockDeviceError, err:
2317 _Fail("Can't change network configuration: %s", err)
2318 # wait until the disks are connected; we need to retry the re-attach
2319 # if the device becomes standalone, as this might happen if the one
2320 # node disconnects and reconnects in a different mode before the
2321 # other node reconnects; in this case, one or both of the nodes will
2322 # decide it has wrong configuration and switch to standalone
2323 RECONNECT_TIMEOUT = 2 * 60
2324 sleep_time = 0.100 # start with 100 miliseconds
2325 timeout_limit = time.time() + RECONNECT_TIMEOUT
2326 while time.time() < timeout_limit:
2327 all_connected = True
2329 stats = rd.GetProcStatus()
2330 if not (stats.is_connected or stats.is_in_resync):
2331 all_connected = False
2332 if stats.is_standalone:
2333 # peer had different config info and this node became
2334 # standalone, even though this should not happen with the
2335 # new staged way of changing disk configs
2337 rd.AttachNet(multimaster)
2338 except errors.BlockDeviceError, err:
2339 _Fail("Can't change network configuration: %s", err)
2342 time.sleep(sleep_time)
2343 sleep_time = min(5, sleep_time * 1.5)
2344 if not all_connected:
2345 _Fail("Timeout in disk reconnecting")
2347 # change to primary mode
2351 except errors.BlockDeviceError, err:
2352 _Fail("Can't change to primary mode: %s", err)
2355 def DrbdWaitSync(nodes_ip, disks):
2356 """Wait until DRBDs have synchronized.
2359 bdevs = _FindDisks(nodes_ip, disks)
2364 stats = rd.GetProcStatus()
2365 if not (stats.is_connected or stats.is_in_resync):
2366 _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
2367 alldone = alldone and (not stats.is_in_resync)
2368 if stats.sync_percent is not None:
2369 min_resync = min(min_resync, stats.sync_percent)
2371 return (alldone, min_resync)
2374 def PowercycleNode(hypervisor_type):
2375 """Hard-powercycle the node.
2377 Because we need to return first, and schedule the powercycle in the
2378 background, we won't be able to report failures nicely.
2381 hyper = hypervisor.GetHypervisor(hypervisor_type)
2385 # if we can't fork, we'll pretend that we're in the child process
2388 return "Reboot scheduled in 5 seconds"
2390 hyper.PowercycleNode()
2393 class HooksRunner(object):
2396 This class is instantiated on the node side (ganeti-noded) and not
2400 RE_MASK = re.compile("^[a-zA-Z0-9_-]+$")
2402 def __init__(self, hooks_base_dir=None):
2403 """Constructor for hooks runner.
2405 @type hooks_base_dir: str or None
2406 @param hooks_base_dir: if not None, this overrides the
2407 L{constants.HOOKS_BASE_DIR} (useful for unittests)
2410 if hooks_base_dir is None:
2411 hooks_base_dir = constants.HOOKS_BASE_DIR
2412 self._BASE_DIR = hooks_base_dir
2415 def ExecHook(script, env):
2416 """Exec one hook script.
2419 @param script: the full path to the script
2421 @param env: the environment with which to exec the script
2422 @rtype: tuple (success, message)
2423 @return: a tuple of success and message, where success
2424 indicates the succes of the operation, and message
2425 which will contain the error details in case we
2429 # exec the process using subprocess and log the output
2432 fdstdin = open("/dev/null", "r")
2433 child = subprocess.Popen([script], stdin=fdstdin, stdout=subprocess.PIPE,
2434 stderr=subprocess.STDOUT, close_fds=True,
2435 shell=False, cwd="/", env=env)
2438 output = child.stdout.read(4096)
2439 child.stdout.close()
2440 except EnvironmentError, err:
2441 output += "Hook script error: %s" % str(err)
2445 result = child.wait()
2447 except EnvironmentError, err:
2448 if err.errno == errno.EINTR:
2452 # try not to leak fds
2453 for fd in (fdstdin, ):
2457 except EnvironmentError, err:
2458 # just log the error
2459 #logging.exception("Error while closing fd %s", fd)
2462 return result == 0, utils.SafeEncode(output.strip())
2464 def RunHooks(self, hpath, phase, env):
2465 """Run the scripts in the hooks directory.
2468 @param hpath: the path to the hooks directory which
2471 @param phase: either L{constants.HOOKS_PHASE_PRE} or
2472 L{constants.HOOKS_PHASE_POST}
2474 @param env: dictionary with the environment for the hook
2476 @return: list of 3-element tuples:
2478 - script result, either L{constants.HKR_SUCCESS} or
2479 L{constants.HKR_FAIL}
2480 - output of the script
2482 @raise errors.ProgrammerError: for invalid input
2486 if phase == constants.HOOKS_PHASE_PRE:
2488 elif phase == constants.HOOKS_PHASE_POST:
2491 _Fail("Unknown hooks phase '%s'", phase)
2495 subdir = "%s-%s.d" % (hpath, suffix)
2496 dir_name = "%s/%s" % (self._BASE_DIR, subdir)
2498 dir_contents = utils.ListVisibleFiles(dir_name)
2500 # FIXME: must log output in case of failures
2503 # we use the standard python sort order,
2504 # so 00name is the recommended naming scheme
2506 for relname in dir_contents:
2507 fname = os.path.join(dir_name, relname)
2508 if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and
2509 self.RE_MASK.match(relname) is not None):
2510 rrval = constants.HKR_SKIP
2513 result, output = self.ExecHook(fname, env)
2515 rrval = constants.HKR_FAIL
2517 rrval = constants.HKR_SUCCESS
2518 rr.append(("%s/%s" % (subdir, relname), rrval, output))
2523 class IAllocatorRunner(object):
2524 """IAllocator runner.
2526 This class is instantiated on the node side (ganeti-noded) and not on
2530 def Run(self, name, idata):
2531 """Run an iallocator script.
2534 @param name: the iallocator script name
2536 @param idata: the allocator input data
2539 @return: two element tuple of:
2541 - either error message or stdout of allocator (for success)
2544 alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
2546 if alloc_script is None:
2547 _Fail("iallocator module '%s' not found in the search path", name)
2549 fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
2553 result = utils.RunCmd([alloc_script, fin_name])
2555 _Fail("iallocator module '%s' failed: %s, output '%s'",
2556 name, result.fail_reason, result.output)
2560 return result.stdout
2563 class DevCacheManager(object):
2564 """Simple class for managing a cache of block device information.
2567 _DEV_PREFIX = "/dev/"
2568 _ROOT_DIR = constants.BDEV_CACHE_DIR
2571 def _ConvertPath(cls, dev_path):
2572 """Converts a /dev/name path to the cache file name.
2574 This replaces slashes with underscores and strips the /dev
2575 prefix. It then returns the full path to the cache file.
2578 @param dev_path: the C{/dev/} path name
2580 @return: the converted path name
2583 if dev_path.startswith(cls._DEV_PREFIX):
2584 dev_path = dev_path[len(cls._DEV_PREFIX):]
2585 dev_path = dev_path.replace("/", "_")
2586 fpath = "%s/bdev_%s" % (cls._ROOT_DIR, dev_path)
2590 def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
2591 """Updates the cache information for a given device.
2594 @param dev_path: the pathname of the device
2596 @param owner: the owner (instance name) of the device
2597 @type on_primary: bool
2598 @param on_primary: whether this is the primary
2601 @param iv_name: the instance-visible name of the
2602 device, as in objects.Disk.iv_name
2607 if dev_path is None:
2608 logging.error("DevCacheManager.UpdateCache got a None dev_path")
2610 fpath = cls._ConvertPath(dev_path)
2616 iv_name = "not_visible"
2617 fdata = "%s %s %s\n" % (str(owner), state, iv_name)
2619 utils.WriteFile(fpath, data=fdata)
2620 except EnvironmentError, err:
2621 logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
2624 def RemoveCache(cls, dev_path):
2625 """Remove data for a dev_path.
2627 This is just a wrapper over L{utils.RemoveFile} with a converted
2628 path name and logging.
2631 @param dev_path: the pathname of the device
2636 if dev_path is None:
2637 logging.error("DevCacheManager.RemoveCache got a None dev_path")
2639 fpath = cls._ConvertPath(dev_path)
2641 utils.RemoveFile(fpath)
2642 except EnvironmentError, err:
2643 logging.exception("Can't update bdev cache for %s: %s", dev_path, err)