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
24 @var _ALLOWED_UPLOAD_FILES: denotes which files are accepted in
25 the L{UploadFile} function
29 # pylint: disable-msg=E1103
31 # E1103: %s %r has no %r member (but some types could not be
32 # inferred), because the _TryOSFromDisk returns either (True, os_obj)
33 # or (False, "string") which confuses pylint
49 from ganeti import errors
50 from ganeti import utils
51 from ganeti import ssh
52 from ganeti import hypervisor
53 from ganeti import constants
54 from ganeti import bdev
55 from ganeti import objects
56 from ganeti import ssconf
59 _BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id"
62 class RPCFail(Exception):
63 """Class denoting RPC failure.
65 Its argument is the error message.
70 def _Fail(msg, *args, **kwargs):
71 """Log an error and the raise an RPCFail exception.
73 This exception is then handled specially in the ganeti daemon and
74 turned into a 'failed' return type. As such, this function is a
75 useful shortcut for logging the error and returning it to the master
79 @param msg: the text of the exception
85 if "log" not in kwargs or kwargs["log"]: # if we should log this error
86 if "exc" in kwargs and kwargs["exc"]:
87 logging.exception(msg)
94 """Simple wrapper to return a SimpleStore.
96 @rtype: L{ssconf.SimpleStore}
97 @return: a SimpleStore instance
100 return ssconf.SimpleStore()
103 def _GetSshRunner(cluster_name):
104 """Simple wrapper to return an SshRunner.
106 @type cluster_name: str
107 @param cluster_name: the cluster name, which is needed
108 by the SshRunner constructor
109 @rtype: L{ssh.SshRunner}
110 @return: an SshRunner instance
113 return ssh.SshRunner(cluster_name)
116 def _Decompress(data):
117 """Unpacks data compressed by the RPC client.
119 @type data: list or tuple
120 @param data: Data sent by RPC client
122 @return: Decompressed data
125 assert isinstance(data, (list, tuple))
126 assert len(data) == 2
127 (encoding, content) = data
128 if encoding == constants.RPC_ENCODING_NONE:
130 elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
131 return zlib.decompress(base64.b64decode(content))
133 raise AssertionError("Unknown data encoding")
136 def _CleanDirectory(path, exclude=None):
137 """Removes all regular files in a directory.
140 @param path: the directory to clean
142 @param exclude: list of files to be excluded, defaults
146 if not os.path.isdir(path):
151 # Normalize excluded paths
152 exclude = [os.path.normpath(i) for i in exclude]
154 for rel_name in utils.ListVisibleFiles(path):
155 full_name = os.path.normpath(os.path.join(path, rel_name))
156 if full_name in exclude:
158 if os.path.isfile(full_name) and not os.path.islink(full_name):
159 utils.RemoveFile(full_name)
162 def _BuildUploadFileList():
163 """Build the list of allowed upload files.
165 This is abstracted so that it's built only once at module import time.
168 allowed_files = set([
169 constants.CLUSTER_CONF_FILE,
171 constants.SSH_KNOWN_HOSTS_FILE,
172 constants.VNC_PASSWORD_FILE,
173 constants.RAPI_CERT_FILE,
174 constants.RAPI_USERS_FILE,
175 constants.HMAC_CLUSTER_KEY,
178 for hv_name in constants.HYPER_TYPES:
179 hv_class = hypervisor.GetHypervisorClass(hv_name)
180 allowed_files.update(hv_class.GetAncillaryFiles())
182 return frozenset(allowed_files)
185 _ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
189 """Removes job queue files and archived jobs.
195 _CleanDirectory(constants.QUEUE_DIR, exclude=[constants.JOB_QUEUE_LOCK_FILE])
196 _CleanDirectory(constants.JOB_QUEUE_ARCHIVE_DIR)
200 """Returns master information.
202 This is an utility function to compute master information, either
203 for consumption here or from the node daemon.
206 @return: master_netdev, master_ip, master_name
207 @raise RPCFail: in case of errors
212 master_netdev = cfg.GetMasterNetdev()
213 master_ip = cfg.GetMasterIP()
214 master_node = cfg.GetMasterNode()
215 except errors.ConfigurationError, err:
216 _Fail("Cluster configuration incomplete: %s", err, exc=True)
217 return (master_netdev, master_ip, master_node)
220 def StartMaster(start_daemons, no_voting):
221 """Activate local node as master node.
223 The function will always try activate the IP address of the master
224 (unless someone else has it). It will also start the master daemons,
225 based on the start_daemons parameter.
227 @type start_daemons: boolean
228 @param start_daemons: whether to also start the master
229 daemons (ganeti-masterd and ganeti-rapi)
230 @type no_voting: boolean
231 @param no_voting: whether to start ganeti-masterd without a node vote
232 (if start_daemons is True), but still non-interactively
236 # GetMasterInfo will raise an exception if not able to return data
237 master_netdev, master_ip, _ = GetMasterInfo()
240 if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
241 if utils.OwnIpAddress(master_ip):
242 # we already have the ip:
243 logging.debug("Master IP already configured, doing nothing")
245 msg = "Someone else has the master ip, not activating"
249 result = utils.RunCmd(["ip", "address", "add", "%s/32" % master_ip,
250 "dev", master_netdev, "label",
251 "%s:0" % master_netdev])
253 msg = "Can't activate master IP: %s" % result.output
257 result = utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev,
258 "-s", master_ip, master_ip])
259 # we'll ignore the exit code of arping
261 # and now start the master and rapi daemons
264 masterd_args = "--no-voting --yes-do-it"
269 "EXTRA_MASTERD_ARGS": masterd_args,
272 result = utils.RunCmd([constants.DAEMON_UTIL, "start-master"], env=env)
274 msg = "Can't start Ganeti master: %s" % result.output
279 _Fail("; ".join(err_msgs))
282 def StopMaster(stop_daemons):
283 """Deactivate this node as master.
285 The function will always try to deactivate the IP address of the
286 master. It will also stop the master daemons depending on the
287 stop_daemons parameter.
289 @type stop_daemons: boolean
290 @param stop_daemons: whether to also stop the master daemons
291 (ganeti-masterd and ganeti-rapi)
295 # TODO: log and report back to the caller the error failures; we
296 # need to decide in which case we fail the RPC for this
298 # GetMasterInfo will raise an exception if not able to return data
299 master_netdev, master_ip, _ = GetMasterInfo()
301 result = utils.RunCmd(["ip", "address", "del", "%s/32" % master_ip,
302 "dev", master_netdev])
304 logging.error("Can't remove the master IP, error: %s", result.output)
305 # but otherwise ignore the failure
308 result = utils.RunCmd([constants.DAEMON_UTIL, "stop-master"])
310 logging.error("Could not stop Ganeti master, command %s had exitcode %s"
312 result.cmd, result.exit_code, result.output)
315 def AddNode(dsa, dsapub, rsa, rsapub, sshkey, sshpub):
316 """Joins this node to the cluster.
318 This does the following:
319 - updates the hostkeys of the machine (rsa and dsa)
320 - adds the ssh private key to the user
321 - adds the ssh public key to the users' authorized_keys file
324 @param dsa: the DSA private key to write
326 @param dsapub: the DSA public key to write
328 @param rsa: the RSA private key to write
330 @param rsapub: the RSA public key to write
332 @param sshkey: the SSH private key to write
334 @param sshpub: the SSH public key to write
336 @return: the success of the operation
339 sshd_keys = [(constants.SSH_HOST_RSA_PRIV, rsa, 0600),
340 (constants.SSH_HOST_RSA_PUB, rsapub, 0644),
341 (constants.SSH_HOST_DSA_PRIV, dsa, 0600),
342 (constants.SSH_HOST_DSA_PUB, dsapub, 0644)]
343 for name, content, mode in sshd_keys:
344 utils.WriteFile(name, data=content, mode=mode)
347 priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS,
349 except errors.OpExecError, err:
350 _Fail("Error while processing user ssh files: %s", err, exc=True)
352 for name, content in [(priv_key, sshkey), (pub_key, sshpub)]:
353 utils.WriteFile(name, data=content, mode=0600)
355 utils.AddAuthorizedKey(auth_keys, sshpub)
357 result = utils.RunCmd([constants.DAEMON_UTIL, "reload-ssh-keys"])
359 _Fail("Unable to reload SSH keys (command %r, exit code %s, output %r)",
360 result.cmd, result.exit_code, result.output)
363 def LeaveCluster(modify_ssh_setup):
364 """Cleans up and remove the current node.
366 This function cleans up and prepares the current node to be removed
369 If processing is successful, then it raises an
370 L{errors.QuitGanetiException} which is used as a special case to
371 shutdown the node daemon.
373 @param modify_ssh_setup: boolean
376 _CleanDirectory(constants.DATA_DIR)
381 priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
383 utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
385 utils.RemoveFile(priv_key)
386 utils.RemoveFile(pub_key)
387 except errors.OpExecError:
388 logging.exception("Error while processing ssh files")
391 utils.RemoveFile(constants.HMAC_CLUSTER_KEY)
392 utils.RemoveFile(constants.RAPI_CERT_FILE)
393 utils.RemoveFile(constants.SSL_CERT_FILE)
394 except: # pylint: disable-msg=W0702
395 logging.exception("Error while removing cluster secrets")
397 result = utils.RunCmd([constants.DAEMON_UTIL, "stop", constants.CONFD])
399 logging.error("Command %s failed with exitcode %s and error %s",
400 result.cmd, result.exit_code, result.output)
402 # Raise a custom exception (handled in ganeti-noded)
403 raise errors.QuitGanetiException(True, 'Shutdown scheduled')
406 def GetNodeInfo(vgname, hypervisor_type):
407 """Gives back a hash with different information about the node.
409 @type vgname: C{string}
410 @param vgname: the name of the volume group to ask for disk space information
411 @type hypervisor_type: C{str}
412 @param hypervisor_type: the name of the hypervisor to ask for
415 @return: dictionary with the following keys:
416 - vg_size is the size of the configured volume group in MiB
417 - vg_free is the free size of the volume group in MiB
418 - memory_dom0 is the memory allocated for domain0 in MiB
419 - memory_free is the currently available (free) ram in MiB
420 - memory_total is the total number of ram in MiB
424 vginfo = _GetVGInfo(vgname)
425 outputarray['vg_size'] = vginfo['vg_size']
426 outputarray['vg_free'] = vginfo['vg_free']
428 hyper = hypervisor.GetHypervisor(hypervisor_type)
429 hyp_info = hyper.GetNodeInfo()
430 if hyp_info is not None:
431 outputarray.update(hyp_info)
433 outputarray["bootid"] = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
438 def VerifyNode(what, cluster_name):
439 """Verify the status of the local node.
441 Based on the input L{what} parameter, various checks are done on the
444 If the I{filelist} key is present, this list of
445 files is checksummed and the file/checksum pairs are returned.
447 If the I{nodelist} key is present, we check that we have
448 connectivity via ssh with the target nodes (and check the hostname
451 If the I{node-net-test} key is present, we check that we have
452 connectivity to the given nodes via both primary IP and, if
453 applicable, secondary IPs.
456 @param what: a dictionary of things to check:
457 - filelist: list of files for which to compute checksums
458 - nodelist: list of nodes we should check ssh communication with
459 - node-net-test: list of nodes we should check node daemon port
461 - hypervisor: list with hypervisors to run the verify for
463 @return: a dictionary with the same keys as the input dict, and
464 values representing the result of the checks
469 if constants.NV_HYPERVISOR in what:
470 result[constants.NV_HYPERVISOR] = tmp = {}
471 for hv_name in what[constants.NV_HYPERVISOR]:
472 tmp[hv_name] = hypervisor.GetHypervisor(hv_name).Verify()
474 if constants.NV_FILELIST in what:
475 result[constants.NV_FILELIST] = utils.FingerprintFiles(
476 what[constants.NV_FILELIST])
478 if constants.NV_NODELIST in what:
479 result[constants.NV_NODELIST] = tmp = {}
480 random.shuffle(what[constants.NV_NODELIST])
481 for node in what[constants.NV_NODELIST]:
482 success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
486 if constants.NV_NODENETTEST in what:
487 result[constants.NV_NODENETTEST] = tmp = {}
488 my_name = utils.HostInfo().name
489 my_pip = my_sip = None
490 for name, pip, sip in what[constants.NV_NODENETTEST]:
496 tmp[my_name] = ("Can't find my own primary/secondary IP"
499 port = utils.GetDaemonPort(constants.NODED)
500 for name, pip, sip in what[constants.NV_NODENETTEST]:
502 if not utils.TcpPing(pip, port, source=my_pip):
503 fail.append("primary")
505 if not utils.TcpPing(sip, port, source=my_sip):
506 fail.append("secondary")
508 tmp[name] = ("failure using the %s interface(s)" %
511 if constants.NV_LVLIST in what:
512 result[constants.NV_LVLIST] = GetVolumeList(what[constants.NV_LVLIST])
514 if constants.NV_INSTANCELIST in what:
515 result[constants.NV_INSTANCELIST] = GetInstanceList(
516 what[constants.NV_INSTANCELIST])
518 if constants.NV_VGLIST in what:
519 result[constants.NV_VGLIST] = utils.ListVolumeGroups()
521 if constants.NV_PVLIST in what:
522 result[constants.NV_PVLIST] = \
523 bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
524 filter_allocatable=False)
526 if constants.NV_VERSION in what:
527 result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
528 constants.RELEASE_VERSION)
530 if constants.NV_HVINFO in what:
531 hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
532 result[constants.NV_HVINFO] = hyper.GetNodeInfo()
534 if constants.NV_DRBDLIST in what:
536 used_minors = bdev.DRBD8.GetUsedDevs().keys()
537 except errors.BlockDeviceError, err:
538 logging.warning("Can't get used minors list", exc_info=True)
539 used_minors = str(err)
540 result[constants.NV_DRBDLIST] = used_minors
542 if constants.NV_NODESETUP in what:
543 result[constants.NV_NODESETUP] = tmpr = []
544 if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
545 tmpr.append("The sysfs filesytem doesn't seem to be mounted"
546 " under /sys, missing required directories /sys/block"
547 " and /sys/class/net")
548 if (not os.path.isdir("/proc/sys") or
549 not os.path.isfile("/proc/sysrq-trigger")):
550 tmpr.append("The procfs filesystem doesn't seem to be mounted"
551 " under /proc, missing required directory /proc/sys and"
552 " the file /proc/sysrq-trigger")
554 if constants.NV_TIME in what:
555 result[constants.NV_TIME] = utils.SplitTime(time.time())
560 def GetVolumeList(vg_name):
561 """Compute list of logical volumes and their size.
564 @param vg_name: the volume group whose LVs we should list
567 dictionary of all partions (key) with value being a tuple of
568 their size (in MiB), inactive and online status::
570 {'test1': ('20.06', True, True)}
572 in case of errors, a string is returned with the error
578 result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
579 "--separator=%s" % sep,
580 "-olv_name,lv_size,lv_attr", vg_name])
582 _Fail("Failed to list logical volumes, lvs output: %s", result.output)
584 valid_line_re = re.compile("^ *([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
585 for line in result.stdout.splitlines():
587 match = valid_line_re.match(line)
589 logging.error("Invalid line returned from lvs output: '%s'", line)
591 name, size, attr = match.groups()
592 inactive = attr[4] == '-'
593 online = attr[5] == 'o'
594 virtual = attr[0] == 'v'
596 # we don't want to report such volumes as existing, since they
597 # don't really hold data
599 lvs[name] = (size, inactive, online)
604 def ListVolumeGroups():
605 """List the volume groups and their size.
608 @return: dictionary with keys volume name and values the
612 return utils.ListVolumeGroups()
616 """List all volumes on this node.
620 A list of dictionaries, each having four keys:
621 - name: the logical volume name,
622 - size: the size of the logical volume
623 - dev: the physical device on which the LV lives
624 - vg: the volume group to which it belongs
626 In case of errors, we return an empty list and log the
629 Note that since a logical volume can live on multiple physical
630 volumes, the resulting list might include a logical volume
634 result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
636 "--options=lv_name,lv_size,devices,vg_name"])
638 _Fail("Failed to list logical volumes, lvs output: %s",
643 return dev.split('(')[0]
649 'name': line[0].strip(),
650 'size': line[1].strip(),
651 'dev': parse_dev(line[2].strip()),
652 'vg': line[3].strip(),
655 return [map_line(line.split('|')) for line in result.stdout.splitlines()
656 if line.count('|') >= 3]
659 def BridgesExist(bridges_list):
660 """Check if a list of bridges exist on the current node.
663 @return: C{True} if all of them exist, C{False} otherwise
667 for bridge in bridges_list:
668 if not utils.BridgeExists(bridge):
669 missing.append(bridge)
672 _Fail("Missing bridges %s", utils.CommaJoin(missing))
675 def GetInstanceList(hypervisor_list):
676 """Provides a list of instances.
678 @type hypervisor_list: list
679 @param hypervisor_list: the list of hypervisors to query information
682 @return: a list of all running instances on the current node
683 - instance1.example.com
684 - instance2.example.com
688 for hname in hypervisor_list:
690 names = hypervisor.GetHypervisor(hname).ListInstances()
691 results.extend(names)
692 except errors.HypervisorError, err:
693 _Fail("Error enumerating instances (hypervisor %s): %s",
694 hname, err, exc=True)
699 def GetInstanceInfo(instance, hname):
700 """Gives back the information about an instance as a dictionary.
702 @type instance: string
703 @param instance: the instance name
705 @param hname: the hypervisor type of the instance
708 @return: dictionary with the following keys:
709 - memory: memory size of instance (int)
710 - state: xen state of instance (string)
711 - time: cpu time of instance (float)
716 iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
717 if iinfo is not None:
718 output['memory'] = iinfo[2]
719 output['state'] = iinfo[4]
720 output['time'] = iinfo[5]
725 def GetInstanceMigratable(instance):
726 """Gives whether an instance can be migrated.
728 @type instance: L{objects.Instance}
729 @param instance: object representing the instance to be checked.
732 @return: tuple of (result, description) where:
733 - result: whether the instance can be migrated or not
734 - description: a description of the issue, if relevant
737 hyper = hypervisor.GetHypervisor(instance.hypervisor)
738 iname = instance.name
739 if iname not in hyper.ListInstances():
740 _Fail("Instance %s is not running", iname)
742 for idx in range(len(instance.disks)):
743 link_name = _GetBlockDevSymlinkPath(iname, idx)
744 if not os.path.islink(link_name):
745 _Fail("Instance %s was not restarted since ganeti 1.2.5", iname)
748 def GetAllInstancesInfo(hypervisor_list):
749 """Gather data about all instances.
751 This is the equivalent of L{GetInstanceInfo}, except that it
752 computes data for all instances at once, thus being faster if one
753 needs data about more than one instance.
755 @type hypervisor_list: list
756 @param hypervisor_list: list of hypervisors to query for instance data
759 @return: dictionary of instance: data, with data having the following keys:
760 - memory: memory size of instance (int)
761 - state: xen state of instance (string)
762 - time: cpu time of instance (float)
763 - vcpus: the number of vcpus
768 for hname in hypervisor_list:
769 iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
771 for name, _, memory, vcpus, state, times in iinfo:
779 # we only check static parameters, like memory and vcpus,
780 # and not state and time which can change between the
781 # invocations of the different hypervisors
782 for key in 'memory', 'vcpus':
783 if value[key] != output[name][key]:
784 _Fail("Instance %s is running twice"
785 " with different parameters", name)
791 def InstanceOsAdd(instance, reinstall, debug):
792 """Add an OS to an instance.
794 @type instance: L{objects.Instance}
795 @param instance: Instance whose OS is to be installed
796 @type reinstall: boolean
797 @param reinstall: whether this is an instance reinstall
799 @param debug: debug level, passed to the OS scripts
803 inst_os = OSFromDisk(instance.os)
805 create_env = OSEnvironment(instance, inst_os, debug)
807 create_env['INSTANCE_REINSTALL'] = "1"
809 logfile = "%s/add-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
810 instance.name, int(time.time()))
812 result = utils.RunCmd([inst_os.create_script], env=create_env,
813 cwd=inst_os.path, output=logfile,)
815 logging.error("os create command '%s' returned error: %s, logfile: %s,"
816 " output: %s", result.cmd, result.fail_reason, logfile,
818 lines = [utils.SafeEncode(val)
819 for val in utils.TailFile(logfile, lines=20)]
820 _Fail("OS create script failed (%s), last lines in the"
821 " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
824 def RunRenameInstance(instance, old_name, debug):
825 """Run the OS rename script for an instance.
827 @type instance: L{objects.Instance}
828 @param instance: Instance whose OS is to be installed
829 @type old_name: string
830 @param old_name: previous instance name
832 @param debug: debug level, passed to the OS scripts
834 @return: the success of the operation
837 inst_os = OSFromDisk(instance.os)
839 rename_env = OSEnvironment(instance, inst_os, debug)
840 rename_env['OLD_INSTANCE_NAME'] = old_name
842 logfile = "%s/rename-%s-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
844 instance.name, int(time.time()))
846 result = utils.RunCmd([inst_os.rename_script], env=rename_env,
847 cwd=inst_os.path, output=logfile)
850 logging.error("os create command '%s' returned error: %s output: %s",
851 result.cmd, result.fail_reason, result.output)
852 lines = [utils.SafeEncode(val)
853 for val in utils.TailFile(logfile, lines=20)]
854 _Fail("OS rename script failed (%s), last lines in the"
855 " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
858 def _GetVGInfo(vg_name):
859 """Get information about the volume group.
862 @param vg_name: the volume group which we query
865 A dictionary with the following keys:
866 - C{vg_size} is the total size of the volume group in MiB
867 - C{vg_free} is the free size of the volume group in MiB
868 - C{pv_count} are the number of physical disks in that VG
870 If an error occurs during gathering of data, we return the same dict
871 with keys all set to None.
874 retdic = dict.fromkeys(["vg_size", "vg_free", "pv_count"])
876 retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings",
877 "--nosuffix", "--units=m", "--separator=:", vg_name])
880 logging.error("volume group %s not present", vg_name)
882 valarr = retval.stdout.strip().rstrip(':').split(':')
886 "vg_size": int(round(float(valarr[0]), 0)),
887 "vg_free": int(round(float(valarr[1]), 0)),
888 "pv_count": int(valarr[2]),
890 except (TypeError, ValueError), err:
891 logging.exception("Fail to parse vgs output: %s", err)
893 logging.error("vgs output has the wrong number of fields (expected"
894 " three): %s", str(valarr))
898 def _GetBlockDevSymlinkPath(instance_name, idx):
899 return os.path.join(constants.DISK_LINKS_DIR,
900 "%s:%d" % (instance_name, idx))
903 def _SymlinkBlockDev(instance_name, device_path, idx):
904 """Set up symlinks to a instance's block device.
906 This is an auxiliary function run when an instance is start (on the primary
907 node) or when an instance is migrated (on the target node).
910 @param instance_name: the name of the target instance
911 @param device_path: path of the physical block device, on the node
912 @param idx: the disk index
913 @return: absolute path to the disk's symlink
916 link_name = _GetBlockDevSymlinkPath(instance_name, idx)
918 os.symlink(device_path, link_name)
920 if err.errno == errno.EEXIST:
921 if (not os.path.islink(link_name) or
922 os.readlink(link_name) != device_path):
924 os.symlink(device_path, link_name)
931 def _RemoveBlockDevLinks(instance_name, disks):
932 """Remove the block device symlinks belonging to the given instance.
935 for idx, _ in enumerate(disks):
936 link_name = _GetBlockDevSymlinkPath(instance_name, idx)
937 if os.path.islink(link_name):
941 logging.exception("Can't remove symlink '%s'", link_name)
944 def _GatherAndLinkBlockDevs(instance):
945 """Set up an instance's block device(s).
947 This is run on the primary node at instance startup. The block
948 devices must be already assembled.
950 @type instance: L{objects.Instance}
951 @param instance: the instance whose disks we shoul assemble
953 @return: list of (disk_object, device_path)
957 for idx, disk in enumerate(instance.disks):
958 device = _RecursiveFindBD(disk)
960 raise errors.BlockDeviceError("Block device '%s' is not set up." %
964 link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
966 raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
969 block_devices.append((disk, link_name))
974 def StartInstance(instance):
975 """Start an instance.
977 @type instance: L{objects.Instance}
978 @param instance: the instance object
982 running_instances = GetInstanceList([instance.hypervisor])
984 if instance.name in running_instances:
985 logging.info("Instance %s already running, not starting", instance.name)
989 block_devices = _GatherAndLinkBlockDevs(instance)
990 hyper = hypervisor.GetHypervisor(instance.hypervisor)
991 hyper.StartInstance(instance, block_devices)
992 except errors.BlockDeviceError, err:
993 _Fail("Block device error: %s", err, exc=True)
994 except errors.HypervisorError, err:
995 _RemoveBlockDevLinks(instance.name, instance.disks)
996 _Fail("Hypervisor error: %s", err, exc=True)
999 def InstanceShutdown(instance, timeout):
1000 """Shut an instance down.
1002 @note: this functions uses polling with a hardcoded timeout.
1004 @type instance: L{objects.Instance}
1005 @param instance: the instance object
1006 @type timeout: integer
1007 @param timeout: maximum timeout for soft shutdown
1011 hv_name = instance.hypervisor
1012 hyper = hypervisor.GetHypervisor(hv_name)
1013 iname = instance.name
1015 if instance.name not in hyper.ListInstances():
1016 logging.info("Instance %s not running, doing nothing", iname)
1021 self.tried_once = False
1024 if iname not in hyper.ListInstances():
1028 hyper.StopInstance(instance, retry=self.tried_once)
1029 except errors.HypervisorError, err:
1030 if iname not in hyper.ListInstances():
1031 # if the instance is no longer existing, consider this a
1032 # success and go to cleanup
1035 _Fail("Failed to stop instance %s: %s", iname, err)
1037 self.tried_once = True
1039 raise utils.RetryAgain()
1042 utils.Retry(_TryShutdown(), 5, timeout)
1043 except utils.RetryTimeout:
1044 # the shutdown did not succeed
1045 logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1048 hyper.StopInstance(instance, force=True)
1049 except errors.HypervisorError, err:
1050 if iname in hyper.ListInstances():
1051 # only raise an error if the instance still exists, otherwise
1052 # the error could simply be "instance ... unknown"!
1053 _Fail("Failed to force stop instance %s: %s", iname, err)
1057 if iname in hyper.ListInstances():
1058 _Fail("Could not shutdown instance %s even by destroy", iname)
1060 _RemoveBlockDevLinks(iname, instance.disks)
1063 def InstanceReboot(instance, reboot_type, shutdown_timeout):
1064 """Reboot an instance.
1066 @type instance: L{objects.Instance}
1067 @param instance: the instance object to reboot
1068 @type reboot_type: str
1069 @param reboot_type: the type of reboot, one the following
1071 - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1072 instance OS, do not recreate the VM
1073 - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1074 restart the VM (at the hypervisor level)
1075 - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1076 not accepted here, since that mode is handled differently, in
1077 cmdlib, and translates into full stop and start of the
1078 instance (instead of a call_instance_reboot RPC)
1079 @type shutdown_timeout: integer
1080 @param shutdown_timeout: maximum timeout for soft shutdown
1084 running_instances = GetInstanceList([instance.hypervisor])
1086 if instance.name not in running_instances:
1087 _Fail("Cannot reboot instance %s that is not running", instance.name)
1089 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1090 if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1092 hyper.RebootInstance(instance)
1093 except errors.HypervisorError, err:
1094 _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1095 elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1097 InstanceShutdown(instance, shutdown_timeout)
1098 return StartInstance(instance)
1099 except errors.HypervisorError, err:
1100 _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1102 _Fail("Invalid reboot_type received: %s", reboot_type)
1105 def MigrationInfo(instance):
1106 """Gather information about an instance to be migrated.
1108 @type instance: L{objects.Instance}
1109 @param instance: the instance definition
1112 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1114 info = hyper.MigrationInfo(instance)
1115 except errors.HypervisorError, err:
1116 _Fail("Failed to fetch migration information: %s", err, exc=True)
1120 def AcceptInstance(instance, info, target):
1121 """Prepare the node to accept an instance.
1123 @type instance: L{objects.Instance}
1124 @param instance: the instance definition
1125 @type info: string/data (opaque)
1126 @param info: migration information, from the source node
1127 @type target: string
1128 @param target: target host (usually ip), on this node
1131 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1133 hyper.AcceptInstance(instance, info, target)
1134 except errors.HypervisorError, err:
1135 _Fail("Failed to accept instance: %s", err, exc=True)
1138 def FinalizeMigration(instance, info, success):
1139 """Finalize any preparation to accept an instance.
1141 @type instance: L{objects.Instance}
1142 @param instance: the instance definition
1143 @type info: string/data (opaque)
1144 @param info: migration information, from the source node
1145 @type success: boolean
1146 @param success: whether the migration was a success or a failure
1149 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1151 hyper.FinalizeMigration(instance, info, success)
1152 except errors.HypervisorError, err:
1153 _Fail("Failed to finalize migration: %s", err, exc=True)
1156 def MigrateInstance(instance, target, live):
1157 """Migrates an instance to another node.
1159 @type instance: L{objects.Instance}
1160 @param instance: the instance definition
1161 @type target: string
1162 @param target: the target node name
1164 @param live: whether the migration should be done live or not (the
1165 interpretation of this parameter is left to the hypervisor)
1167 @return: a tuple of (success, msg) where:
1168 - succes is a boolean denoting the success/failure of the operation
1169 - msg is a string with details in case of failure
1172 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1175 hyper.MigrateInstance(instance, target, live)
1176 except errors.HypervisorError, err:
1177 _Fail("Failed to migrate instance: %s", err, exc=True)
1180 def BlockdevCreate(disk, size, owner, on_primary, info):
1181 """Creates a block device for an instance.
1183 @type disk: L{objects.Disk}
1184 @param disk: the object describing the disk we should create
1186 @param size: the size of the physical underlying device, in MiB
1188 @param owner: the name of the instance for which disk is created,
1189 used for device cache data
1190 @type on_primary: boolean
1191 @param on_primary: indicates if it is the primary node or not
1193 @param info: string that will be sent to the physical device
1194 creation, used for example to set (LVM) tags on LVs
1196 @return: the new unique_id of the device (this can sometime be
1197 computed only after creation), or None. On secondary nodes,
1198 it's not required to return anything.
1201 # TODO: remove the obsolete 'size' argument
1202 # pylint: disable-msg=W0613
1205 for child in disk.children:
1207 crdev = _RecursiveAssembleBD(child, owner, on_primary)
1208 except errors.BlockDeviceError, err:
1209 _Fail("Can't assemble device %s: %s", child, err)
1210 if on_primary or disk.AssembleOnSecondary():
1211 # we need the children open in case the device itself has to
1214 # pylint: disable-msg=E1103
1216 except errors.BlockDeviceError, err:
1217 _Fail("Can't make child '%s' read-write: %s", child, err)
1221 device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
1222 except errors.BlockDeviceError, err:
1223 _Fail("Can't create block device: %s", err)
1225 if on_primary or disk.AssembleOnSecondary():
1228 except errors.BlockDeviceError, err:
1229 _Fail("Can't assemble device after creation, unusual event: %s", err)
1230 device.SetSyncSpeed(constants.SYNC_SPEED)
1231 if on_primary or disk.OpenOnSecondary():
1233 device.Open(force=True)
1234 except errors.BlockDeviceError, err:
1235 _Fail("Can't make device r/w after creation, unusual event: %s", err)
1236 DevCacheManager.UpdateCache(device.dev_path, owner,
1237 on_primary, disk.iv_name)
1239 device.SetInfo(info)
1241 return device.unique_id
1244 def BlockdevRemove(disk):
1245 """Remove a block device.
1247 @note: This is intended to be called recursively.
1249 @type disk: L{objects.Disk}
1250 @param disk: the disk object we should remove
1252 @return: the success of the operation
1257 rdev = _RecursiveFindBD(disk)
1258 except errors.BlockDeviceError, err:
1259 # probably can't attach
1260 logging.info("Can't attach to device %s in remove", disk)
1262 if rdev is not None:
1263 r_path = rdev.dev_path
1266 except errors.BlockDeviceError, err:
1267 msgs.append(str(err))
1269 DevCacheManager.RemoveCache(r_path)
1272 for child in disk.children:
1274 BlockdevRemove(child)
1275 except RPCFail, err:
1276 msgs.append(str(err))
1279 _Fail("; ".join(msgs))
1282 def _RecursiveAssembleBD(disk, owner, as_primary):
1283 """Activate a block device for an instance.
1285 This is run on the primary and secondary nodes for an instance.
1287 @note: this function is called recursively.
1289 @type disk: L{objects.Disk}
1290 @param disk: the disk we try to assemble
1292 @param owner: the name of the instance which owns the disk
1293 @type as_primary: boolean
1294 @param as_primary: if we should make the block device
1297 @return: the assembled device or None (in case no device
1299 @raise errors.BlockDeviceError: in case there is an error
1300 during the activation of the children or the device
1306 mcn = disk.ChildrenNeeded()
1308 mcn = 0 # max number of Nones allowed
1310 mcn = len(disk.children) - mcn # max number of Nones
1311 for chld_disk in disk.children:
1313 cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1314 except errors.BlockDeviceError, err:
1315 if children.count(None) >= mcn:
1318 logging.error("Error in child activation (but continuing): %s",
1320 children.append(cdev)
1322 if as_primary or disk.AssembleOnSecondary():
1323 r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
1324 r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1326 if as_primary or disk.OpenOnSecondary():
1328 DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1329 as_primary, disk.iv_name)
1336 def BlockdevAssemble(disk, owner, as_primary):
1337 """Activate a block device for an instance.
1339 This is a wrapper over _RecursiveAssembleBD.
1341 @rtype: str or boolean
1342 @return: a C{/dev/...} path for primary nodes, and
1343 C{True} for secondary nodes
1347 result = _RecursiveAssembleBD(disk, owner, as_primary)
1348 if isinstance(result, bdev.BlockDev):
1349 # pylint: disable-msg=E1103
1350 result = result.dev_path
1351 except errors.BlockDeviceError, err:
1352 _Fail("Error while assembling disk: %s", err, exc=True)
1357 def BlockdevShutdown(disk):
1358 """Shut down a block device.
1360 First, if the device is assembled (Attach() is successful), then
1361 the device is shutdown. Then the children of the device are
1364 This function is called recursively. Note that we don't cache the
1365 children or such, as oppossed to assemble, shutdown of different
1366 devices doesn't require that the upper device was active.
1368 @type disk: L{objects.Disk}
1369 @param disk: the description of the disk we should
1375 r_dev = _RecursiveFindBD(disk)
1376 if r_dev is not None:
1377 r_path = r_dev.dev_path
1380 DevCacheManager.RemoveCache(r_path)
1381 except errors.BlockDeviceError, err:
1382 msgs.append(str(err))
1385 for child in disk.children:
1387 BlockdevShutdown(child)
1388 except RPCFail, err:
1389 msgs.append(str(err))
1392 _Fail("; ".join(msgs))
1395 def BlockdevAddchildren(parent_cdev, new_cdevs):
1396 """Extend a mirrored block device.
1398 @type parent_cdev: L{objects.Disk}
1399 @param parent_cdev: the disk to which we should add children
1400 @type new_cdevs: list of L{objects.Disk}
1401 @param new_cdevs: the list of children which we should add
1405 parent_bdev = _RecursiveFindBD(parent_cdev)
1406 if parent_bdev is None:
1407 _Fail("Can't find parent device '%s' in add children", parent_cdev)
1408 new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1409 if new_bdevs.count(None) > 0:
1410 _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1411 parent_bdev.AddChildren(new_bdevs)
1414 def BlockdevRemovechildren(parent_cdev, new_cdevs):
1415 """Shrink a mirrored block device.
1417 @type parent_cdev: L{objects.Disk}
1418 @param parent_cdev: the disk from which we should remove children
1419 @type new_cdevs: list of L{objects.Disk}
1420 @param new_cdevs: the list of children which we should remove
1424 parent_bdev = _RecursiveFindBD(parent_cdev)
1425 if parent_bdev is None:
1426 _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1428 for disk in new_cdevs:
1429 rpath = disk.StaticDevPath()
1431 bd = _RecursiveFindBD(disk)
1433 _Fail("Can't find device %s while removing children", disk)
1435 devs.append(bd.dev_path)
1438 parent_bdev.RemoveChildren(devs)
1441 def BlockdevGetmirrorstatus(disks):
1442 """Get the mirroring status of a list of devices.
1444 @type disks: list of L{objects.Disk}
1445 @param disks: the list of disks which we should query
1448 a list of (mirror_done, estimated_time) tuples, which
1449 are the result of L{bdev.BlockDev.CombinedSyncStatus}
1450 @raise errors.BlockDeviceError: if any of the disks cannot be
1456 rbd = _RecursiveFindBD(dsk)
1458 _Fail("Can't find device %s", dsk)
1460 stats.append(rbd.CombinedSyncStatus())
1465 def _RecursiveFindBD(disk):
1466 """Check if a device is activated.
1468 If so, return information about the real device.
1470 @type disk: L{objects.Disk}
1471 @param disk: the disk object we need to find
1473 @return: None if the device can't be found,
1474 otherwise the device instance
1479 for chdisk in disk.children:
1480 children.append(_RecursiveFindBD(chdisk))
1482 return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1485 def BlockdevFind(disk):
1486 """Check if a device is activated.
1488 If it is, return information about the real device.
1490 @type disk: L{objects.Disk}
1491 @param disk: the disk to find
1492 @rtype: None or objects.BlockDevStatus
1493 @return: None if the disk cannot be found, otherwise a the current
1498 rbd = _RecursiveFindBD(disk)
1499 except errors.BlockDeviceError, err:
1500 _Fail("Failed to find device: %s", err, exc=True)
1505 return rbd.GetSyncStatus()
1508 def BlockdevGetsize(disks):
1509 """Computes the size of the given disks.
1511 If a disk is not found, returns None instead.
1513 @type disks: list of L{objects.Disk}
1514 @param disks: the list of disk to compute the size for
1516 @return: list with elements None if the disk cannot be found,
1523 rbd = _RecursiveFindBD(cf)
1524 except errors.BlockDeviceError:
1530 result.append(rbd.GetActualSize())
1534 def BlockdevExport(disk, dest_node, dest_path, cluster_name):
1535 """Export a block device to a remote node.
1537 @type disk: L{objects.Disk}
1538 @param disk: the description of the disk to export
1539 @type dest_node: str
1540 @param dest_node: the destination node to export to
1541 @type dest_path: str
1542 @param dest_path: the destination path on the target node
1543 @type cluster_name: str
1544 @param cluster_name: the cluster name, needed for SSH hostalias
1548 real_disk = _RecursiveFindBD(disk)
1549 if real_disk is None:
1550 _Fail("Block device '%s' is not set up", disk)
1554 # the block size on the read dd is 1MiB to match our units
1555 expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
1556 "dd if=%s bs=1048576 count=%s",
1557 real_disk.dev_path, str(disk.size))
1559 # we set here a smaller block size as, due to ssh buffering, more
1560 # than 64-128k will mostly ignored; we use nocreat to fail if the
1561 # device is not already there or we pass a wrong path; we use
1562 # notrunc to no attempt truncate on an LV device; we use oflag=dsync
1563 # to not buffer too much memory; this means that at best, we flush
1564 # every 64k, which will not be very fast
1565 destcmd = utils.BuildShellCmd("dd of=%s conv=nocreat,notrunc bs=65536"
1566 " oflag=dsync", dest_path)
1568 remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1569 constants.GANETI_RUNAS,
1572 # all commands have been checked, so we're safe to combine them
1573 command = '|'.join([expcmd, utils.ShellQuoteArgs(remotecmd)])
1575 result = utils.RunCmd(["bash", "-c", command])
1578 _Fail("Disk copy command '%s' returned error: %s"
1579 " output: %s", command, result.fail_reason, result.output)
1582 def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1583 """Write a file to the filesystem.
1585 This allows the master to overwrite(!) a file. It will only perform
1586 the operation if the file belongs to a list of configuration files.
1588 @type file_name: str
1589 @param file_name: the target file name
1591 @param data: the new contents of the file
1593 @param mode: the mode to give the file (can be None)
1595 @param uid: the owner of the file (can be -1 for default)
1597 @param gid: the group of the file (can be -1 for default)
1599 @param atime: the atime to set on the file (can be None)
1601 @param mtime: the mtime to set on the file (can be None)
1605 if not os.path.isabs(file_name):
1606 _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
1608 if file_name not in _ALLOWED_UPLOAD_FILES:
1609 _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
1612 raw_data = _Decompress(data)
1614 utils.WriteFile(file_name, data=raw_data, mode=mode, uid=uid, gid=gid,
1615 atime=atime, mtime=mtime)
1618 def WriteSsconfFiles(values):
1619 """Update all ssconf files.
1621 Wrapper around the SimpleStore.WriteFiles.
1624 ssconf.SimpleStore().WriteFiles(values)
1627 def _ErrnoOrStr(err):
1628 """Format an EnvironmentError exception.
1630 If the L{err} argument has an errno attribute, it will be looked up
1631 and converted into a textual C{E...} description. Otherwise the
1632 string representation of the error will be returned.
1634 @type err: L{EnvironmentError}
1635 @param err: the exception to format
1638 if hasattr(err, 'errno'):
1639 detail = errno.errorcode[err.errno]
1645 def _OSOndiskAPIVersion(os_dir):
1646 """Compute and return the API version of a given OS.
1648 This function will try to read the API version of the OS residing in
1649 the 'os_dir' directory.
1652 @param os_dir: the directory in which we should look for the OS
1654 @return: tuple (status, data) with status denoting the validity and
1655 data holding either the vaid versions or an error message
1658 api_file = os.path.sep.join([os_dir, constants.OS_API_FILE])
1661 st = os.stat(api_file)
1662 except EnvironmentError, err:
1663 return False, ("Required file '%s' not found under path %s: %s" %
1664 (constants.OS_API_FILE, os_dir, _ErrnoOrStr(err)))
1666 if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1667 return False, ("File '%s' in %s is not a regular file" %
1668 (constants.OS_API_FILE, os_dir))
1671 api_versions = utils.ReadFile(api_file).splitlines()
1672 except EnvironmentError, err:
1673 return False, ("Error while reading the API version file at %s: %s" %
1674 (api_file, _ErrnoOrStr(err)))
1677 api_versions = [int(version.strip()) for version in api_versions]
1678 except (TypeError, ValueError), err:
1679 return False, ("API version(s) can't be converted to integer: %s" %
1682 return True, api_versions
1685 def DiagnoseOS(top_dirs=None):
1686 """Compute the validity for all OSes.
1688 @type top_dirs: list
1689 @param top_dirs: the list of directories in which to
1690 search (if not given defaults to
1691 L{constants.OS_SEARCH_PATH})
1692 @rtype: list of L{objects.OS}
1693 @return: a list of tuples (name, path, status, diagnose, variants)
1694 for all (potential) OSes under all search paths, where:
1695 - name is the (potential) OS name
1696 - path is the full path to the OS
1697 - status True/False is the validity of the OS
1698 - diagnose is the error message for an invalid OS, otherwise empty
1699 - variants is a list of supported OS variants, if any
1702 if top_dirs is None:
1703 top_dirs = constants.OS_SEARCH_PATH
1706 for dir_name in top_dirs:
1707 if os.path.isdir(dir_name):
1709 f_names = utils.ListVisibleFiles(dir_name)
1710 except EnvironmentError, err:
1711 logging.exception("Can't list the OS directory %s: %s", dir_name, err)
1713 for name in f_names:
1714 os_path = os.path.sep.join([dir_name, name])
1715 status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
1718 variants = os_inst.supported_variants
1722 result.append((name, os_path, status, diagnose, variants))
1727 def _TryOSFromDisk(name, base_dir=None):
1728 """Create an OS instance from disk.
1730 This function will return an OS instance if the given name is a
1733 @type base_dir: string
1734 @keyword base_dir: Base directory containing OS installations.
1735 Defaults to a search in all the OS_SEARCH_PATH dirs.
1737 @return: success and either the OS instance if we find a valid one,
1741 if base_dir is None:
1742 os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1744 os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
1747 return False, "Directory for OS %s not found in search path" % name
1749 status, api_versions = _OSOndiskAPIVersion(os_dir)
1752 return status, api_versions
1754 if not constants.OS_API_VERSIONS.intersection(api_versions):
1755 return False, ("API version mismatch for path '%s': found %s, want %s." %
1756 (os_dir, api_versions, constants.OS_API_VERSIONS))
1758 # OS Files dictionary, we will populate it with the absolute path names
1759 os_files = dict.fromkeys(constants.OS_SCRIPTS)
1761 if max(api_versions) >= constants.OS_API_V15:
1762 os_files[constants.OS_VARIANTS_FILE] = ''
1764 for filename in os_files:
1765 os_files[filename] = os.path.sep.join([os_dir, filename])
1768 st = os.stat(os_files[filename])
1769 except EnvironmentError, err:
1770 return False, ("File '%s' under path '%s' is missing (%s)" %
1771 (filename, os_dir, _ErrnoOrStr(err)))
1773 if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1774 return False, ("File '%s' under path '%s' is not a regular file" %
1777 if filename in constants.OS_SCRIPTS:
1778 if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1779 return False, ("File '%s' under path '%s' is not executable" %
1783 if constants.OS_VARIANTS_FILE in os_files:
1784 variants_file = os_files[constants.OS_VARIANTS_FILE]
1786 variants = utils.ReadFile(variants_file).splitlines()
1787 except EnvironmentError, err:
1788 return False, ("Error while reading the OS variants file at %s: %s" %
1789 (variants_file, _ErrnoOrStr(err)))
1791 return False, ("No supported os variant found")
1793 os_obj = objects.OS(name=name, path=os_dir,
1794 create_script=os_files[constants.OS_SCRIPT_CREATE],
1795 export_script=os_files[constants.OS_SCRIPT_EXPORT],
1796 import_script=os_files[constants.OS_SCRIPT_IMPORT],
1797 rename_script=os_files[constants.OS_SCRIPT_RENAME],
1798 supported_variants=variants,
1799 api_versions=api_versions)
1803 def OSFromDisk(name, base_dir=None):
1804 """Create an OS instance from disk.
1806 This function will return an OS instance if the given name is a
1807 valid OS name. Otherwise, it will raise an appropriate
1808 L{RPCFail} exception, detailing why this is not a valid OS.
1810 This is just a wrapper over L{_TryOSFromDisk}, which doesn't raise
1811 an exception but returns true/false status data.
1813 @type base_dir: string
1814 @keyword base_dir: Base directory containing OS installations.
1815 Defaults to a search in all the OS_SEARCH_PATH dirs.
1816 @rtype: L{objects.OS}
1817 @return: the OS instance if we find a valid one
1818 @raise RPCFail: if we don't find a valid OS
1821 name_only = name.split("+", 1)[0]
1822 status, payload = _TryOSFromDisk(name_only, base_dir)
1830 def OSEnvironment(instance, inst_os, debug=0):
1831 """Calculate the environment for an os script.
1833 @type instance: L{objects.Instance}
1834 @param instance: target instance for the os script run
1835 @type inst_os: L{objects.OS}
1836 @param inst_os: operating system for which the environment is being built
1837 @type debug: integer
1838 @param debug: debug level (0 or 1, for OS Api 10)
1840 @return: dict of environment variables
1841 @raise errors.BlockDeviceError: if the block device
1847 max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
1848 result['OS_API_VERSION'] = '%d' % api_version
1849 result['INSTANCE_NAME'] = instance.name
1850 result['INSTANCE_OS'] = instance.os
1851 result['HYPERVISOR'] = instance.hypervisor
1852 result['DISK_COUNT'] = '%d' % len(instance.disks)
1853 result['NIC_COUNT'] = '%d' % len(instance.nics)
1854 result['DEBUG_LEVEL'] = '%d' % debug
1855 if api_version >= constants.OS_API_V15:
1857 variant = instance.os.split('+', 1)[1]
1859 variant = inst_os.supported_variants[0]
1860 result['OS_VARIANT'] = variant
1861 for idx, disk in enumerate(instance.disks):
1862 real_disk = _RecursiveFindBD(disk)
1863 if real_disk is None:
1864 raise errors.BlockDeviceError("Block device '%s' is not set up" %
1867 result['DISK_%d_PATH' % idx] = real_disk.dev_path
1868 result['DISK_%d_ACCESS' % idx] = disk.mode
1869 if constants.HV_DISK_TYPE in instance.hvparams:
1870 result['DISK_%d_FRONTEND_TYPE' % idx] = \
1871 instance.hvparams[constants.HV_DISK_TYPE]
1872 if disk.dev_type in constants.LDS_BLOCK:
1873 result['DISK_%d_BACKEND_TYPE' % idx] = 'block'
1874 elif disk.dev_type == constants.LD_FILE:
1875 result['DISK_%d_BACKEND_TYPE' % idx] = \
1876 'file:%s' % disk.physical_id[0]
1877 for idx, nic in enumerate(instance.nics):
1878 result['NIC_%d_MAC' % idx] = nic.mac
1880 result['NIC_%d_IP' % idx] = nic.ip
1881 result['NIC_%d_MODE' % idx] = nic.nicparams[constants.NIC_MODE]
1882 if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
1883 result['NIC_%d_BRIDGE' % idx] = nic.nicparams[constants.NIC_LINK]
1884 if nic.nicparams[constants.NIC_LINK]:
1885 result['NIC_%d_LINK' % idx] = nic.nicparams[constants.NIC_LINK]
1886 if constants.HV_NIC_TYPE in instance.hvparams:
1887 result['NIC_%d_FRONTEND_TYPE' % idx] = \
1888 instance.hvparams[constants.HV_NIC_TYPE]
1890 for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
1891 for key, value in source.items():
1892 result["INSTANCE_%s_%s" % (kind, key)] = str(value)
1896 def BlockdevGrow(disk, amount):
1897 """Grow a stack of block devices.
1899 This function is called recursively, with the childrens being the
1900 first ones to resize.
1902 @type disk: L{objects.Disk}
1903 @param disk: the disk to be grown
1904 @rtype: (status, result)
1905 @return: a tuple with the status of the operation
1906 (True/False), and the errors message if status
1910 r_dev = _RecursiveFindBD(disk)
1912 _Fail("Cannot find block device %s", disk)
1916 except errors.BlockDeviceError, err:
1917 _Fail("Failed to grow block device: %s", err, exc=True)
1920 def BlockdevSnapshot(disk):
1921 """Create a snapshot copy of a block device.
1923 This function is called recursively, and the snapshot is actually created
1924 just for the leaf lvm backend device.
1926 @type disk: L{objects.Disk}
1927 @param disk: the disk to be snapshotted
1929 @return: snapshot disk path
1932 if disk.dev_type == constants.LD_DRBD8:
1933 if not disk.children:
1934 _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
1936 return BlockdevSnapshot(disk.children[0])
1937 elif disk.dev_type == constants.LD_LV:
1938 r_dev = _RecursiveFindBD(disk)
1939 if r_dev is not None:
1940 # FIXME: choose a saner value for the snapshot size
1941 # let's stay on the safe side and ask for the full size, for now
1942 return r_dev.Snapshot(disk.size)
1944 _Fail("Cannot find block device %s", disk)
1946 _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
1947 disk.unique_id, disk.dev_type)
1950 def ExportSnapshot(disk, dest_node, instance, cluster_name, idx, debug):
1951 """Export a block device snapshot to a remote node.
1953 @type disk: L{objects.Disk}
1954 @param disk: the description of the disk to export
1955 @type dest_node: str
1956 @param dest_node: the destination node to export to
1957 @type instance: L{objects.Instance}
1958 @param instance: the instance object to whom the disk belongs
1959 @type cluster_name: str
1960 @param cluster_name: the cluster name, needed for SSH hostalias
1962 @param idx: the index of the disk in the instance's disk list,
1963 used to export to the OS scripts environment
1964 @type debug: integer
1965 @param debug: debug level, passed to the OS scripts
1969 inst_os = OSFromDisk(instance.os)
1970 export_env = OSEnvironment(instance, inst_os, debug)
1972 export_script = inst_os.export_script
1974 logfile = "%s/exp-%s-%s-%s.log" % (constants.LOG_OS_DIR, inst_os.name,
1975 instance.name, int(time.time()))
1976 if not os.path.exists(constants.LOG_OS_DIR):
1977 os.mkdir(constants.LOG_OS_DIR, 0750)
1978 real_disk = _RecursiveFindBD(disk)
1979 if real_disk is None:
1980 _Fail("Block device '%s' is not set up", disk)
1984 export_env['EXPORT_DEVICE'] = real_disk.dev_path
1985 export_env['EXPORT_INDEX'] = str(idx)
1987 destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1988 destfile = disk.physical_id[1]
1990 # the target command is built out of three individual commands,
1991 # which are joined by pipes; we check each individual command for
1993 expcmd = utils.BuildShellCmd("set -e; set -o pipefail; cd %s; %s 2>%s",
1994 inst_os.path, export_script, logfile)
1998 destcmd = utils.BuildShellCmd("mkdir -p %s && cat > %s/%s",
1999 destdir, destdir, destfile)
2000 remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2001 constants.GANETI_RUNAS,
2004 # all commands have been checked, so we're safe to combine them
2005 command = '|'.join([expcmd, comprcmd, utils.ShellQuoteArgs(remotecmd)])
2007 result = utils.RunCmd(["bash", "-c", command], env=export_env)
2010 _Fail("OS snapshot export command '%s' returned error: %s"
2011 " output: %s", command, result.fail_reason, result.output)
2014 def FinalizeExport(instance, snap_disks):
2015 """Write out the export configuration information.
2017 @type instance: L{objects.Instance}
2018 @param instance: the instance which we export, used for
2019 saving configuration
2020 @type snap_disks: list of L{objects.Disk}
2021 @param snap_disks: list of snapshot block devices, which
2022 will be used to get the actual name of the dump file
2027 destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
2028 finaldestdir = os.path.join(constants.EXPORT_DIR, instance.name)
2030 config = objects.SerializableConfigParser()
2032 config.add_section(constants.INISECT_EXP)
2033 config.set(constants.INISECT_EXP, 'version', '0')
2034 config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
2035 config.set(constants.INISECT_EXP, 'source', instance.primary_node)
2036 config.set(constants.INISECT_EXP, 'os', instance.os)
2037 config.set(constants.INISECT_EXP, 'compression', 'gzip')
2039 config.add_section(constants.INISECT_INS)
2040 config.set(constants.INISECT_INS, 'name', instance.name)
2041 config.set(constants.INISECT_INS, 'memory', '%d' %
2042 instance.beparams[constants.BE_MEMORY])
2043 config.set(constants.INISECT_INS, 'vcpus', '%d' %
2044 instance.beparams[constants.BE_VCPUS])
2045 config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
2048 for nic_count, nic in enumerate(instance.nics):
2050 config.set(constants.INISECT_INS, 'nic%d_mac' %
2051 nic_count, '%s' % nic.mac)
2052 config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
2053 config.set(constants.INISECT_INS, 'nic%d_bridge' % nic_count,
2055 # TODO: redundant: on load can read nics until it doesn't exist
2056 config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_total)
2059 for disk_count, disk in enumerate(snap_disks):
2062 config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
2063 ('%s' % disk.iv_name))
2064 config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
2065 ('%s' % disk.physical_id[1]))
2066 config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
2069 config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_total)
2071 utils.WriteFile(os.path.join(destdir, constants.EXPORT_CONF_FILE),
2072 data=config.Dumps())
2073 shutil.rmtree(finaldestdir, True)
2074 shutil.move(destdir, finaldestdir)
2077 def ExportInfo(dest):
2078 """Get export configuration information.
2081 @param dest: directory containing the export
2083 @rtype: L{objects.SerializableConfigParser}
2084 @return: a serializable config file containing the
2088 cff = os.path.join(dest, constants.EXPORT_CONF_FILE)
2090 config = objects.SerializableConfigParser()
2093 if (not config.has_section(constants.INISECT_EXP) or
2094 not config.has_section(constants.INISECT_INS)):
2095 _Fail("Export info file doesn't have the required fields")
2097 return config.Dumps()
2100 def ImportOSIntoInstance(instance, src_node, src_images, cluster_name, debug):
2101 """Import an os image into an instance.
2103 @type instance: L{objects.Instance}
2104 @param instance: instance to import the disks into
2105 @type src_node: string
2106 @param src_node: source node for the disk images
2107 @type src_images: list of string
2108 @param src_images: absolute paths of the disk images
2109 @type debug: integer
2110 @param debug: debug level, passed to the OS scripts
2111 @rtype: list of boolean
2112 @return: each boolean represent the success of importing the n-th disk
2115 inst_os = OSFromDisk(instance.os)
2116 import_env = OSEnvironment(instance, inst_os, debug)
2117 import_script = inst_os.import_script
2119 logfile = "%s/import-%s-%s-%s.log" % (constants.LOG_OS_DIR, instance.os,
2120 instance.name, int(time.time()))
2121 if not os.path.exists(constants.LOG_OS_DIR):
2122 os.mkdir(constants.LOG_OS_DIR, 0750)
2125 impcmd = utils.BuildShellCmd("(cd %s; %s >%s 2>&1)", inst_os.path,
2126 import_script, logfile)
2129 for idx, image in enumerate(src_images):
2131 destcmd = utils.BuildShellCmd('cat %s', image)
2132 remotecmd = _GetSshRunner(cluster_name).BuildCmd(src_node,
2133 constants.GANETI_RUNAS,
2135 command = '|'.join([utils.ShellQuoteArgs(remotecmd), comprcmd, impcmd])
2136 import_env['IMPORT_DEVICE'] = import_env['DISK_%d_PATH' % idx]
2137 import_env['IMPORT_INDEX'] = str(idx)
2138 result = utils.RunCmd(command, env=import_env)
2140 logging.error("Disk import command '%s' returned error: %s"
2141 " output: %s", command, result.fail_reason,
2143 final_result.append("error importing disk %d: %s, %s" %
2144 (idx, result.fail_reason, result.output[-100]))
2147 _Fail("; ".join(final_result), log=False)
2151 """Return a list of exports currently available on this machine.
2154 @return: list of the exports
2157 if os.path.isdir(constants.EXPORT_DIR):
2158 return utils.ListVisibleFiles(constants.EXPORT_DIR)
2160 _Fail("No exports directory")
2163 def RemoveExport(export):
2164 """Remove an existing export from the node.
2167 @param export: the name of the export to remove
2171 target = os.path.join(constants.EXPORT_DIR, export)
2174 shutil.rmtree(target)
2175 except EnvironmentError, err:
2176 _Fail("Error while removing the export: %s", err, exc=True)
2179 def BlockdevRename(devlist):
2180 """Rename a list of block devices.
2182 @type devlist: list of tuples
2183 @param devlist: list of tuples of the form (disk,
2184 new_logical_id, new_physical_id); disk is an
2185 L{objects.Disk} object describing the current disk,
2186 and new logical_id/physical_id is the name we
2189 @return: True if all renames succeeded, False otherwise
2194 for disk, unique_id in devlist:
2195 dev = _RecursiveFindBD(disk)
2197 msgs.append("Can't find device %s in rename" % str(disk))
2201 old_rpath = dev.dev_path
2202 dev.Rename(unique_id)
2203 new_rpath = dev.dev_path
2204 if old_rpath != new_rpath:
2205 DevCacheManager.RemoveCache(old_rpath)
2206 # FIXME: we should add the new cache information here, like:
2207 # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2208 # but we don't have the owner here - maybe parse from existing
2209 # cache? for now, we only lose lvm data when we rename, which
2210 # is less critical than DRBD or MD
2211 except errors.BlockDeviceError, err:
2212 msgs.append("Can't rename device '%s' to '%s': %s" %
2213 (dev, unique_id, err))
2214 logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2217 _Fail("; ".join(msgs))
2220 def _TransformFileStorageDir(file_storage_dir):
2221 """Checks whether given file_storage_dir is valid.
2223 Checks wheter the given file_storage_dir is within the cluster-wide
2224 default file_storage_dir stored in SimpleStore. Only paths under that
2225 directory are allowed.
2227 @type file_storage_dir: str
2228 @param file_storage_dir: the path to check
2230 @return: the normalized path if valid, None otherwise
2234 file_storage_dir = os.path.normpath(file_storage_dir)
2235 base_file_storage_dir = cfg.GetFileStorageDir()
2236 if (not os.path.commonprefix([file_storage_dir, base_file_storage_dir]) ==
2237 base_file_storage_dir):
2238 _Fail("File storage directory '%s' is not under base file"
2239 " storage directory '%s'", file_storage_dir, base_file_storage_dir)
2240 return file_storage_dir
2243 def CreateFileStorageDir(file_storage_dir):
2244 """Create file storage directory.
2246 @type file_storage_dir: str
2247 @param file_storage_dir: directory to create
2250 @return: tuple with first element a boolean indicating wheter dir
2251 creation was successful or not
2254 file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2255 if os.path.exists(file_storage_dir):
2256 if not os.path.isdir(file_storage_dir):
2257 _Fail("Specified storage dir '%s' is not a directory",
2261 os.makedirs(file_storage_dir, 0750)
2262 except OSError, err:
2263 _Fail("Cannot create file storage directory '%s': %s",
2264 file_storage_dir, err, exc=True)
2267 def RemoveFileStorageDir(file_storage_dir):
2268 """Remove file storage directory.
2270 Remove it only if it's empty. If not log an error and return.
2272 @type file_storage_dir: str
2273 @param file_storage_dir: the directory we should cleanup
2274 @rtype: tuple (success,)
2275 @return: tuple of one element, C{success}, denoting
2276 whether the operation was successful
2279 file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2280 if os.path.exists(file_storage_dir):
2281 if not os.path.isdir(file_storage_dir):
2282 _Fail("Specified Storage directory '%s' is not a directory",
2284 # deletes dir only if empty, otherwise we want to fail the rpc call
2286 os.rmdir(file_storage_dir)
2287 except OSError, err:
2288 _Fail("Cannot remove file storage directory '%s': %s",
2289 file_storage_dir, err)
2292 def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2293 """Rename the file storage directory.
2295 @type old_file_storage_dir: str
2296 @param old_file_storage_dir: the current path
2297 @type new_file_storage_dir: str
2298 @param new_file_storage_dir: the name we should rename to
2299 @rtype: tuple (success,)
2300 @return: tuple of one element, C{success}, denoting
2301 whether the operation was successful
2304 old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2305 new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2306 if not os.path.exists(new_file_storage_dir):
2307 if os.path.isdir(old_file_storage_dir):
2309 os.rename(old_file_storage_dir, new_file_storage_dir)
2310 except OSError, err:
2311 _Fail("Cannot rename '%s' to '%s': %s",
2312 old_file_storage_dir, new_file_storage_dir, err)
2314 _Fail("Specified storage dir '%s' is not a directory",
2315 old_file_storage_dir)
2317 if os.path.exists(old_file_storage_dir):
2318 _Fail("Cannot rename '%s' to '%s': both locations exist",
2319 old_file_storage_dir, new_file_storage_dir)
2322 def _EnsureJobQueueFile(file_name):
2323 """Checks whether the given filename is in the queue directory.
2325 @type file_name: str
2326 @param file_name: the file name we should check
2328 @raises RPCFail: if the file is not valid
2331 queue_dir = os.path.normpath(constants.QUEUE_DIR)
2332 result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2335 _Fail("Passed job queue file '%s' does not belong to"
2336 " the queue directory '%s'", file_name, queue_dir)
2339 def JobQueueUpdate(file_name, content):
2340 """Updates a file in the queue directory.
2342 This is just a wrapper over L{utils.WriteFile}, with proper
2345 @type file_name: str
2346 @param file_name: the job file name
2348 @param content: the new job contents
2350 @return: the success of the operation
2353 _EnsureJobQueueFile(file_name)
2355 # Write and replace the file atomically
2356 utils.WriteFile(file_name, data=_Decompress(content))
2359 def JobQueueRename(old, new):
2360 """Renames a job queue file.
2362 This is just a wrapper over os.rename with proper checking.
2365 @param old: the old (actual) file name
2367 @param new: the desired file name
2369 @return: the success of the operation and payload
2372 _EnsureJobQueueFile(old)
2373 _EnsureJobQueueFile(new)
2375 utils.RenameFile(old, new, mkdir=True)
2378 def JobQueueSetDrainFlag(drain_flag):
2379 """Set the drain flag for the queue.
2381 This will set or unset the queue drain flag.
2383 @type drain_flag: boolean
2384 @param drain_flag: if True, will set the drain flag, otherwise reset it.
2386 @return: always True, None
2387 @warning: the function always returns True
2391 utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True)
2393 utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
2396 def BlockdevClose(instance_name, disks):
2397 """Closes the given block devices.
2399 This means they will be switched to secondary mode (in case of
2402 @param instance_name: if the argument is not empty, the symlinks
2403 of this instance will be removed
2404 @type disks: list of L{objects.Disk}
2405 @param disks: the list of disks to be closed
2406 @rtype: tuple (success, message)
2407 @return: a tuple of success and message, where success
2408 indicates the succes of the operation, and message
2409 which will contain the error details in case we
2415 rd = _RecursiveFindBD(cf)
2417 _Fail("Can't find device %s", cf)
2424 except errors.BlockDeviceError, err:
2425 msg.append(str(err))
2427 _Fail("Can't make devices secondary: %s", ",".join(msg))
2430 _RemoveBlockDevLinks(instance_name, disks)
2433 def ValidateHVParams(hvname, hvparams):
2434 """Validates the given hypervisor parameters.
2436 @type hvname: string
2437 @param hvname: the hypervisor name
2438 @type hvparams: dict
2439 @param hvparams: the hypervisor parameters to be validated
2444 hv_type = hypervisor.GetHypervisor(hvname)
2445 hv_type.ValidateParameters(hvparams)
2446 except errors.HypervisorError, err:
2447 _Fail(str(err), log=False)
2451 """Demotes the current node from master candidate role.
2454 # try to ensure we're not the master by mistake
2455 master, myself = ssconf.GetMasterAndMyself()
2456 if master == myself:
2457 _Fail("ssconf status shows I'm the master node, will not demote")
2459 result = utils.RunCmd([constants.DAEMON_UTIL, "check", constants.MASTERD])
2460 if not result.failed:
2461 _Fail("The master daemon is running, will not demote")
2464 if os.path.isfile(constants.CLUSTER_CONF_FILE):
2465 utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2466 except EnvironmentError, err:
2467 if err.errno != errno.ENOENT:
2468 _Fail("Error while backing up cluster file: %s", err, exc=True)
2470 utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2473 def _FindDisks(nodes_ip, disks):
2474 """Sets the physical ID on disks and returns the block devices.
2477 # set the correct physical ID
2478 my_name = utils.HostInfo().name
2480 cf.SetPhysicalID(my_name, nodes_ip)
2485 rd = _RecursiveFindBD(cf)
2487 _Fail("Can't find device %s", cf)
2492 def DrbdDisconnectNet(nodes_ip, disks):
2493 """Disconnects the network on a list of drbd devices.
2496 bdevs = _FindDisks(nodes_ip, disks)
2502 except errors.BlockDeviceError, err:
2503 _Fail("Can't change network configuration to standalone mode: %s",
2507 def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
2508 """Attaches the network on a list of drbd devices.
2511 bdevs = _FindDisks(nodes_ip, disks)
2514 for idx, rd in enumerate(bdevs):
2516 _SymlinkBlockDev(instance_name, rd.dev_path, idx)
2517 except EnvironmentError, err:
2518 _Fail("Can't create symlink: %s", err)
2519 # reconnect disks, switch to new master configuration and if
2520 # needed primary mode
2523 rd.AttachNet(multimaster)
2524 except errors.BlockDeviceError, err:
2525 _Fail("Can't change network configuration: %s", err)
2527 # wait until the disks are connected; we need to retry the re-attach
2528 # if the device becomes standalone, as this might happen if the one
2529 # node disconnects and reconnects in a different mode before the
2530 # other node reconnects; in this case, one or both of the nodes will
2531 # decide it has wrong configuration and switch to standalone
2534 all_connected = True
2537 stats = rd.GetProcStatus()
2539 all_connected = (all_connected and
2540 (stats.is_connected or stats.is_in_resync))
2542 if stats.is_standalone:
2543 # peer had different config info and this node became
2544 # standalone, even though this should not happen with the
2545 # new staged way of changing disk configs
2547 rd.AttachNet(multimaster)
2548 except errors.BlockDeviceError, err:
2549 _Fail("Can't change network configuration: %s", err)
2551 if not all_connected:
2552 raise utils.RetryAgain()
2555 # Start with a delay of 100 miliseconds and go up to 5 seconds
2556 utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
2557 except utils.RetryTimeout:
2558 _Fail("Timeout in disk reconnecting")
2561 # change to primary mode
2565 except errors.BlockDeviceError, err:
2566 _Fail("Can't change to primary mode: %s", err)
2569 def DrbdWaitSync(nodes_ip, disks):
2570 """Wait until DRBDs have synchronized.
2574 stats = rd.GetProcStatus()
2575 if not (stats.is_connected or stats.is_in_resync):
2576 raise utils.RetryAgain()
2579 bdevs = _FindDisks(nodes_ip, disks)
2585 # poll each second for 15 seconds
2586 stats = utils.Retry(_helper, 1, 15, args=[rd])
2587 except utils.RetryTimeout:
2588 stats = rd.GetProcStatus()
2590 if not (stats.is_connected or stats.is_in_resync):
2591 _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
2592 alldone = alldone and (not stats.is_in_resync)
2593 if stats.sync_percent is not None:
2594 min_resync = min(min_resync, stats.sync_percent)
2596 return (alldone, min_resync)
2599 def PowercycleNode(hypervisor_type):
2600 """Hard-powercycle the node.
2602 Because we need to return first, and schedule the powercycle in the
2603 background, we won't be able to report failures nicely.
2606 hyper = hypervisor.GetHypervisor(hypervisor_type)
2610 # if we can't fork, we'll pretend that we're in the child process
2613 return "Reboot scheduled in 5 seconds"
2615 hyper.PowercycleNode()
2618 class HooksRunner(object):
2621 This class is instantiated on the node side (ganeti-noded) and not
2625 def __init__(self, hooks_base_dir=None):
2626 """Constructor for hooks runner.
2628 @type hooks_base_dir: str or None
2629 @param hooks_base_dir: if not None, this overrides the
2630 L{constants.HOOKS_BASE_DIR} (useful for unittests)
2633 if hooks_base_dir is None:
2634 hooks_base_dir = constants.HOOKS_BASE_DIR
2635 # yeah, _BASE_DIR is not valid for attributes, we use it like a
2637 self._BASE_DIR = hooks_base_dir # pylint: disable-msg=C0103
2639 def RunHooks(self, hpath, phase, env):
2640 """Run the scripts in the hooks directory.
2643 @param hpath: the path to the hooks directory which
2646 @param phase: either L{constants.HOOKS_PHASE_PRE} or
2647 L{constants.HOOKS_PHASE_POST}
2649 @param env: dictionary with the environment for the hook
2651 @return: list of 3-element tuples:
2653 - script result, either L{constants.HKR_SUCCESS} or
2654 L{constants.HKR_FAIL}
2655 - output of the script
2657 @raise errors.ProgrammerError: for invalid input
2661 if phase == constants.HOOKS_PHASE_PRE:
2663 elif phase == constants.HOOKS_PHASE_POST:
2666 _Fail("Unknown hooks phase '%s'", phase)
2669 subdir = "%s-%s.d" % (hpath, suffix)
2670 dir_name = "%s/%s" % (self._BASE_DIR, subdir)
2671 runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
2674 for (relname, relstatus, runresult) in runparts_results:
2675 if relstatus == constants.RUNPARTS_SKIP:
2676 rrval = constants.HKR_SKIP
2678 elif relstatus == constants.RUNPARTS_ERR:
2679 rrval = constants.HKR_FAIL
2680 output = "Hook script execution error: %s" % runresult
2681 elif relstatus == constants.RUNPARTS_RUN:
2682 if runresult.failed:
2683 rrval = constants.HKR_FAIL
2685 rrval = constants.HKR_SUCCESS
2686 output = utils.SafeEncode(runresult.output.strip())
2687 results.append(("%s/%s" % (subdir, relname), rrval, output))
2692 class IAllocatorRunner(object):
2693 """IAllocator runner.
2695 This class is instantiated on the node side (ganeti-noded) and not on
2700 def Run(name, idata):
2701 """Run an iallocator script.
2704 @param name: the iallocator script name
2706 @param idata: the allocator input data
2709 @return: two element tuple of:
2711 - either error message or stdout of allocator (for success)
2714 alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
2716 if alloc_script is None:
2717 _Fail("iallocator module '%s' not found in the search path", name)
2719 fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
2723 result = utils.RunCmd([alloc_script, fin_name])
2725 _Fail("iallocator module '%s' failed: %s, output '%s'",
2726 name, result.fail_reason, result.output)
2730 return result.stdout
2733 class DevCacheManager(object):
2734 """Simple class for managing a cache of block device information.
2737 _DEV_PREFIX = "/dev/"
2738 _ROOT_DIR = constants.BDEV_CACHE_DIR
2741 def _ConvertPath(cls, dev_path):
2742 """Converts a /dev/name path to the cache file name.
2744 This replaces slashes with underscores and strips the /dev
2745 prefix. It then returns the full path to the cache file.
2748 @param dev_path: the C{/dev/} path name
2750 @return: the converted path name
2753 if dev_path.startswith(cls._DEV_PREFIX):
2754 dev_path = dev_path[len(cls._DEV_PREFIX):]
2755 dev_path = dev_path.replace("/", "_")
2756 fpath = "%s/bdev_%s" % (cls._ROOT_DIR, dev_path)
2760 def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
2761 """Updates the cache information for a given device.
2764 @param dev_path: the pathname of the device
2766 @param owner: the owner (instance name) of the device
2767 @type on_primary: bool
2768 @param on_primary: whether this is the primary
2771 @param iv_name: the instance-visible name of the
2772 device, as in objects.Disk.iv_name
2777 if dev_path is None:
2778 logging.error("DevCacheManager.UpdateCache got a None dev_path")
2780 fpath = cls._ConvertPath(dev_path)
2786 iv_name = "not_visible"
2787 fdata = "%s %s %s\n" % (str(owner), state, iv_name)
2789 utils.WriteFile(fpath, data=fdata)
2790 except EnvironmentError, err:
2791 logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
2794 def RemoveCache(cls, dev_path):
2795 """Remove data for a dev_path.
2797 This is just a wrapper over L{utils.RemoveFile} with a converted
2798 path name and logging.
2801 @param dev_path: the pathname of the device
2806 if dev_path is None:
2807 logging.error("DevCacheManager.RemoveCache got a None dev_path")
2809 fpath = cls._ConvertPath(dev_path)
2811 utils.RemoveFile(fpath)
2812 except EnvironmentError, err:
2813 logging.exception("Can't update bdev cache for %s: %s", dev_path, err)