4 # Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 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
26 @var _ALLOWED_CLEAN_DIRS: denotes which directories are accepted
27 in the L{_CleanDirectory} function
31 # pylint: disable=E1103
33 # E1103: %s %r has no %r member (but some types could not be
34 # inferred), because the _TryOSFromDisk returns either (True, os_obj)
35 # or (False, "string") which confuses pylint
52 from ganeti import errors
53 from ganeti import utils
54 from ganeti import ssh
55 from ganeti import hypervisor
56 from ganeti import constants
57 from ganeti import bdev
58 from ganeti import objects
59 from ganeti import ssconf
60 from ganeti import serializer
61 from ganeti import netutils
62 from ganeti import runtime
63 from ganeti import compat
64 from ganeti import pathutils
65 from ganeti import vcluster
67 from ganeti import hooksmaster
70 _BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id"
71 _ALLOWED_CLEAN_DIRS = compat.UniqueFrozenset([
73 pathutils.JOB_QUEUE_ARCHIVE_DIR,
75 pathutils.CRYPTO_KEYS_DIR,
77 _MAX_SSL_CERT_VALIDITY = 7 * 24 * 60 * 60
78 _X509_KEY_FILE = "key"
79 _X509_CERT_FILE = "cert"
80 _IES_STATUS_FILE = "status"
84 #: Valid LVS output line regex
85 _LVSLINE_REGEX = re.compile("^ *([^|]+)\|([^|]+)\|([0-9.]+)\|([^|]{6,})\|?$")
87 # Actions for the master setup script
88 _MASTER_START = "start"
91 #: Maximum file permissions for restricted command directory and executables
92 _RCMD_MAX_MODE = (stat.S_IRWXU |
93 stat.S_IRGRP | stat.S_IXGRP |
94 stat.S_IROTH | stat.S_IXOTH)
96 #: Delay before returning an error for restricted commands
97 _RCMD_INVALID_DELAY = 10
99 #: How long to wait to acquire lock for restricted commands (shorter than
100 #: L{_RCMD_INVALID_DELAY}) to reduce blockage of noded forks when many
101 #: command requests arrive
102 _RCMD_LOCK_TIMEOUT = _RCMD_INVALID_DELAY * 0.8
105 class RPCFail(Exception):
106 """Class denoting RPC failure.
108 Its argument is the error message.
113 def _GetInstReasonFilename(instance_name):
114 """Path of the file containing the reason of the instance status change.
116 @type instance_name: string
117 @param instance_name: The name of the instance
119 @return: The path of the file
122 return utils.PathJoin(pathutils.INSTANCE_REASON_DIR, instance_name)
125 def _StoreInstReasonTrail(instance_name, trail):
126 """Serialize a reason trail related to an instance change of state to file.
128 The exact location of the file depends on the name of the instance and on
129 the configuration of the Ganeti cluster defined at deploy time.
131 @type instance_name: string
132 @param instance_name: The name of the instance
136 json = serializer.DumpJson(trail)
137 filename = _GetInstReasonFilename(instance_name)
138 utils.WriteFile(filename, data=json)
141 def _Fail(msg, *args, **kwargs):
142 """Log an error and the raise an RPCFail exception.
144 This exception is then handled specially in the ganeti daemon and
145 turned into a 'failed' return type. As such, this function is a
146 useful shortcut for logging the error and returning it to the master
150 @param msg: the text of the exception
156 if "log" not in kwargs or kwargs["log"]: # if we should log this error
157 if "exc" in kwargs and kwargs["exc"]:
158 logging.exception(msg)
165 """Simple wrapper to return a SimpleStore.
167 @rtype: L{ssconf.SimpleStore}
168 @return: a SimpleStore instance
171 return ssconf.SimpleStore()
174 def _GetSshRunner(cluster_name):
175 """Simple wrapper to return an SshRunner.
177 @type cluster_name: str
178 @param cluster_name: the cluster name, which is needed
179 by the SshRunner constructor
180 @rtype: L{ssh.SshRunner}
181 @return: an SshRunner instance
184 return ssh.SshRunner(cluster_name)
187 def _Decompress(data):
188 """Unpacks data compressed by the RPC client.
190 @type data: list or tuple
191 @param data: Data sent by RPC client
193 @return: Decompressed data
196 assert isinstance(data, (list, tuple))
197 assert len(data) == 2
198 (encoding, content) = data
199 if encoding == constants.RPC_ENCODING_NONE:
201 elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
202 return zlib.decompress(base64.b64decode(content))
204 raise AssertionError("Unknown data encoding")
207 def _CleanDirectory(path, exclude=None):
208 """Removes all regular files in a directory.
211 @param path: the directory to clean
213 @param exclude: list of files to be excluded, defaults
217 if path not in _ALLOWED_CLEAN_DIRS:
218 _Fail("Path passed to _CleanDirectory not in allowed clean targets: '%s'",
221 if not os.path.isdir(path):
226 # Normalize excluded paths
227 exclude = [os.path.normpath(i) for i in exclude]
229 for rel_name in utils.ListVisibleFiles(path):
230 full_name = utils.PathJoin(path, rel_name)
231 if full_name in exclude:
233 if os.path.isfile(full_name) and not os.path.islink(full_name):
234 utils.RemoveFile(full_name)
237 def _BuildUploadFileList():
238 """Build the list of allowed upload files.
240 This is abstracted so that it's built only once at module import time.
243 allowed_files = set([
244 pathutils.CLUSTER_CONF_FILE,
246 pathutils.SSH_KNOWN_HOSTS_FILE,
247 pathutils.VNC_PASSWORD_FILE,
248 pathutils.RAPI_CERT_FILE,
249 pathutils.SPICE_CERT_FILE,
250 pathutils.SPICE_CACERT_FILE,
251 pathutils.RAPI_USERS_FILE,
252 pathutils.CONFD_HMAC_KEY,
253 pathutils.CLUSTER_DOMAIN_SECRET_FILE,
256 for hv_name in constants.HYPER_TYPES:
257 hv_class = hypervisor.GetHypervisorClass(hv_name)
258 allowed_files.update(hv_class.GetAncillaryFiles()[0])
260 assert pathutils.FILE_STORAGE_PATHS_FILE not in allowed_files, \
261 "Allowed file storage paths should never be uploaded via RPC"
263 return frozenset(allowed_files)
266 _ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
270 """Removes job queue files and archived jobs.
276 _CleanDirectory(pathutils.QUEUE_DIR, exclude=[pathutils.JOB_QUEUE_LOCK_FILE])
277 _CleanDirectory(pathutils.JOB_QUEUE_ARCHIVE_DIR)
281 """Returns master information.
283 This is an utility function to compute master information, either
284 for consumption here or from the node daemon.
287 @return: master_netdev, master_ip, master_name, primary_ip_family,
289 @raise RPCFail: in case of errors
294 master_netdev = cfg.GetMasterNetdev()
295 master_ip = cfg.GetMasterIP()
296 master_netmask = cfg.GetMasterNetmask()
297 master_node = cfg.GetMasterNode()
298 primary_ip_family = cfg.GetPrimaryIPFamily()
299 except errors.ConfigurationError, err:
300 _Fail("Cluster configuration incomplete: %s", err, exc=True)
301 return (master_netdev, master_ip, master_node, primary_ip_family,
305 def RunLocalHooks(hook_opcode, hooks_path, env_builder_fn):
306 """Decorator that runs hooks before and after the decorated function.
308 @type hook_opcode: string
309 @param hook_opcode: opcode of the hook
310 @type hooks_path: string
311 @param hooks_path: path of the hooks
312 @type env_builder_fn: function
313 @param env_builder_fn: function that returns a dictionary containing the
314 environment variables for the hooks. Will get all the parameters of the
316 @raise RPCFail: in case of pre-hook failure
320 def wrapper(*args, **kwargs):
321 _, myself = ssconf.GetMasterAndMyself()
322 nodes = ([myself], [myself]) # these hooks run locally
324 env_fn = compat.partial(env_builder_fn, *args, **kwargs)
328 hm = hooksmaster.HooksMaster(hook_opcode, hooks_path, nodes,
329 hr.RunLocalHooks, None, env_fn,
330 logging.warning, cfg.GetClusterName(),
332 hm.RunPhase(constants.HOOKS_PHASE_PRE)
333 result = fn(*args, **kwargs)
334 hm.RunPhase(constants.HOOKS_PHASE_POST)
341 def _BuildMasterIpEnv(master_params, use_external_mip_script=None):
342 """Builds environment variables for master IP hooks.
344 @type master_params: L{objects.MasterNetworkParameters}
345 @param master_params: network parameters of the master
346 @type use_external_mip_script: boolean
347 @param use_external_mip_script: whether to use an external master IP
348 address setup script (unused, but necessary per the implementation of the
349 _RunLocalHooks decorator)
352 # pylint: disable=W0613
353 ver = netutils.IPAddress.GetVersionFromAddressFamily(master_params.ip_family)
355 "MASTER_NETDEV": master_params.netdev,
356 "MASTER_IP": master_params.ip,
357 "MASTER_NETMASK": str(master_params.netmask),
358 "CLUSTER_IP_VERSION": str(ver),
364 def _RunMasterSetupScript(master_params, action, use_external_mip_script):
365 """Execute the master IP address setup script.
367 @type master_params: L{objects.MasterNetworkParameters}
368 @param master_params: network parameters of the master
370 @param action: action to pass to the script. Must be one of
371 L{backend._MASTER_START} or L{backend._MASTER_STOP}
372 @type use_external_mip_script: boolean
373 @param use_external_mip_script: whether to use an external master IP
375 @raise backend.RPCFail: if there are errors during the execution of the
379 env = _BuildMasterIpEnv(master_params)
381 if use_external_mip_script:
382 setup_script = pathutils.EXTERNAL_MASTER_SETUP_SCRIPT
384 setup_script = pathutils.DEFAULT_MASTER_SETUP_SCRIPT
386 result = utils.RunCmd([setup_script, action], env=env, reset_env=True)
389 _Fail("Failed to %s the master IP. Script return value: %s, output: '%s'" %
390 (action, result.exit_code, result.output), log=True)
393 @RunLocalHooks(constants.FAKE_OP_MASTER_TURNUP, "master-ip-turnup",
395 def ActivateMasterIp(master_params, use_external_mip_script):
396 """Activate the IP address of the master daemon.
398 @type master_params: L{objects.MasterNetworkParameters}
399 @param master_params: network parameters of the master
400 @type use_external_mip_script: boolean
401 @param use_external_mip_script: whether to use an external master IP
403 @raise RPCFail: in case of errors during the IP startup
406 _RunMasterSetupScript(master_params, _MASTER_START,
407 use_external_mip_script)
410 def StartMasterDaemons(no_voting):
411 """Activate local node as master node.
413 The function will start the master daemons (ganeti-masterd and ganeti-rapi).
415 @type no_voting: boolean
416 @param no_voting: whether to start ganeti-masterd without a node vote
417 but still non-interactively
423 masterd_args = "--no-voting --yes-do-it"
428 "EXTRA_MASTERD_ARGS": masterd_args,
431 result = utils.RunCmd([pathutils.DAEMON_UTIL, "start-master"], env=env)
433 msg = "Can't start Ganeti master: %s" % result.output
438 @RunLocalHooks(constants.FAKE_OP_MASTER_TURNDOWN, "master-ip-turndown",
440 def DeactivateMasterIp(master_params, use_external_mip_script):
441 """Deactivate the master IP on this node.
443 @type master_params: L{objects.MasterNetworkParameters}
444 @param master_params: network parameters of the master
445 @type use_external_mip_script: boolean
446 @param use_external_mip_script: whether to use an external master IP
448 @raise RPCFail: in case of errors during the IP turndown
451 _RunMasterSetupScript(master_params, _MASTER_STOP,
452 use_external_mip_script)
455 def StopMasterDaemons():
456 """Stop the master daemons on this node.
458 Stop the master daemons (ganeti-masterd and ganeti-rapi) on this node.
463 # TODO: log and report back to the caller the error failures; we
464 # need to decide in which case we fail the RPC for this
466 result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop-master"])
468 logging.error("Could not stop Ganeti master, command %s had exitcode %s"
470 result.cmd, result.exit_code, result.output)
473 def ChangeMasterNetmask(old_netmask, netmask, master_ip, master_netdev):
474 """Change the netmask of the master IP.
476 @param old_netmask: the old value of the netmask
477 @param netmask: the new value of the netmask
478 @param master_ip: the master IP
479 @param master_netdev: the master network device
482 if old_netmask == netmask:
485 if not netutils.IPAddress.Own(master_ip):
486 _Fail("The master IP address is not up, not attempting to change its"
489 result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
490 "%s/%s" % (master_ip, netmask),
491 "dev", master_netdev, "label",
492 "%s:0" % master_netdev])
494 _Fail("Could not set the new netmask on the master IP address")
496 result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
497 "%s/%s" % (master_ip, old_netmask),
498 "dev", master_netdev, "label",
499 "%s:0" % master_netdev])
501 _Fail("Could not bring down the master IP address with the old netmask")
504 def EtcHostsModify(mode, host, ip):
505 """Modify a host entry in /etc/hosts.
507 @param mode: The mode to operate. Either add or remove entry
508 @param host: The host to operate on
509 @param ip: The ip associated with the entry
512 if mode == constants.ETC_HOSTS_ADD:
514 RPCFail("Mode 'add' needs 'ip' parameter, but parameter not"
516 utils.AddHostToEtcHosts(host, ip)
517 elif mode == constants.ETC_HOSTS_REMOVE:
519 RPCFail("Mode 'remove' does not allow 'ip' parameter, but"
520 " parameter is present")
521 utils.RemoveHostFromEtcHosts(host)
523 RPCFail("Mode not supported")
526 def LeaveCluster(modify_ssh_setup):
527 """Cleans up and remove the current node.
529 This function cleans up and prepares the current node to be removed
532 If processing is successful, then it raises an
533 L{errors.QuitGanetiException} which is used as a special case to
534 shutdown the node daemon.
536 @param modify_ssh_setup: boolean
539 _CleanDirectory(pathutils.DATA_DIR)
540 _CleanDirectory(pathutils.CRYPTO_KEYS_DIR)
545 priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.SSH_LOGIN_USER)
547 utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
549 utils.RemoveFile(priv_key)
550 utils.RemoveFile(pub_key)
551 except errors.OpExecError:
552 logging.exception("Error while processing ssh files")
555 utils.RemoveFile(pathutils.CONFD_HMAC_KEY)
556 utils.RemoveFile(pathutils.RAPI_CERT_FILE)
557 utils.RemoveFile(pathutils.SPICE_CERT_FILE)
558 utils.RemoveFile(pathutils.SPICE_CACERT_FILE)
559 utils.RemoveFile(pathutils.NODED_CERT_FILE)
560 except: # pylint: disable=W0702
561 logging.exception("Error while removing cluster secrets")
563 result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop", constants.CONFD])
565 logging.error("Command %s failed with exitcode %s and error %s",
566 result.cmd, result.exit_code, result.output)
568 # Raise a custom exception (handled in ganeti-noded)
569 raise errors.QuitGanetiException(True, "Shutdown scheduled")
572 def _GetVgInfo(name, excl_stor):
573 """Retrieves information about a LVM volume group.
576 # TODO: GetVGInfo supports returning information for multiple VGs at once
577 vginfo = bdev.LogicalVolume.GetVGInfo([name], excl_stor)
579 vg_free = int(round(vginfo[0][0], 0))
580 vg_size = int(round(vginfo[0][1], 0))
592 def _GetHvInfo(name):
593 """Retrieves node information from a hypervisor.
595 The information returned depends on the hypervisor. Common items:
597 - vg_size is the size of the configured volume group in MiB
598 - vg_free is the free size of the volume group in MiB
599 - memory_dom0 is the memory allocated for domain0 in MiB
600 - memory_free is the currently available (free) ram in MiB
601 - memory_total is the total number of ram in MiB
602 - hv_version: the hypervisor version, if available
605 return hypervisor.GetHypervisor(name).GetNodeInfo()
608 def _GetNamedNodeInfo(names, fn):
609 """Calls C{fn} for all names in C{names} and returns a dictionary.
617 return map(fn, names)
620 def GetNodeInfo(vg_names, hv_names, excl_stor):
621 """Gives back a hash with different information about the node.
623 @type vg_names: list of string
624 @param vg_names: Names of the volume groups to ask for disk space information
625 @type hv_names: list of string
626 @param hv_names: Names of the hypervisors to ask for node information
627 @type excl_stor: boolean
628 @param excl_stor: Whether exclusive_storage is active
629 @rtype: tuple; (string, None/dict, None/dict)
630 @return: Tuple containing boot ID, volume group information and hypervisor
634 bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
635 vg_info = _GetNamedNodeInfo(vg_names, (lambda vg: _GetVgInfo(vg, excl_stor)))
636 hv_info = _GetNamedNodeInfo(hv_names, _GetHvInfo)
638 return (bootid, vg_info, hv_info)
641 def _CheckExclusivePvs(pvi_list):
642 """Check that PVs are not shared among LVs
644 @type pvi_list: list of L{objects.LvmPvInfo} objects
645 @param pvi_list: information about the PVs
647 @rtype: list of tuples (string, list of strings)
648 @return: offending volumes, as tuples: (pv_name, [lv1_name, lv2_name...])
653 if len(pvi.lv_list) > 1:
654 res.append((pvi.name, pvi.lv_list))
658 def VerifyNode(what, cluster_name):
659 """Verify the status of the local node.
661 Based on the input L{what} parameter, various checks are done on the
664 If the I{filelist} key is present, this list of
665 files is checksummed and the file/checksum pairs are returned.
667 If the I{nodelist} key is present, we check that we have
668 connectivity via ssh with the target nodes (and check the hostname
671 If the I{node-net-test} key is present, we check that we have
672 connectivity to the given nodes via both primary IP and, if
673 applicable, secondary IPs.
676 @param what: a dictionary of things to check:
677 - filelist: list of files for which to compute checksums
678 - nodelist: list of nodes we should check ssh communication with
679 - node-net-test: list of nodes we should check node daemon port
681 - hypervisor: list with hypervisors to run the verify for
683 @return: a dictionary with the same keys as the input dict, and
684 values representing the result of the checks
688 my_name = netutils.Hostname.GetSysName()
689 port = netutils.GetDaemonPort(constants.NODED)
690 vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
692 if constants.NV_HYPERVISOR in what and vm_capable:
693 result[constants.NV_HYPERVISOR] = tmp = {}
694 for hv_name in what[constants.NV_HYPERVISOR]:
696 val = hypervisor.GetHypervisor(hv_name).Verify()
697 except errors.HypervisorError, err:
698 val = "Error while checking hypervisor: %s" % str(err)
701 if constants.NV_HVPARAMS in what and vm_capable:
702 result[constants.NV_HVPARAMS] = tmp = []
703 for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
705 logging.info("Validating hv %s, %s", hv_name, hvparms)
706 hypervisor.GetHypervisor(hv_name).ValidateParameters(hvparms)
707 except errors.HypervisorError, err:
708 tmp.append((source, hv_name, str(err)))
710 if constants.NV_FILELIST in what:
711 fingerprints = utils.FingerprintFiles(map(vcluster.LocalizeVirtualPath,
712 what[constants.NV_FILELIST]))
713 result[constants.NV_FILELIST] = \
714 dict((vcluster.MakeVirtualPath(key), value)
715 for (key, value) in fingerprints.items())
717 if constants.NV_NODELIST in what:
718 (nodes, bynode) = what[constants.NV_NODELIST]
720 # Add nodes from other groups (different for each node)
722 nodes.extend(bynode[my_name])
727 random.shuffle(nodes)
729 # Try to contact all nodes
732 success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
736 result[constants.NV_NODELIST] = val
738 if constants.NV_NODENETTEST in what:
739 result[constants.NV_NODENETTEST] = tmp = {}
740 my_pip = my_sip = None
741 for name, pip, sip in what[constants.NV_NODENETTEST]:
747 tmp[my_name] = ("Can't find my own primary/secondary IP"
750 for name, pip, sip in what[constants.NV_NODENETTEST]:
752 if not netutils.TcpPing(pip, port, source=my_pip):
753 fail.append("primary")
755 if not netutils.TcpPing(sip, port, source=my_sip):
756 fail.append("secondary")
758 tmp[name] = ("failure using the %s interface(s)" %
761 if constants.NV_MASTERIP in what:
762 # FIXME: add checks on incoming data structures (here and in the
763 # rest of the function)
764 master_name, master_ip = what[constants.NV_MASTERIP]
765 if master_name == my_name:
766 source = constants.IP4_ADDRESS_LOCALHOST
769 result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
772 if constants.NV_USERSCRIPTS in what:
773 result[constants.NV_USERSCRIPTS] = \
774 [script for script in what[constants.NV_USERSCRIPTS]
775 if not utils.IsExecutable(script)]
777 if constants.NV_OOB_PATHS in what:
778 result[constants.NV_OOB_PATHS] = tmp = []
779 for path in what[constants.NV_OOB_PATHS]:
783 tmp.append("error stating out of band helper: %s" % err)
785 if stat.S_ISREG(st.st_mode):
786 if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
789 tmp.append("out of band helper %s is not executable" % path)
791 tmp.append("out of band helper %s is not a file" % path)
793 if constants.NV_LVLIST in what and vm_capable:
795 val = GetVolumeList(utils.ListVolumeGroups().keys())
798 result[constants.NV_LVLIST] = val
800 if constants.NV_INSTANCELIST in what and vm_capable:
801 # GetInstanceList can fail
803 val = GetInstanceList(what[constants.NV_INSTANCELIST])
806 result[constants.NV_INSTANCELIST] = val
808 if constants.NV_VGLIST in what and vm_capable:
809 result[constants.NV_VGLIST] = utils.ListVolumeGroups()
811 if constants.NV_PVLIST in what and vm_capable:
812 check_exclusive_pvs = constants.NV_EXCLUSIVEPVS in what
813 val = bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
814 filter_allocatable=False,
815 include_lvs=check_exclusive_pvs)
816 if check_exclusive_pvs:
817 result[constants.NV_EXCLUSIVEPVS] = _CheckExclusivePvs(val)
819 # Avoid sending useless data on the wire
821 result[constants.NV_PVLIST] = map(objects.LvmPvInfo.ToDict, val)
823 if constants.NV_VERSION in what:
824 result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
825 constants.RELEASE_VERSION)
827 if constants.NV_HVINFO in what and vm_capable:
828 hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
829 result[constants.NV_HVINFO] = hyper.GetNodeInfo()
831 if constants.NV_DRBDLIST in what and vm_capable:
833 used_minors = bdev.DRBD8.GetUsedDevs().keys()
834 except errors.BlockDeviceError, err:
835 logging.warning("Can't get used minors list", exc_info=True)
836 used_minors = str(err)
837 result[constants.NV_DRBDLIST] = used_minors
839 if constants.NV_DRBDHELPER in what and vm_capable:
842 payload = bdev.BaseDRBD.GetUsermodeHelper()
843 except errors.BlockDeviceError, err:
844 logging.error("Can't get DRBD usermode helper: %s", str(err))
847 result[constants.NV_DRBDHELPER] = (status, payload)
849 if constants.NV_NODESETUP in what:
850 result[constants.NV_NODESETUP] = tmpr = []
851 if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
852 tmpr.append("The sysfs filesytem doesn't seem to be mounted"
853 " under /sys, missing required directories /sys/block"
854 " and /sys/class/net")
855 if (not os.path.isdir("/proc/sys") or
856 not os.path.isfile("/proc/sysrq-trigger")):
857 tmpr.append("The procfs filesystem doesn't seem to be mounted"
858 " under /proc, missing required directory /proc/sys and"
859 " the file /proc/sysrq-trigger")
861 if constants.NV_TIME in what:
862 result[constants.NV_TIME] = utils.SplitTime(time.time())
864 if constants.NV_OSLIST in what and vm_capable:
865 result[constants.NV_OSLIST] = DiagnoseOS()
867 if constants.NV_BRIDGES in what and vm_capable:
868 result[constants.NV_BRIDGES] = [bridge
869 for bridge in what[constants.NV_BRIDGES]
870 if not utils.BridgeExists(bridge)]
872 if what.get(constants.NV_FILE_STORAGE_PATHS) == my_name:
873 result[constants.NV_FILE_STORAGE_PATHS] = \
874 bdev.ComputeWrongFileStoragePaths()
879 def GetBlockDevSizes(devices):
880 """Return the size of the given block devices
883 @param devices: list of block device nodes to query
886 dictionary of all block devices under /dev (key). The value is their
889 {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
895 for devpath in devices:
896 if not utils.IsBelowDir(DEV_PREFIX, devpath):
900 st = os.stat(devpath)
901 except EnvironmentError, err:
902 logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
905 if stat.S_ISBLK(st.st_mode):
906 result = utils.RunCmd(["blockdev", "--getsize64", devpath])
908 # We don't want to fail, just do not list this device as available
909 logging.warning("Cannot get size for block device %s", devpath)
912 size = int(result.stdout) / (1024 * 1024)
913 blockdevs[devpath] = size
917 def GetVolumeList(vg_names):
918 """Compute list of logical volumes and their size.
921 @param vg_names: the volume groups whose LVs we should list, or
922 empty for all volume groups
925 dictionary of all partions (key) with value being a tuple of
926 their size (in MiB), inactive and online status::
928 {'xenvg/test1': ('20.06', True, True)}
930 in case of errors, a string is returned with the error
938 result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
939 "--separator=%s" % sep,
940 "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
942 _Fail("Failed to list logical volumes, lvs output: %s", result.output)
944 for line in result.stdout.splitlines():
946 match = _LVSLINE_REGEX.match(line)
948 logging.error("Invalid line returned from lvs output: '%s'", line)
950 vg_name, name, size, attr = match.groups()
951 inactive = attr[4] == "-"
952 online = attr[5] == "o"
953 virtual = attr[0] == "v"
955 # we don't want to report such volumes as existing, since they
956 # don't really hold data
958 lvs[vg_name + "/" + name] = (size, inactive, online)
963 def ListVolumeGroups():
964 """List the volume groups and their size.
967 @return: dictionary with keys volume name and values the
971 return utils.ListVolumeGroups()
975 """List all volumes on this node.
979 A list of dictionaries, each having four keys:
980 - name: the logical volume name,
981 - size: the size of the logical volume
982 - dev: the physical device on which the LV lives
983 - vg: the volume group to which it belongs
985 In case of errors, we return an empty list and log the
988 Note that since a logical volume can live on multiple physical
989 volumes, the resulting list might include a logical volume
993 result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
995 "--options=lv_name,lv_size,devices,vg_name"])
997 _Fail("Failed to list logical volumes, lvs output: %s",
1001 return dev.split("(")[0]
1003 def handle_dev(dev):
1004 return [parse_dev(x) for x in dev.split(",")]
1007 line = [v.strip() for v in line]
1008 return [{"name": line[0], "size": line[1],
1009 "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
1012 for line in result.stdout.splitlines():
1013 if line.count("|") >= 3:
1014 all_devs.extend(map_line(line.split("|")))
1016 logging.warning("Strange line in the output from lvs: '%s'", line)
1020 def BridgesExist(bridges_list):
1021 """Check if a list of bridges exist on the current node.
1024 @return: C{True} if all of them exist, C{False} otherwise
1028 for bridge in bridges_list:
1029 if not utils.BridgeExists(bridge):
1030 missing.append(bridge)
1033 _Fail("Missing bridges %s", utils.CommaJoin(missing))
1036 def GetInstanceList(hypervisor_list):
1037 """Provides a list of instances.
1039 @type hypervisor_list: list
1040 @param hypervisor_list: the list of hypervisors to query information
1043 @return: a list of all running instances on the current node
1044 - instance1.example.com
1045 - instance2.example.com
1049 for hname in hypervisor_list:
1051 names = hypervisor.GetHypervisor(hname).ListInstances()
1052 results.extend(names)
1053 except errors.HypervisorError, err:
1054 _Fail("Error enumerating instances (hypervisor %s): %s",
1055 hname, err, exc=True)
1060 def GetInstanceInfo(instance, hname):
1061 """Gives back the information about an instance as a dictionary.
1063 @type instance: string
1064 @param instance: the instance name
1066 @param hname: the hypervisor type of the instance
1069 @return: dictionary with the following keys:
1070 - memory: memory size of instance (int)
1071 - state: xen state of instance (string)
1072 - time: cpu time of instance (float)
1073 - vcpus: the number of vcpus (int)
1078 iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
1079 if iinfo is not None:
1080 output["memory"] = iinfo[2]
1081 output["vcpus"] = iinfo[3]
1082 output["state"] = iinfo[4]
1083 output["time"] = iinfo[5]
1088 def GetInstanceMigratable(instance):
1089 """Gives whether an instance can be migrated.
1091 @type instance: L{objects.Instance}
1092 @param instance: object representing the instance to be checked.
1095 @return: tuple of (result, description) where:
1096 - result: whether the instance can be migrated or not
1097 - description: a description of the issue, if relevant
1100 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1101 iname = instance.name
1102 if iname not in hyper.ListInstances():
1103 _Fail("Instance %s is not running", iname)
1105 for idx in range(len(instance.disks)):
1106 link_name = _GetBlockDevSymlinkPath(iname, idx)
1107 if not os.path.islink(link_name):
1108 logging.warning("Instance %s is missing symlink %s for disk %d",
1109 iname, link_name, idx)
1112 def GetAllInstancesInfo(hypervisor_list):
1113 """Gather data about all instances.
1115 This is the equivalent of L{GetInstanceInfo}, except that it
1116 computes data for all instances at once, thus being faster if one
1117 needs data about more than one instance.
1119 @type hypervisor_list: list
1120 @param hypervisor_list: list of hypervisors to query for instance data
1123 @return: dictionary of instance: data, with data having the following keys:
1124 - memory: memory size of instance (int)
1125 - state: xen state of instance (string)
1126 - time: cpu time of instance (float)
1127 - vcpus: the number of vcpus
1132 for hname in hypervisor_list:
1133 iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
1135 for name, _, memory, vcpus, state, times in iinfo:
1143 # we only check static parameters, like memory and vcpus,
1144 # and not state and time which can change between the
1145 # invocations of the different hypervisors
1146 for key in "memory", "vcpus":
1147 if value[key] != output[name][key]:
1148 _Fail("Instance %s is running twice"
1149 " with different parameters", name)
1150 output[name] = value
1155 def _InstanceLogName(kind, os_name, instance, component):
1156 """Compute the OS log filename for a given instance and operation.
1158 The instance name and os name are passed in as strings since not all
1159 operations have these as part of an instance object.
1162 @param kind: the operation type (e.g. add, import, etc.)
1163 @type os_name: string
1164 @param os_name: the os name
1165 @type instance: string
1166 @param instance: the name of the instance being imported/added/etc.
1167 @type component: string or None
1168 @param component: the name of the component of the instance being
1172 # TODO: Use tempfile.mkstemp to create unique filename
1174 assert "/" not in component
1175 c_msg = "-%s" % component
1178 base = ("%s-%s-%s%s-%s.log" %
1179 (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1180 return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1183 def InstanceOsAdd(instance, reinstall, debug):
1184 """Add an OS to an instance.
1186 @type instance: L{objects.Instance}
1187 @param instance: Instance whose OS is to be installed
1188 @type reinstall: boolean
1189 @param reinstall: whether this is an instance reinstall
1190 @type debug: integer
1191 @param debug: debug level, passed to the OS scripts
1195 inst_os = OSFromDisk(instance.os)
1197 create_env = OSEnvironment(instance, inst_os, debug)
1199 create_env["INSTANCE_REINSTALL"] = "1"
1201 logfile = _InstanceLogName("add", instance.os, instance.name, None)
1203 result = utils.RunCmd([inst_os.create_script], env=create_env,
1204 cwd=inst_os.path, output=logfile, reset_env=True)
1206 logging.error("os create command '%s' returned error: %s, logfile: %s,"
1207 " output: %s", result.cmd, result.fail_reason, logfile,
1209 lines = [utils.SafeEncode(val)
1210 for val in utils.TailFile(logfile, lines=20)]
1211 _Fail("OS create script failed (%s), last lines in the"
1212 " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1215 def RunRenameInstance(instance, old_name, debug):
1216 """Run the OS rename script for an instance.
1218 @type instance: L{objects.Instance}
1219 @param instance: Instance whose OS is to be installed
1220 @type old_name: string
1221 @param old_name: previous instance name
1222 @type debug: integer
1223 @param debug: debug level, passed to the OS scripts
1225 @return: the success of the operation
1228 inst_os = OSFromDisk(instance.os)
1230 rename_env = OSEnvironment(instance, inst_os, debug)
1231 rename_env["OLD_INSTANCE_NAME"] = old_name
1233 logfile = _InstanceLogName("rename", instance.os,
1234 "%s-%s" % (old_name, instance.name), None)
1236 result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1237 cwd=inst_os.path, output=logfile, reset_env=True)
1240 logging.error("os create command '%s' returned error: %s output: %s",
1241 result.cmd, result.fail_reason, result.output)
1242 lines = [utils.SafeEncode(val)
1243 for val in utils.TailFile(logfile, lines=20)]
1244 _Fail("OS rename script failed (%s), last lines in the"
1245 " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1248 def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1249 """Returns symlink path for block device.
1253 _dir = pathutils.DISK_LINKS_DIR
1255 return utils.PathJoin(_dir,
1257 (instance_name, constants.DISK_SEPARATOR, idx)))
1260 def _SymlinkBlockDev(instance_name, device_path, idx):
1261 """Set up symlinks to a instance's block device.
1263 This is an auxiliary function run when an instance is start (on the primary
1264 node) or when an instance is migrated (on the target node).
1267 @param instance_name: the name of the target instance
1268 @param device_path: path of the physical block device, on the node
1269 @param idx: the disk index
1270 @return: absolute path to the disk's symlink
1273 link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1275 os.symlink(device_path, link_name)
1276 except OSError, err:
1277 if err.errno == errno.EEXIST:
1278 if (not os.path.islink(link_name) or
1279 os.readlink(link_name) != device_path):
1280 os.remove(link_name)
1281 os.symlink(device_path, link_name)
1288 def _RemoveBlockDevLinks(instance_name, disks):
1289 """Remove the block device symlinks belonging to the given instance.
1292 for idx, _ in enumerate(disks):
1293 link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1294 if os.path.islink(link_name):
1296 os.remove(link_name)
1298 logging.exception("Can't remove symlink '%s'", link_name)
1301 def _GatherAndLinkBlockDevs(instance):
1302 """Set up an instance's block device(s).
1304 This is run on the primary node at instance startup. The block
1305 devices must be already assembled.
1307 @type instance: L{objects.Instance}
1308 @param instance: the instance whose disks we shoul assemble
1310 @return: list of (disk_object, device_path)
1314 for idx, disk in enumerate(instance.disks):
1315 device = _RecursiveFindBD(disk)
1317 raise errors.BlockDeviceError("Block device '%s' is not set up." %
1321 link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1323 raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1326 block_devices.append((disk, link_name))
1328 return block_devices
1331 def StartInstance(instance, startup_paused, reason, store_reason=True):
1332 """Start an instance.
1334 @type instance: L{objects.Instance}
1335 @param instance: the instance object
1336 @type startup_paused: bool
1337 @param instance: pause instance at startup?
1338 @type reason: list of reasons
1339 @param reason: the reason trail for this startup
1340 @type store_reason: boolean
1341 @param store_reason: whether to store the shutdown reason trail on file
1345 running_instances = GetInstanceList([instance.hypervisor])
1347 if instance.name in running_instances:
1348 logging.info("Instance %s already running, not starting", instance.name)
1352 block_devices = _GatherAndLinkBlockDevs(instance)
1353 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1354 hyper.StartInstance(instance, block_devices, startup_paused)
1356 _StoreInstReasonTrail(instance.name, reason)
1357 except errors.BlockDeviceError, err:
1358 _Fail("Block device error: %s", err, exc=True)
1359 except errors.HypervisorError, err:
1360 _RemoveBlockDevLinks(instance.name, instance.disks)
1361 _Fail("Hypervisor error: %s", err, exc=True)
1364 def InstanceShutdown(instance, timeout, reason, store_reason=True):
1365 """Shut an instance down.
1367 @note: this functions uses polling with a hardcoded timeout.
1369 @type instance: L{objects.Instance}
1370 @param instance: the instance object
1371 @type timeout: integer
1372 @param timeout: maximum timeout for soft shutdown
1373 @type reason: list of reasons
1374 @param reason: the reason trail for this shutdown
1375 @type store_reason: boolean
1376 @param store_reason: whether to store the shutdown reason trail on file
1380 hv_name = instance.hypervisor
1381 hyper = hypervisor.GetHypervisor(hv_name)
1382 iname = instance.name
1384 if instance.name not in hyper.ListInstances():
1385 logging.info("Instance %s not running, doing nothing", iname)
1390 self.tried_once = False
1393 if iname not in hyper.ListInstances():
1397 hyper.StopInstance(instance, retry=self.tried_once)
1399 _StoreInstReasonTrail(instance.name, reason)
1400 except errors.HypervisorError, err:
1401 if iname not in hyper.ListInstances():
1402 # if the instance is no longer existing, consider this a
1403 # success and go to cleanup
1406 _Fail("Failed to stop instance %s: %s", iname, err)
1408 self.tried_once = True
1410 raise utils.RetryAgain()
1413 utils.Retry(_TryShutdown(), 5, timeout)
1414 except utils.RetryTimeout:
1415 # the shutdown did not succeed
1416 logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1419 hyper.StopInstance(instance, force=True)
1420 except errors.HypervisorError, err:
1421 if iname in hyper.ListInstances():
1422 # only raise an error if the instance still exists, otherwise
1423 # the error could simply be "instance ... unknown"!
1424 _Fail("Failed to force stop instance %s: %s", iname, err)
1428 if iname in hyper.ListInstances():
1429 _Fail("Could not shutdown instance %s even by destroy", iname)
1432 hyper.CleanupInstance(instance.name)
1433 except errors.HypervisorError, err:
1434 logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1436 _RemoveBlockDevLinks(iname, instance.disks)
1439 def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1440 """Reboot an instance.
1442 @type instance: L{objects.Instance}
1443 @param instance: the instance object to reboot
1444 @type reboot_type: str
1445 @param reboot_type: the type of reboot, one the following
1447 - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1448 instance OS, do not recreate the VM
1449 - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1450 restart the VM (at the hypervisor level)
1451 - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1452 not accepted here, since that mode is handled differently, in
1453 cmdlib, and translates into full stop and start of the
1454 instance (instead of a call_instance_reboot RPC)
1455 @type shutdown_timeout: integer
1456 @param shutdown_timeout: maximum timeout for soft shutdown
1457 @type reason: list of reasons
1458 @param reason: the reason trail for this reboot
1462 running_instances = GetInstanceList([instance.hypervisor])
1464 if instance.name not in running_instances:
1465 _Fail("Cannot reboot instance %s that is not running", instance.name)
1467 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1468 if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1470 hyper.RebootInstance(instance)
1471 except errors.HypervisorError, err:
1472 _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1473 elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1475 InstanceShutdown(instance, shutdown_timeout, reason, store_reason=False)
1476 result = StartInstance(instance, False, reason, store_reason=False)
1477 _StoreInstReasonTrail(instance.name, reason)
1479 except errors.HypervisorError, err:
1480 _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1482 _Fail("Invalid reboot_type received: %s", reboot_type)
1485 def InstanceBalloonMemory(instance, memory):
1486 """Resize an instance's memory.
1488 @type instance: L{objects.Instance}
1489 @param instance: the instance object
1491 @param memory: new memory amount in MB
1495 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1496 running = hyper.ListInstances()
1497 if instance.name not in running:
1498 logging.info("Instance %s is not running, cannot balloon", instance.name)
1501 hyper.BalloonInstanceMemory(instance, memory)
1502 except errors.HypervisorError, err:
1503 _Fail("Failed to balloon instance memory: %s", err, exc=True)
1506 def MigrationInfo(instance):
1507 """Gather information about an instance to be migrated.
1509 @type instance: L{objects.Instance}
1510 @param instance: the instance definition
1513 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1515 info = hyper.MigrationInfo(instance)
1516 except errors.HypervisorError, err:
1517 _Fail("Failed to fetch migration information: %s", err, exc=True)
1521 def AcceptInstance(instance, info, target):
1522 """Prepare the node to accept an instance.
1524 @type instance: L{objects.Instance}
1525 @param instance: the instance definition
1526 @type info: string/data (opaque)
1527 @param info: migration information, from the source node
1528 @type target: string
1529 @param target: target host (usually ip), on this node
1532 # TODO: why is this required only for DTS_EXT_MIRROR?
1533 if instance.disk_template in constants.DTS_EXT_MIRROR:
1534 # Create the symlinks, as the disks are not active
1537 _GatherAndLinkBlockDevs(instance)
1538 except errors.BlockDeviceError, err:
1539 _Fail("Block device error: %s", err, exc=True)
1541 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1543 hyper.AcceptInstance(instance, info, target)
1544 except errors.HypervisorError, err:
1545 if instance.disk_template in constants.DTS_EXT_MIRROR:
1546 _RemoveBlockDevLinks(instance.name, instance.disks)
1547 _Fail("Failed to accept instance: %s", err, exc=True)
1550 def FinalizeMigrationDst(instance, info, success):
1551 """Finalize any preparation to accept an instance.
1553 @type instance: L{objects.Instance}
1554 @param instance: the instance definition
1555 @type info: string/data (opaque)
1556 @param info: migration information, from the source node
1557 @type success: boolean
1558 @param success: whether the migration was a success or a failure
1561 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1563 hyper.FinalizeMigrationDst(instance, info, success)
1564 except errors.HypervisorError, err:
1565 _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1568 def MigrateInstance(instance, target, live):
1569 """Migrates an instance to another node.
1571 @type instance: L{objects.Instance}
1572 @param instance: the instance definition
1573 @type target: string
1574 @param target: the target node name
1576 @param live: whether the migration should be done live or not (the
1577 interpretation of this parameter is left to the hypervisor)
1578 @raise RPCFail: if migration fails for some reason
1581 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1584 hyper.MigrateInstance(instance, target, live)
1585 except errors.HypervisorError, err:
1586 _Fail("Failed to migrate instance: %s", err, exc=True)
1589 def FinalizeMigrationSource(instance, success, live):
1590 """Finalize the instance migration on the source node.
1592 @type instance: L{objects.Instance}
1593 @param instance: the instance definition of the migrated instance
1595 @param success: whether the migration succeeded or not
1597 @param live: whether the user requested a live migration or not
1598 @raise RPCFail: If the execution fails for some reason
1601 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1604 hyper.FinalizeMigrationSource(instance, success, live)
1605 except Exception, err: # pylint: disable=W0703
1606 _Fail("Failed to finalize the migration on the source node: %s", err,
1610 def GetMigrationStatus(instance):
1611 """Get the migration status
1613 @type instance: L{objects.Instance}
1614 @param instance: the instance that is being migrated
1615 @rtype: L{objects.MigrationStatus}
1616 @return: the status of the current migration (one of
1617 L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1618 progress info that can be retrieved from the hypervisor
1619 @raise RPCFail: If the migration status cannot be retrieved
1622 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1624 return hyper.GetMigrationStatus(instance)
1625 except Exception, err: # pylint: disable=W0703
1626 _Fail("Failed to get migration status: %s", err, exc=True)
1629 def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
1630 """Creates a block device for an instance.
1632 @type disk: L{objects.Disk}
1633 @param disk: the object describing the disk we should create
1635 @param size: the size of the physical underlying device, in MiB
1637 @param owner: the name of the instance for which disk is created,
1638 used for device cache data
1639 @type on_primary: boolean
1640 @param on_primary: indicates if it is the primary node or not
1642 @param info: string that will be sent to the physical device
1643 creation, used for example to set (LVM) tags on LVs
1644 @type excl_stor: boolean
1645 @param excl_stor: Whether exclusive_storage is active
1647 @return: the new unique_id of the device (this can sometime be
1648 computed only after creation), or None. On secondary nodes,
1649 it's not required to return anything.
1652 # TODO: remove the obsolete "size" argument
1653 # pylint: disable=W0613
1656 for child in disk.children:
1658 crdev = _RecursiveAssembleBD(child, owner, on_primary)
1659 except errors.BlockDeviceError, err:
1660 _Fail("Can't assemble device %s: %s", child, err)
1661 if on_primary or disk.AssembleOnSecondary():
1662 # we need the children open in case the device itself has to
1665 # pylint: disable=E1103
1667 except errors.BlockDeviceError, err:
1668 _Fail("Can't make child '%s' read-write: %s", child, err)
1672 device = bdev.Create(disk, clist, excl_stor)
1673 except errors.BlockDeviceError, err:
1674 _Fail("Can't create block device: %s", err)
1676 if on_primary or disk.AssembleOnSecondary():
1679 except errors.BlockDeviceError, err:
1680 _Fail("Can't assemble device after creation, unusual event: %s", err)
1681 if on_primary or disk.OpenOnSecondary():
1683 device.Open(force=True)
1684 except errors.BlockDeviceError, err:
1685 _Fail("Can't make device r/w after creation, unusual event: %s", err)
1686 DevCacheManager.UpdateCache(device.dev_path, owner,
1687 on_primary, disk.iv_name)
1689 device.SetInfo(info)
1691 return device.unique_id
1694 def _WipeDevice(path, offset, size):
1695 """This function actually wipes the device.
1697 @param path: The path to the device to wipe
1698 @param offset: The offset in MiB in the file
1699 @param size: The size in MiB to write
1702 # Internal sizes are always in Mebibytes; if the following "dd" command
1703 # should use a different block size the offset and size given to this
1704 # function must be adjusted accordingly before being passed to "dd".
1705 block_size = 1024 * 1024
1707 cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1708 "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
1710 result = utils.RunCmd(cmd)
1713 _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1714 result.fail_reason, result.output)
1717 def BlockdevWipe(disk, offset, size):
1718 """Wipes a block device.
1720 @type disk: L{objects.Disk}
1721 @param disk: the disk object we want to wipe
1723 @param offset: The offset in MiB in the file
1725 @param size: The size in MiB to write
1729 rdev = _RecursiveFindBD(disk)
1730 except errors.BlockDeviceError:
1734 _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1736 # Do cross verify some of the parameters
1738 _Fail("Negative offset")
1740 _Fail("Negative size")
1741 if offset > rdev.size:
1742 _Fail("Offset is bigger than device size")
1743 if (offset + size) > rdev.size:
1744 _Fail("The provided offset and size to wipe is bigger than device size")
1746 _WipeDevice(rdev.dev_path, offset, size)
1749 def BlockdevPauseResumeSync(disks, pause):
1750 """Pause or resume the sync of the block device.
1752 @type disks: list of L{objects.Disk}
1753 @param disks: the disks object we want to pause/resume
1755 @param pause: Wheater to pause or resume
1761 rdev = _RecursiveFindBD(disk)
1762 except errors.BlockDeviceError:
1766 success.append((False, ("Cannot change sync for device %s:"
1767 " device not found" % disk.iv_name)))
1770 result = rdev.PauseResumeSync(pause)
1773 success.append((result, None))
1779 success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1784 def BlockdevRemove(disk):
1785 """Remove a block device.
1787 @note: This is intended to be called recursively.
1789 @type disk: L{objects.Disk}
1790 @param disk: the disk object we should remove
1792 @return: the success of the operation
1797 rdev = _RecursiveFindBD(disk)
1798 except errors.BlockDeviceError, err:
1799 # probably can't attach
1800 logging.info("Can't attach to device %s in remove", disk)
1802 if rdev is not None:
1803 r_path = rdev.dev_path
1806 except errors.BlockDeviceError, err:
1807 msgs.append(str(err))
1809 DevCacheManager.RemoveCache(r_path)
1812 for child in disk.children:
1814 BlockdevRemove(child)
1815 except RPCFail, err:
1816 msgs.append(str(err))
1819 _Fail("; ".join(msgs))
1822 def _RecursiveAssembleBD(disk, owner, as_primary):
1823 """Activate a block device for an instance.
1825 This is run on the primary and secondary nodes for an instance.
1827 @note: this function is called recursively.
1829 @type disk: L{objects.Disk}
1830 @param disk: the disk we try to assemble
1832 @param owner: the name of the instance which owns the disk
1833 @type as_primary: boolean
1834 @param as_primary: if we should make the block device
1837 @return: the assembled device or None (in case no device
1839 @raise errors.BlockDeviceError: in case there is an error
1840 during the activation of the children or the device
1846 mcn = disk.ChildrenNeeded()
1848 mcn = 0 # max number of Nones allowed
1850 mcn = len(disk.children) - mcn # max number of Nones
1851 for chld_disk in disk.children:
1853 cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1854 except errors.BlockDeviceError, err:
1855 if children.count(None) >= mcn:
1858 logging.error("Error in child activation (but continuing): %s",
1860 children.append(cdev)
1862 if as_primary or disk.AssembleOnSecondary():
1863 r_dev = bdev.Assemble(disk, children)
1865 if as_primary or disk.OpenOnSecondary():
1867 DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1868 as_primary, disk.iv_name)
1875 def BlockdevAssemble(disk, owner, as_primary, idx):
1876 """Activate a block device for an instance.
1878 This is a wrapper over _RecursiveAssembleBD.
1880 @rtype: str or boolean
1881 @return: a C{/dev/...} path for primary nodes, and
1882 C{True} for secondary nodes
1886 result = _RecursiveAssembleBD(disk, owner, as_primary)
1887 if isinstance(result, bdev.BlockDev):
1888 # pylint: disable=E1103
1889 result = result.dev_path
1891 _SymlinkBlockDev(owner, result, idx)
1892 except errors.BlockDeviceError, err:
1893 _Fail("Error while assembling disk: %s", err, exc=True)
1894 except OSError, err:
1895 _Fail("Error while symlinking disk: %s", err, exc=True)
1900 def BlockdevShutdown(disk):
1901 """Shut down a block device.
1903 First, if the device is assembled (Attach() is successful), then
1904 the device is shutdown. Then the children of the device are
1907 This function is called recursively. Note that we don't cache the
1908 children or such, as oppossed to assemble, shutdown of different
1909 devices doesn't require that the upper device was active.
1911 @type disk: L{objects.Disk}
1912 @param disk: the description of the disk we should
1918 r_dev = _RecursiveFindBD(disk)
1919 if r_dev is not None:
1920 r_path = r_dev.dev_path
1923 DevCacheManager.RemoveCache(r_path)
1924 except errors.BlockDeviceError, err:
1925 msgs.append(str(err))
1928 for child in disk.children:
1930 BlockdevShutdown(child)
1931 except RPCFail, err:
1932 msgs.append(str(err))
1935 _Fail("; ".join(msgs))
1938 def BlockdevAddchildren(parent_cdev, new_cdevs):
1939 """Extend a mirrored block device.
1941 @type parent_cdev: L{objects.Disk}
1942 @param parent_cdev: the disk to which we should add children
1943 @type new_cdevs: list of L{objects.Disk}
1944 @param new_cdevs: the list of children which we should add
1948 parent_bdev = _RecursiveFindBD(parent_cdev)
1949 if parent_bdev is None:
1950 _Fail("Can't find parent device '%s' in add children", parent_cdev)
1951 new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1952 if new_bdevs.count(None) > 0:
1953 _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1954 parent_bdev.AddChildren(new_bdevs)
1957 def BlockdevRemovechildren(parent_cdev, new_cdevs):
1958 """Shrink a mirrored block device.
1960 @type parent_cdev: L{objects.Disk}
1961 @param parent_cdev: the disk from which we should remove children
1962 @type new_cdevs: list of L{objects.Disk}
1963 @param new_cdevs: the list of children which we should remove
1967 parent_bdev = _RecursiveFindBD(parent_cdev)
1968 if parent_bdev is None:
1969 _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1971 for disk in new_cdevs:
1972 rpath = disk.StaticDevPath()
1974 bd = _RecursiveFindBD(disk)
1976 _Fail("Can't find device %s while removing children", disk)
1978 devs.append(bd.dev_path)
1980 if not utils.IsNormAbsPath(rpath):
1981 _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
1983 parent_bdev.RemoveChildren(devs)
1986 def BlockdevGetmirrorstatus(disks):
1987 """Get the mirroring status of a list of devices.
1989 @type disks: list of L{objects.Disk}
1990 @param disks: the list of disks which we should query
1992 @return: List of L{objects.BlockDevStatus}, one for each disk
1993 @raise errors.BlockDeviceError: if any of the disks cannot be
1999 rbd = _RecursiveFindBD(dsk)
2001 _Fail("Can't find device %s", dsk)
2003 stats.append(rbd.CombinedSyncStatus())
2008 def BlockdevGetmirrorstatusMulti(disks):
2009 """Get the mirroring status of a list of devices.
2011 @type disks: list of L{objects.Disk}
2012 @param disks: the list of disks which we should query
2014 @return: List of tuples, (bool, status), one for each disk; bool denotes
2015 success/failure, status is L{objects.BlockDevStatus} on success, string
2022 rbd = _RecursiveFindBD(disk)
2024 result.append((False, "Can't find device %s" % disk))
2027 status = rbd.CombinedSyncStatus()
2028 except errors.BlockDeviceError, err:
2029 logging.exception("Error while getting disk status")
2030 result.append((False, str(err)))
2032 result.append((True, status))
2034 assert len(disks) == len(result)
2039 def _RecursiveFindBD(disk):
2040 """Check if a device is activated.
2042 If so, return information about the real device.
2044 @type disk: L{objects.Disk}
2045 @param disk: the disk object we need to find
2047 @return: None if the device can't be found,
2048 otherwise the device instance
2053 for chdisk in disk.children:
2054 children.append(_RecursiveFindBD(chdisk))
2056 return bdev.FindDevice(disk, children)
2059 def _OpenRealBD(disk):
2060 """Opens the underlying block device of a disk.
2062 @type disk: L{objects.Disk}
2063 @param disk: the disk object we want to open
2066 real_disk = _RecursiveFindBD(disk)
2067 if real_disk is None:
2068 _Fail("Block device '%s' is not set up", disk)
2075 def BlockdevFind(disk):
2076 """Check if a device is activated.
2078 If it is, return information about the real device.
2080 @type disk: L{objects.Disk}
2081 @param disk: the disk to find
2082 @rtype: None or objects.BlockDevStatus
2083 @return: None if the disk cannot be found, otherwise a the current
2088 rbd = _RecursiveFindBD(disk)
2089 except errors.BlockDeviceError, err:
2090 _Fail("Failed to find device: %s", err, exc=True)
2095 return rbd.GetSyncStatus()
2098 def BlockdevGetsize(disks):
2099 """Computes the size of the given disks.
2101 If a disk is not found, returns None instead.
2103 @type disks: list of L{objects.Disk}
2104 @param disks: the list of disk to compute the size for
2106 @return: list with elements None if the disk cannot be found,
2113 rbd = _RecursiveFindBD(cf)
2114 except errors.BlockDeviceError:
2120 result.append(rbd.GetActualSize())
2124 def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2125 """Export a block device to a remote node.
2127 @type disk: L{objects.Disk}
2128 @param disk: the description of the disk to export
2129 @type dest_node: str
2130 @param dest_node: the destination node to export to
2131 @type dest_path: str
2132 @param dest_path: the destination path on the target node
2133 @type cluster_name: str
2134 @param cluster_name: the cluster name, needed for SSH hostalias
2138 real_disk = _OpenRealBD(disk)
2140 # the block size on the read dd is 1MiB to match our units
2141 expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2142 "dd if=%s bs=1048576 count=%s",
2143 real_disk.dev_path, str(disk.size))
2145 # we set here a smaller block size as, due to ssh buffering, more
2146 # than 64-128k will mostly ignored; we use nocreat to fail if the
2147 # device is not already there or we pass a wrong path; we use
2148 # notrunc to no attempt truncate on an LV device; we use oflag=dsync
2149 # to not buffer too much memory; this means that at best, we flush
2150 # every 64k, which will not be very fast
2151 destcmd = utils.BuildShellCmd("dd of=%s conv=nocreat,notrunc bs=65536"
2152 " oflag=dsync", dest_path)
2154 remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2155 constants.SSH_LOGIN_USER,
2158 # all commands have been checked, so we're safe to combine them
2159 command = "|".join([expcmd, utils.ShellQuoteArgs(remotecmd)])
2161 result = utils.RunCmd(["bash", "-c", command])
2164 _Fail("Disk copy command '%s' returned error: %s"
2165 " output: %s", command, result.fail_reason, result.output)
2168 def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2169 """Write a file to the filesystem.
2171 This allows the master to overwrite(!) a file. It will only perform
2172 the operation if the file belongs to a list of configuration files.
2174 @type file_name: str
2175 @param file_name: the target file name
2177 @param data: the new contents of the file
2179 @param mode: the mode to give the file (can be None)
2181 @param uid: the owner of the file
2183 @param gid: the group of the file
2185 @param atime: the atime to set on the file (can be None)
2187 @param mtime: the mtime to set on the file (can be None)
2191 file_name = vcluster.LocalizeVirtualPath(file_name)
2193 if not os.path.isabs(file_name):
2194 _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2196 if file_name not in _ALLOWED_UPLOAD_FILES:
2197 _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2200 raw_data = _Decompress(data)
2202 if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2203 _Fail("Invalid username/groupname type")
2205 getents = runtime.GetEnts()
2206 uid = getents.LookupUser(uid)
2207 gid = getents.LookupGroup(gid)
2209 utils.SafeWriteFile(file_name, None,
2210 data=raw_data, mode=mode, uid=uid, gid=gid,
2211 atime=atime, mtime=mtime)
2214 def RunOob(oob_program, command, node, timeout):
2215 """Executes oob_program with given command on given node.
2217 @param oob_program: The path to the executable oob_program
2218 @param command: The command to invoke on oob_program
2219 @param node: The node given as an argument to the program
2220 @param timeout: Timeout after which we kill the oob program
2223 @raise RPCFail: If execution fails for some reason
2226 result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2229 _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2230 result.fail_reason, result.output)
2232 return result.stdout
2235 def _OSOndiskAPIVersion(os_dir):
2236 """Compute and return the API version of a given OS.
2238 This function will try to read the API version of the OS residing in
2239 the 'os_dir' directory.
2242 @param os_dir: the directory in which we should look for the OS
2244 @return: tuple (status, data) with status denoting the validity and
2245 data holding either the vaid versions or an error message
2248 api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2251 st = os.stat(api_file)
2252 except EnvironmentError, err:
2253 return False, ("Required file '%s' not found under path %s: %s" %
2254 (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2256 if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2257 return False, ("File '%s' in %s is not a regular file" %
2258 (constants.OS_API_FILE, os_dir))
2261 api_versions = utils.ReadFile(api_file).splitlines()
2262 except EnvironmentError, err:
2263 return False, ("Error while reading the API version file at %s: %s" %
2264 (api_file, utils.ErrnoOrStr(err)))
2267 api_versions = [int(version.strip()) for version in api_versions]
2268 except (TypeError, ValueError), err:
2269 return False, ("API version(s) can't be converted to integer: %s" %
2272 return True, api_versions
2275 def DiagnoseOS(top_dirs=None):
2276 """Compute the validity for all OSes.
2278 @type top_dirs: list
2279 @param top_dirs: the list of directories in which to
2280 search (if not given defaults to
2281 L{pathutils.OS_SEARCH_PATH})
2282 @rtype: list of L{objects.OS}
2283 @return: a list of tuples (name, path, status, diagnose, variants,
2284 parameters, api_version) for all (potential) OSes under all
2285 search paths, where:
2286 - name is the (potential) OS name
2287 - path is the full path to the OS
2288 - status True/False is the validity of the OS
2289 - diagnose is the error message for an invalid OS, otherwise empty
2290 - variants is a list of supported OS variants, if any
2291 - parameters is a list of (name, help) parameters, if any
2292 - api_version is a list of support OS API versions
2295 if top_dirs is None:
2296 top_dirs = pathutils.OS_SEARCH_PATH
2299 for dir_name in top_dirs:
2300 if os.path.isdir(dir_name):
2302 f_names = utils.ListVisibleFiles(dir_name)
2303 except EnvironmentError, err:
2304 logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2306 for name in f_names:
2307 os_path = utils.PathJoin(dir_name, name)
2308 status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2311 variants = os_inst.supported_variants
2312 parameters = os_inst.supported_parameters
2313 api_versions = os_inst.api_versions
2316 variants = parameters = api_versions = []
2317 result.append((name, os_path, status, diagnose, variants,
2318 parameters, api_versions))
2323 def _TryOSFromDisk(name, base_dir=None):
2324 """Create an OS instance from disk.
2326 This function will return an OS instance if the given name is a
2329 @type base_dir: string
2330 @keyword base_dir: Base directory containing OS installations.
2331 Defaults to a search in all the OS_SEARCH_PATH dirs.
2333 @return: success and either the OS instance if we find a valid one,
2337 if base_dir is None:
2338 os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2340 os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2343 return False, "Directory for OS %s not found in search path" % name
2345 status, api_versions = _OSOndiskAPIVersion(os_dir)
2348 return status, api_versions
2350 if not constants.OS_API_VERSIONS.intersection(api_versions):
2351 return False, ("API version mismatch for path '%s': found %s, want %s." %
2352 (os_dir, api_versions, constants.OS_API_VERSIONS))
2354 # OS Files dictionary, we will populate it with the absolute path
2355 # names; if the value is True, then it is a required file, otherwise
2357 os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2359 if max(api_versions) >= constants.OS_API_V15:
2360 os_files[constants.OS_VARIANTS_FILE] = False
2362 if max(api_versions) >= constants.OS_API_V20:
2363 os_files[constants.OS_PARAMETERS_FILE] = True
2365 del os_files[constants.OS_SCRIPT_VERIFY]
2367 for (filename, required) in os_files.items():
2368 os_files[filename] = utils.PathJoin(os_dir, filename)
2371 st = os.stat(os_files[filename])
2372 except EnvironmentError, err:
2373 if err.errno == errno.ENOENT and not required:
2374 del os_files[filename]
2376 return False, ("File '%s' under path '%s' is missing (%s)" %
2377 (filename, os_dir, utils.ErrnoOrStr(err)))
2379 if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2380 return False, ("File '%s' under path '%s' is not a regular file" %
2383 if filename in constants.OS_SCRIPTS:
2384 if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2385 return False, ("File '%s' under path '%s' is not executable" %
2389 if constants.OS_VARIANTS_FILE in os_files:
2390 variants_file = os_files[constants.OS_VARIANTS_FILE]
2393 utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2394 except EnvironmentError, err:
2395 # we accept missing files, but not other errors
2396 if err.errno != errno.ENOENT:
2397 return False, ("Error while reading the OS variants file at %s: %s" %
2398 (variants_file, utils.ErrnoOrStr(err)))
2401 if constants.OS_PARAMETERS_FILE in os_files:
2402 parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2404 parameters = utils.ReadFile(parameters_file).splitlines()
2405 except EnvironmentError, err:
2406 return False, ("Error while reading the OS parameters file at %s: %s" %
2407 (parameters_file, utils.ErrnoOrStr(err)))
2408 parameters = [v.split(None, 1) for v in parameters]
2410 os_obj = objects.OS(name=name, path=os_dir,
2411 create_script=os_files[constants.OS_SCRIPT_CREATE],
2412 export_script=os_files[constants.OS_SCRIPT_EXPORT],
2413 import_script=os_files[constants.OS_SCRIPT_IMPORT],
2414 rename_script=os_files[constants.OS_SCRIPT_RENAME],
2415 verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2417 supported_variants=variants,
2418 supported_parameters=parameters,
2419 api_versions=api_versions)
2423 def OSFromDisk(name, base_dir=None):
2424 """Create an OS instance from disk.
2426 This function will return an OS instance if the given name is a
2427 valid OS name. Otherwise, it will raise an appropriate
2428 L{RPCFail} exception, detailing why this is not a valid OS.
2430 This is just a wrapper over L{_TryOSFromDisk}, which doesn't raise
2431 an exception but returns true/false status data.
2433 @type base_dir: string
2434 @keyword base_dir: Base directory containing OS installations.
2435 Defaults to a search in all the OS_SEARCH_PATH dirs.
2436 @rtype: L{objects.OS}
2437 @return: the OS instance if we find a valid one
2438 @raise RPCFail: if we don't find a valid OS
2441 name_only = objects.OS.GetName(name)
2442 status, payload = _TryOSFromDisk(name_only, base_dir)
2450 def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2451 """Calculate the basic environment for an os script.
2454 @param os_name: full operating system name (including variant)
2455 @type inst_os: L{objects.OS}
2456 @param inst_os: operating system for which the environment is being built
2457 @type os_params: dict
2458 @param os_params: the OS parameters
2459 @type debug: integer
2460 @param debug: debug level (0 or 1, for OS Api 10)
2462 @return: dict of environment variables
2463 @raise errors.BlockDeviceError: if the block device
2469 max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2470 result["OS_API_VERSION"] = "%d" % api_version
2471 result["OS_NAME"] = inst_os.name
2472 result["DEBUG_LEVEL"] = "%d" % debug
2475 if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2476 variant = objects.OS.GetVariant(os_name)
2478 variant = inst_os.supported_variants[0]
2481 result["OS_VARIANT"] = variant
2484 for pname, pvalue in os_params.items():
2485 result["OSP_%s" % pname.upper()] = pvalue
2487 # Set a default path otherwise programs called by OS scripts (or
2488 # even hooks called from OS scripts) might break, and we don't want
2489 # to have each script require setting a PATH variable
2490 result["PATH"] = constants.HOOKS_PATH
2495 def OSEnvironment(instance, inst_os, debug=0):
2496 """Calculate the environment for an os script.
2498 @type instance: L{objects.Instance}
2499 @param instance: target instance for the os script run
2500 @type inst_os: L{objects.OS}
2501 @param inst_os: operating system for which the environment is being built
2502 @type debug: integer
2503 @param debug: debug level (0 or 1, for OS Api 10)
2505 @return: dict of environment variables
2506 @raise errors.BlockDeviceError: if the block device
2510 result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2512 for attr in ["name", "os", "uuid", "ctime", "mtime", "primary_node"]:
2513 result["INSTANCE_%s" % attr.upper()] = str(getattr(instance, attr))
2515 result["HYPERVISOR"] = instance.hypervisor
2516 result["DISK_COUNT"] = "%d" % len(instance.disks)
2517 result["NIC_COUNT"] = "%d" % len(instance.nics)
2518 result["INSTANCE_SECONDARY_NODES"] = \
2519 ("%s" % " ".join(instance.secondary_nodes))
2522 for idx, disk in enumerate(instance.disks):
2523 real_disk = _OpenRealBD(disk)
2524 result["DISK_%d_PATH" % idx] = real_disk.dev_path
2525 result["DISK_%d_ACCESS" % idx] = disk.mode
2526 result["DISK_%d_UUID" % idx] = disk.uuid
2528 result["DISK_%d_NAME" % idx] = disk.name
2529 if constants.HV_DISK_TYPE in instance.hvparams:
2530 result["DISK_%d_FRONTEND_TYPE" % idx] = \
2531 instance.hvparams[constants.HV_DISK_TYPE]
2532 if disk.dev_type in constants.LDS_BLOCK:
2533 result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2534 elif disk.dev_type == constants.LD_FILE:
2535 result["DISK_%d_BACKEND_TYPE" % idx] = \
2536 "file:%s" % disk.physical_id[0]
2539 for idx, nic in enumerate(instance.nics):
2540 result["NIC_%d_MAC" % idx] = nic.mac
2541 result["NIC_%d_UUID" % idx] = nic.uuid
2543 result["NIC_%d_NAME" % idx] = nic.name
2545 result["NIC_%d_IP" % idx] = nic.ip
2546 result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2547 if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2548 result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2549 if nic.nicparams[constants.NIC_LINK]:
2550 result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2552 nobj = objects.Network.FromDict(nic.netinfo)
2553 result.update(nobj.HooksDict("NIC_%d_" % idx))
2554 if constants.HV_NIC_TYPE in instance.hvparams:
2555 result["NIC_%d_FRONTEND_TYPE" % idx] = \
2556 instance.hvparams[constants.HV_NIC_TYPE]
2559 for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2560 for key, value in source.items():
2561 result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2566 def DiagnoseExtStorage(top_dirs=None):
2567 """Compute the validity for all ExtStorage Providers.
2569 @type top_dirs: list
2570 @param top_dirs: the list of directories in which to
2571 search (if not given defaults to
2572 L{pathutils.ES_SEARCH_PATH})
2573 @rtype: list of L{objects.ExtStorage}
2574 @return: a list of tuples (name, path, status, diagnose, parameters)
2575 for all (potential) ExtStorage Providers under all
2576 search paths, where:
2577 - name is the (potential) ExtStorage Provider
2578 - path is the full path to the ExtStorage Provider
2579 - status True/False is the validity of the ExtStorage Provider
2580 - diagnose is the error message for an invalid ExtStorage Provider,
2582 - parameters is a list of (name, help) parameters, if any
2585 if top_dirs is None:
2586 top_dirs = pathutils.ES_SEARCH_PATH
2589 for dir_name in top_dirs:
2590 if os.path.isdir(dir_name):
2592 f_names = utils.ListVisibleFiles(dir_name)
2593 except EnvironmentError, err:
2594 logging.exception("Can't list the ExtStorage directory %s: %s",
2597 for name in f_names:
2598 es_path = utils.PathJoin(dir_name, name)
2599 status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2602 parameters = es_inst.supported_parameters
2606 result.append((name, es_path, status, diagnose, parameters))
2611 def BlockdevGrow(disk, amount, dryrun, backingstore):
2612 """Grow a stack of block devices.
2614 This function is called recursively, with the childrens being the
2615 first ones to resize.
2617 @type disk: L{objects.Disk}
2618 @param disk: the disk to be grown
2619 @type amount: integer
2620 @param amount: the amount (in mebibytes) to grow with
2621 @type dryrun: boolean
2622 @param dryrun: whether to execute the operation in simulation mode
2623 only, without actually increasing the size
2624 @param backingstore: whether to execute the operation on backing storage
2625 only, or on "logical" storage only; e.g. DRBD is logical storage,
2626 whereas LVM, file, RBD are backing storage
2627 @rtype: (status, result)
2628 @return: a tuple with the status of the operation (True/False), and
2629 the errors message if status is False
2632 r_dev = _RecursiveFindBD(disk)
2634 _Fail("Cannot find block device %s", disk)
2637 r_dev.Grow(amount, dryrun, backingstore)
2638 except errors.BlockDeviceError, err:
2639 _Fail("Failed to grow block device: %s", err, exc=True)
2642 def BlockdevSnapshot(disk):
2643 """Create a snapshot copy of a block device.
2645 This function is called recursively, and the snapshot is actually created
2646 just for the leaf lvm backend device.
2648 @type disk: L{objects.Disk}
2649 @param disk: the disk to be snapshotted
2651 @return: snapshot disk ID as (vg, lv)
2654 if disk.dev_type == constants.LD_DRBD8:
2655 if not disk.children:
2656 _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2658 return BlockdevSnapshot(disk.children[0])
2659 elif disk.dev_type == constants.LD_LV:
2660 r_dev = _RecursiveFindBD(disk)
2661 if r_dev is not None:
2662 # FIXME: choose a saner value for the snapshot size
2663 # let's stay on the safe side and ask for the full size, for now
2664 return r_dev.Snapshot(disk.size)
2666 _Fail("Cannot find block device %s", disk)
2668 _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2669 disk.unique_id, disk.dev_type)
2672 def BlockdevSetInfo(disk, info):
2673 """Sets 'metadata' information on block devices.
2675 This function sets 'info' metadata on block devices. Initial
2676 information is set at device creation; this function should be used
2677 for example after renames.
2679 @type disk: L{objects.Disk}
2680 @param disk: the disk to be grown
2682 @param info: new 'info' metadata
2683 @rtype: (status, result)
2684 @return: a tuple with the status of the operation (True/False), and
2685 the errors message if status is False
2688 r_dev = _RecursiveFindBD(disk)
2690 _Fail("Cannot find block device %s", disk)
2694 except errors.BlockDeviceError, err:
2695 _Fail("Failed to set information on block device: %s", err, exc=True)
2698 def FinalizeExport(instance, snap_disks):
2699 """Write out the export configuration information.
2701 @type instance: L{objects.Instance}
2702 @param instance: the instance which we export, used for
2703 saving configuration
2704 @type snap_disks: list of L{objects.Disk}
2705 @param snap_disks: list of snapshot block devices, which
2706 will be used to get the actual name of the dump file
2711 destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
2712 finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
2714 config = objects.SerializableConfigParser()
2716 config.add_section(constants.INISECT_EXP)
2717 config.set(constants.INISECT_EXP, "version", "0")
2718 config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2719 config.set(constants.INISECT_EXP, "source", instance.primary_node)
2720 config.set(constants.INISECT_EXP, "os", instance.os)
2721 config.set(constants.INISECT_EXP, "compression", "none")
2723 config.add_section(constants.INISECT_INS)
2724 config.set(constants.INISECT_INS, "name", instance.name)
2725 config.set(constants.INISECT_INS, "maxmem", "%d" %
2726 instance.beparams[constants.BE_MAXMEM])
2727 config.set(constants.INISECT_INS, "minmem", "%d" %
2728 instance.beparams[constants.BE_MINMEM])
2729 # "memory" is deprecated, but useful for exporting to old ganeti versions
2730 config.set(constants.INISECT_INS, "memory", "%d" %
2731 instance.beparams[constants.BE_MAXMEM])
2732 config.set(constants.INISECT_INS, "vcpus", "%d" %
2733 instance.beparams[constants.BE_VCPUS])
2734 config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2735 config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2736 config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2739 for nic_count, nic in enumerate(instance.nics):
2741 config.set(constants.INISECT_INS, "nic%d_mac" %
2742 nic_count, "%s" % nic.mac)
2743 config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2744 config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
2746 for param in constants.NICS_PARAMETER_TYPES:
2747 config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2748 "%s" % nic.nicparams.get(param, None))
2749 # TODO: redundant: on load can read nics until it doesn't exist
2750 config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2753 for disk_count, disk in enumerate(snap_disks):
2756 config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2757 ("%s" % disk.iv_name))
2758 config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2759 ("%s" % disk.physical_id[1]))
2760 config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2763 config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2765 # New-style hypervisor/backend parameters
2767 config.add_section(constants.INISECT_HYP)
2768 for name, value in instance.hvparams.items():
2769 if name not in constants.HVC_GLOBALS:
2770 config.set(constants.INISECT_HYP, name, str(value))
2772 config.add_section(constants.INISECT_BEP)
2773 for name, value in instance.beparams.items():
2774 config.set(constants.INISECT_BEP, name, str(value))
2776 config.add_section(constants.INISECT_OSP)
2777 for name, value in instance.osparams.items():
2778 config.set(constants.INISECT_OSP, name, str(value))
2780 utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2781 data=config.Dumps())
2782 shutil.rmtree(finaldestdir, ignore_errors=True)
2783 shutil.move(destdir, finaldestdir)
2786 def ExportInfo(dest):
2787 """Get export configuration information.
2790 @param dest: directory containing the export
2792 @rtype: L{objects.SerializableConfigParser}
2793 @return: a serializable config file containing the
2797 cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2799 config = objects.SerializableConfigParser()
2802 if (not config.has_section(constants.INISECT_EXP) or
2803 not config.has_section(constants.INISECT_INS)):
2804 _Fail("Export info file doesn't have the required fields")
2806 return config.Dumps()
2810 """Return a list of exports currently available on this machine.
2813 @return: list of the exports
2816 if os.path.isdir(pathutils.EXPORT_DIR):
2817 return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
2819 _Fail("No exports directory")
2822 def RemoveExport(export):
2823 """Remove an existing export from the node.
2826 @param export: the name of the export to remove
2830 target = utils.PathJoin(pathutils.EXPORT_DIR, export)
2833 shutil.rmtree(target)
2834 except EnvironmentError, err:
2835 _Fail("Error while removing the export: %s", err, exc=True)
2838 def BlockdevRename(devlist):
2839 """Rename a list of block devices.
2841 @type devlist: list of tuples
2842 @param devlist: list of tuples of the form (disk,
2843 new_logical_id, new_physical_id); disk is an
2844 L{objects.Disk} object describing the current disk,
2845 and new logical_id/physical_id is the name we
2848 @return: True if all renames succeeded, False otherwise
2853 for disk, unique_id in devlist:
2854 dev = _RecursiveFindBD(disk)
2856 msgs.append("Can't find device %s in rename" % str(disk))
2860 old_rpath = dev.dev_path
2861 dev.Rename(unique_id)
2862 new_rpath = dev.dev_path
2863 if old_rpath != new_rpath:
2864 DevCacheManager.RemoveCache(old_rpath)
2865 # FIXME: we should add the new cache information here, like:
2866 # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2867 # but we don't have the owner here - maybe parse from existing
2868 # cache? for now, we only lose lvm data when we rename, which
2869 # is less critical than DRBD or MD
2870 except errors.BlockDeviceError, err:
2871 msgs.append("Can't rename device '%s' to '%s': %s" %
2872 (dev, unique_id, err))
2873 logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2876 _Fail("; ".join(msgs))
2879 def _TransformFileStorageDir(fs_dir):
2880 """Checks whether given file_storage_dir is valid.
2882 Checks wheter the given fs_dir is within the cluster-wide default
2883 file_storage_dir or the shared_file_storage_dir, which are stored in
2884 SimpleStore. Only paths under those directories are allowed.
2887 @param fs_dir: the path to check
2889 @return: the normalized path if valid, None otherwise
2892 if not (constants.ENABLE_FILE_STORAGE or
2893 constants.ENABLE_SHARED_FILE_STORAGE):
2894 _Fail("File storage disabled at configure time")
2896 bdev.CheckFileStoragePath(fs_dir)
2898 return os.path.normpath(fs_dir)
2901 def CreateFileStorageDir(file_storage_dir):
2902 """Create file storage directory.
2904 @type file_storage_dir: str
2905 @param file_storage_dir: directory to create
2908 @return: tuple with first element a boolean indicating wheter dir
2909 creation was successful or not
2912 file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2913 if os.path.exists(file_storage_dir):
2914 if not os.path.isdir(file_storage_dir):
2915 _Fail("Specified storage dir '%s' is not a directory",
2919 os.makedirs(file_storage_dir, 0750)
2920 except OSError, err:
2921 _Fail("Cannot create file storage directory '%s': %s",
2922 file_storage_dir, err, exc=True)
2925 def RemoveFileStorageDir(file_storage_dir):
2926 """Remove file storage directory.
2928 Remove it only if it's empty. If not log an error and return.
2930 @type file_storage_dir: str
2931 @param file_storage_dir: the directory we should cleanup
2932 @rtype: tuple (success,)
2933 @return: tuple of one element, C{success}, denoting
2934 whether the operation was successful
2937 file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2938 if os.path.exists(file_storage_dir):
2939 if not os.path.isdir(file_storage_dir):
2940 _Fail("Specified Storage directory '%s' is not a directory",
2942 # deletes dir only if empty, otherwise we want to fail the rpc call
2944 os.rmdir(file_storage_dir)
2945 except OSError, err:
2946 _Fail("Cannot remove file storage directory '%s': %s",
2947 file_storage_dir, err)
2950 def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2951 """Rename the file storage directory.
2953 @type old_file_storage_dir: str
2954 @param old_file_storage_dir: the current path
2955 @type new_file_storage_dir: str
2956 @param new_file_storage_dir: the name we should rename to
2957 @rtype: tuple (success,)
2958 @return: tuple of one element, C{success}, denoting
2959 whether the operation was successful
2962 old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2963 new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2964 if not os.path.exists(new_file_storage_dir):
2965 if os.path.isdir(old_file_storage_dir):
2967 os.rename(old_file_storage_dir, new_file_storage_dir)
2968 except OSError, err:
2969 _Fail("Cannot rename '%s' to '%s': %s",
2970 old_file_storage_dir, new_file_storage_dir, err)
2972 _Fail("Specified storage dir '%s' is not a directory",
2973 old_file_storage_dir)
2975 if os.path.exists(old_file_storage_dir):
2976 _Fail("Cannot rename '%s' to '%s': both locations exist",
2977 old_file_storage_dir, new_file_storage_dir)
2980 def _EnsureJobQueueFile(file_name):
2981 """Checks whether the given filename is in the queue directory.
2983 @type file_name: str
2984 @param file_name: the file name we should check
2986 @raises RPCFail: if the file is not valid
2989 if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
2990 _Fail("Passed job queue file '%s' does not belong to"
2991 " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
2994 def JobQueueUpdate(file_name, content):
2995 """Updates a file in the queue directory.
2997 This is just a wrapper over L{utils.io.WriteFile}, with proper
3000 @type file_name: str
3001 @param file_name: the job file name
3003 @param content: the new job contents
3005 @return: the success of the operation
3008 file_name = vcluster.LocalizeVirtualPath(file_name)
3010 _EnsureJobQueueFile(file_name)
3011 getents = runtime.GetEnts()
3013 # Write and replace the file atomically
3014 utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3015 gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3018 def JobQueueRename(old, new):
3019 """Renames a job queue file.
3021 This is just a wrapper over os.rename with proper checking.
3024 @param old: the old (actual) file name
3026 @param new: the desired file name
3028 @return: the success of the operation and payload
3031 old = vcluster.LocalizeVirtualPath(old)
3032 new = vcluster.LocalizeVirtualPath(new)
3034 _EnsureJobQueueFile(old)
3035 _EnsureJobQueueFile(new)
3037 getents = runtime.GetEnts()
3039 utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3040 dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3043 def BlockdevClose(instance_name, disks):
3044 """Closes the given block devices.
3046 This means they will be switched to secondary mode (in case of
3049 @param instance_name: if the argument is not empty, the symlinks
3050 of this instance will be removed
3051 @type disks: list of L{objects.Disk}
3052 @param disks: the list of disks to be closed
3053 @rtype: tuple (success, message)
3054 @return: a tuple of success and message, where success
3055 indicates the succes of the operation, and message
3056 which will contain the error details in case we
3062 rd = _RecursiveFindBD(cf)
3064 _Fail("Can't find device %s", cf)
3071 except errors.BlockDeviceError, err:
3072 msg.append(str(err))
3074 _Fail("Can't make devices secondary: %s", ",".join(msg))
3077 _RemoveBlockDevLinks(instance_name, disks)
3080 def ValidateHVParams(hvname, hvparams):
3081 """Validates the given hypervisor parameters.
3083 @type hvname: string
3084 @param hvname: the hypervisor name
3085 @type hvparams: dict
3086 @param hvparams: the hypervisor parameters to be validated
3091 hv_type = hypervisor.GetHypervisor(hvname)
3092 hv_type.ValidateParameters(hvparams)
3093 except errors.HypervisorError, err:
3094 _Fail(str(err), log=False)
3097 def _CheckOSPList(os_obj, parameters):
3098 """Check whether a list of parameters is supported by the OS.
3100 @type os_obj: L{objects.OS}
3101 @param os_obj: OS object to check
3102 @type parameters: list
3103 @param parameters: the list of parameters to check
3106 supported = [v[0] for v in os_obj.supported_parameters]
3107 delta = frozenset(parameters).difference(supported)
3109 _Fail("The following parameters are not supported"
3110 " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3113 def ValidateOS(required, osname, checks, osparams):
3114 """Validate the given OS' parameters.
3116 @type required: boolean
3117 @param required: whether absence of the OS should translate into
3119 @type osname: string
3120 @param osname: the OS to be validated
3122 @param checks: list of the checks to run (currently only 'parameters')
3123 @type osparams: dict
3124 @param osparams: dictionary with OS parameters
3126 @return: True if the validation passed, or False if the OS was not
3127 found and L{required} was false
3130 if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3131 _Fail("Unknown checks required for OS %s: %s", osname,
3132 set(checks).difference(constants.OS_VALIDATE_CALLS))
3134 name_only = objects.OS.GetName(osname)
3135 status, tbv = _TryOSFromDisk(name_only, None)
3143 if max(tbv.api_versions) < constants.OS_API_V20:
3146 if constants.OS_VALIDATE_PARAMETERS in checks:
3147 _CheckOSPList(tbv, osparams.keys())
3149 validate_env = OSCoreEnv(osname, tbv, osparams)
3150 result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3151 cwd=tbv.path, reset_env=True)
3153 logging.error("os validate command '%s' returned error: %s output: %s",
3154 result.cmd, result.fail_reason, result.output)
3155 _Fail("OS validation script failed (%s), output: %s",
3156 result.fail_reason, result.output, log=False)
3162 """Demotes the current node from master candidate role.
3165 # try to ensure we're not the master by mistake
3166 master, myself = ssconf.GetMasterAndMyself()
3167 if master == myself:
3168 _Fail("ssconf status shows I'm the master node, will not demote")
3170 result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3171 if not result.failed:
3172 _Fail("The master daemon is running, will not demote")
3175 if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3176 utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3177 except EnvironmentError, err:
3178 if err.errno != errno.ENOENT:
3179 _Fail("Error while backing up cluster file: %s", err, exc=True)
3181 utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3184 def _GetX509Filenames(cryptodir, name):
3185 """Returns the full paths for the private key and certificate.
3188 return (utils.PathJoin(cryptodir, name),
3189 utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3190 utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3193 def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3194 """Creates a new X509 certificate for SSL/TLS.
3197 @param validity: Validity in seconds
3198 @rtype: tuple; (string, string)
3199 @return: Certificate name and public part
3202 (key_pem, cert_pem) = \
3203 utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3204 min(validity, _MAX_SSL_CERT_VALIDITY))
3206 cert_dir = tempfile.mkdtemp(dir=cryptodir,
3207 prefix="x509-%s-" % utils.TimestampForFilename())
3209 name = os.path.basename(cert_dir)
3210 assert len(name) > 5
3212 (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3214 utils.WriteFile(key_file, mode=0400, data=key_pem)
3215 utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3217 # Never return private key as it shouldn't leave the node
3218 return (name, cert_pem)
3220 shutil.rmtree(cert_dir, ignore_errors=True)
3224 def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3225 """Removes a X509 certificate.
3228 @param name: Certificate name
3231 (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3233 utils.RemoveFile(key_file)
3234 utils.RemoveFile(cert_file)
3238 except EnvironmentError, err:
3239 _Fail("Cannot remove certificate directory '%s': %s",
3243 def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3244 """Returns the command for the requested input/output.
3246 @type instance: L{objects.Instance}
3247 @param instance: The instance object
3248 @param mode: Import/export mode
3249 @param ieio: Input/output type
3250 @param ieargs: Input/output arguments
3253 assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3260 if ieio == constants.IEIO_FILE:
3261 (filename, ) = ieargs
3263 if not utils.IsNormAbsPath(filename):
3264 _Fail("Path '%s' is not normalized or absolute", filename)
3266 real_filename = os.path.realpath(filename)
3267 directory = os.path.dirname(real_filename)
3269 if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3270 _Fail("File '%s' is not under exports directory '%s': %s",
3271 filename, pathutils.EXPORT_DIR, real_filename)
3274 utils.Makedirs(directory, mode=0750)
3276 quoted_filename = utils.ShellQuote(filename)
3278 if mode == constants.IEM_IMPORT:
3279 suffix = "> %s" % quoted_filename
3280 elif mode == constants.IEM_EXPORT:
3281 suffix = "< %s" % quoted_filename
3283 # Retrieve file size
3285 st = os.stat(filename)
3286 except EnvironmentError, err:
3287 logging.error("Can't stat(2) %s: %s", filename, err)
3289 exp_size = utils.BytesToMebibyte(st.st_size)
3291 elif ieio == constants.IEIO_RAW_DISK:
3294 real_disk = _OpenRealBD(disk)
3296 if mode == constants.IEM_IMPORT:
3297 # we set here a smaller block size as, due to transport buffering, more
3298 # than 64-128k will mostly ignored; we use nocreat to fail if the device
3299 # is not already there or we pass a wrong path; we use notrunc to no
3300 # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3301 # much memory; this means that at best, we flush every 64k, which will
3303 suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3304 " bs=%s oflag=dsync"),
3308 elif mode == constants.IEM_EXPORT:
3309 # the block size on the read dd is 1MiB to match our units
3310 prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3312 str(1024 * 1024), # 1 MB
3314 exp_size = disk.size
3316 elif ieio == constants.IEIO_SCRIPT:
3317 (disk, disk_index, ) = ieargs
3319 assert isinstance(disk_index, (int, long))
3321 real_disk = _OpenRealBD(disk)
3323 inst_os = OSFromDisk(instance.os)
3324 env = OSEnvironment(instance, inst_os)
3326 if mode == constants.IEM_IMPORT:
3327 env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3328 env["IMPORT_INDEX"] = str(disk_index)
3329 script = inst_os.import_script
3331 elif mode == constants.IEM_EXPORT:
3332 env["EXPORT_DEVICE"] = real_disk.dev_path
3333 env["EXPORT_INDEX"] = str(disk_index)
3334 script = inst_os.export_script
3336 # TODO: Pass special environment only to script
3337 script_cmd = utils.BuildShellCmd("( cd %s && %s; )", inst_os.path, script)
3339 if mode == constants.IEM_IMPORT:
3340 suffix = "| %s" % script_cmd
3342 elif mode == constants.IEM_EXPORT:
3343 prefix = "%s |" % script_cmd
3345 # Let script predict size
3346 exp_size = constants.IE_CUSTOM_SIZE
3349 _Fail("Invalid %s I/O mode %r", mode, ieio)
3351 return (env, prefix, suffix, exp_size)
3354 def _CreateImportExportStatusDir(prefix):
3355 """Creates status directory for import/export.
3358 return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3360 (prefix, utils.TimestampForFilename())))
3363 def StartImportExportDaemon(mode, opts, host, port, instance, component,
3365 """Starts an import or export daemon.
3367 @param mode: Import/output mode
3368 @type opts: L{objects.ImportExportOptions}
3369 @param opts: Daemon options
3371 @param host: Remote host for export (None for import)
3373 @param port: Remote port for export (None for import)
3374 @type instance: L{objects.Instance}
3375 @param instance: Instance object
3376 @type component: string
3377 @param component: which part of the instance is transferred now,
3379 @param ieio: Input/output type
3380 @param ieioargs: Input/output arguments
3383 if mode == constants.IEM_IMPORT:
3386 if not (host is None and port is None):
3387 _Fail("Can not specify host or port on import")
3389 elif mode == constants.IEM_EXPORT:
3392 if host is None or port is None:
3393 _Fail("Host and port must be specified for an export")
3396 _Fail("Invalid mode %r", mode)
3398 if (opts.key_name is None) ^ (opts.ca_pem is None):
3399 _Fail("Cluster certificate can only be used for both key and CA")
3401 (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3402 _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3404 if opts.key_name is None:
3406 key_path = pathutils.NODED_CERT_FILE
3407 cert_path = pathutils.NODED_CERT_FILE
3408 assert opts.ca_pem is None
3410 (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3412 assert opts.ca_pem is not None
3414 for i in [key_path, cert_path]:
3415 if not os.path.exists(i):
3416 _Fail("File '%s' does not exist" % i)
3418 status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3420 status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3421 pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3422 ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3424 if opts.ca_pem is None:
3426 ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3431 utils.WriteFile(ca_file, data=ca, mode=0400)
3434 pathutils.IMPORT_EXPORT_DAEMON,
3436 "--key=%s" % key_path,
3437 "--cert=%s" % cert_path,
3438 "--ca=%s" % ca_file,
3442 cmd.append("--host=%s" % host)
3445 cmd.append("--port=%s" % port)
3448 cmd.append("--ipv6")
3450 cmd.append("--ipv4")
3453 cmd.append("--compress=%s" % opts.compress)
3456 cmd.append("--magic=%s" % opts.magic)
3458 if exp_size is not None:
3459 cmd.append("--expected-size=%s" % exp_size)
3462 cmd.append("--cmd-prefix=%s" % cmd_prefix)
3465 cmd.append("--cmd-suffix=%s" % cmd_suffix)
3467 if mode == constants.IEM_EXPORT:
3468 # Retry connection a few times when connecting to remote peer
3469 cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3470 cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3471 elif opts.connect_timeout is not None:
3472 assert mode == constants.IEM_IMPORT
3473 # Overall timeout for establishing connection while listening
3474 cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3476 logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3478 # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3479 # support for receiving a file descriptor for output
3480 utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3483 # The import/export name is simply the status directory name
3484 return os.path.basename(status_dir)
3487 shutil.rmtree(status_dir, ignore_errors=True)
3491 def GetImportExportStatus(names):
3492 """Returns import/export daemon status.
3494 @type names: sequence
3495 @param names: List of names
3496 @rtype: List of dicts
3497 @return: Returns a list of the state of each named import/export or None if a
3498 status couldn't be read
3504 status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3508 data = utils.ReadFile(status_file)
3509 except EnvironmentError, err:
3510 if err.errno != errno.ENOENT:
3518 result.append(serializer.LoadJson(data))
3523 def AbortImportExport(name):
3524 """Sends SIGTERM to a running import/export daemon.
3527 logging.info("Abort import/export %s", name)
3529 status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3530 pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3533 logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3535 utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3538 def CleanupImportExport(name):
3539 """Cleanup after an import or export.
3541 If the import/export daemon is still running it's killed. Afterwards the
3542 whole status directory is removed.
3545 logging.info("Finalizing import/export %s", name)
3547 status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3549 pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3552 logging.info("Import/export %s is still running with PID %s",
3554 utils.KillProcess(pid, waitpid=False)
3556 shutil.rmtree(status_dir, ignore_errors=True)
3559 def _FindDisks(nodes_ip, disks):
3560 """Sets the physical ID on disks and returns the block devices.
3563 # set the correct physical ID
3564 my_name = netutils.Hostname.GetSysName()
3566 cf.SetPhysicalID(my_name, nodes_ip)
3571 rd = _RecursiveFindBD(cf)
3573 _Fail("Can't find device %s", cf)
3578 def DrbdDisconnectNet(nodes_ip, disks):
3579 """Disconnects the network on a list of drbd devices.
3582 bdevs = _FindDisks(nodes_ip, disks)
3588 except errors.BlockDeviceError, err:
3589 _Fail("Can't change network configuration to standalone mode: %s",
3593 def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3594 """Attaches the network on a list of drbd devices.
3597 bdevs = _FindDisks(nodes_ip, disks)
3600 for idx, rd in enumerate(bdevs):
3602 _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3603 except EnvironmentError, err:
3604 _Fail("Can't create symlink: %s", err)
3605 # reconnect disks, switch to new master configuration and if
3606 # needed primary mode
3609 rd.AttachNet(multimaster)
3610 except errors.BlockDeviceError, err:
3611 _Fail("Can't change network configuration: %s", err)
3613 # wait until the disks are connected; we need to retry the re-attach
3614 # if the device becomes standalone, as this might happen if the one
3615 # node disconnects and reconnects in a different mode before the
3616 # other node reconnects; in this case, one or both of the nodes will
3617 # decide it has wrong configuration and switch to standalone
3620 all_connected = True
3623 stats = rd.GetProcStatus()
3625 all_connected = (all_connected and
3626 (stats.is_connected or stats.is_in_resync))
3628 if stats.is_standalone:
3629 # peer had different config info and this node became
3630 # standalone, even though this should not happen with the
3631 # new staged way of changing disk configs
3633 rd.AttachNet(multimaster)
3634 except errors.BlockDeviceError, err:
3635 _Fail("Can't change network configuration: %s", err)
3637 if not all_connected:
3638 raise utils.RetryAgain()
3641 # Start with a delay of 100 miliseconds and go up to 5 seconds
3642 utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3643 except utils.RetryTimeout:
3644 _Fail("Timeout in disk reconnecting")
3647 # change to primary mode
3651 except errors.BlockDeviceError, err:
3652 _Fail("Can't change to primary mode: %s", err)
3655 def DrbdWaitSync(nodes_ip, disks):
3656 """Wait until DRBDs have synchronized.
3660 stats = rd.GetProcStatus()
3661 if not (stats.is_connected or stats.is_in_resync):
3662 raise utils.RetryAgain()
3665 bdevs = _FindDisks(nodes_ip, disks)
3671 # poll each second for 15 seconds
3672 stats = utils.Retry(_helper, 1, 15, args=[rd])
3673 except utils.RetryTimeout:
3674 stats = rd.GetProcStatus()
3676 if not (stats.is_connected or stats.is_in_resync):
3677 _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3678 alldone = alldone and (not stats.is_in_resync)
3679 if stats.sync_percent is not None:
3680 min_resync = min(min_resync, stats.sync_percent)
3682 return (alldone, min_resync)
3685 def GetDrbdUsermodeHelper():
3686 """Returns DRBD usermode helper currently configured.
3690 return bdev.BaseDRBD.GetUsermodeHelper()
3691 except errors.BlockDeviceError, err:
3695 def PowercycleNode(hypervisor_type):
3696 """Hard-powercycle the node.
3698 Because we need to return first, and schedule the powercycle in the
3699 background, we won't be able to report failures nicely.
3702 hyper = hypervisor.GetHypervisor(hypervisor_type)
3706 # if we can't fork, we'll pretend that we're in the child process
3709 return "Reboot scheduled in 5 seconds"
3710 # ensure the child is running on ram
3713 except Exception: # pylint: disable=W0703
3716 hyper.PowercycleNode()
3719 def _VerifyRestrictedCmdName(cmd):
3720 """Verifies a restricted command name.
3723 @param cmd: Command name
3724 @rtype: tuple; (boolean, string or None)
3725 @return: The tuple's first element is the status; if C{False}, the second
3726 element is an error message string, otherwise it's C{None}
3730 return (False, "Missing command name")
3732 if os.path.basename(cmd) != cmd:
3733 return (False, "Invalid command name")
3735 if not constants.EXT_PLUGIN_MASK.match(cmd):
3736 return (False, "Command name contains forbidden characters")
3741 def _CommonRestrictedCmdCheck(path, owner):
3742 """Common checks for restricted command file system directories and files.
3745 @param path: Path to check
3746 @param owner: C{None} or tuple containing UID and GID
3747 @rtype: tuple; (boolean, string or C{os.stat} result)
3748 @return: The tuple's first element is the status; if C{False}, the second
3749 element is an error message string, otherwise it's the result of C{os.stat}
3753 # Default to root as owner
3758 except EnvironmentError, err:
3759 return (False, "Can't stat(2) '%s': %s" % (path, err))
3761 if stat.S_IMODE(st.st_mode) & (~_RCMD_MAX_MODE):
3762 return (False, "Permissions on '%s' are too permissive" % path)
3764 if (st.st_uid, st.st_gid) != owner:
3765 (owner_uid, owner_gid) = owner
3766 return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
3771 def _VerifyRestrictedCmdDirectory(path, _owner=None):
3772 """Verifies restricted command directory.
3775 @param path: Path to check
3776 @rtype: tuple; (boolean, string or None)
3777 @return: The tuple's first element is the status; if C{False}, the second
3778 element is an error message string, otherwise it's C{None}
3781 (status, value) = _CommonRestrictedCmdCheck(path, _owner)
3784 return (False, value)
3786 if not stat.S_ISDIR(value.st_mode):
3787 return (False, "Path '%s' is not a directory" % path)
3792 def _VerifyRestrictedCmd(path, cmd, _owner=None):
3793 """Verifies a whole restricted command and returns its executable filename.
3796 @param path: Directory containing restricted commands
3798 @param cmd: Command name
3799 @rtype: tuple; (boolean, string)
3800 @return: The tuple's first element is the status; if C{False}, the second
3801 element is an error message string, otherwise the second element is the
3802 absolute path to the executable
3805 executable = utils.PathJoin(path, cmd)
3807 (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
3812 if not utils.IsExecutable(executable):
3813 return (False, "access(2) thinks '%s' can't be executed" % executable)
3815 return (True, executable)
3818 def _PrepareRestrictedCmd(path, cmd,
3819 _verify_dir=_VerifyRestrictedCmdDirectory,
3820 _verify_name=_VerifyRestrictedCmdName,
3821 _verify_cmd=_VerifyRestrictedCmd):
3822 """Performs a number of tests on a restricted command.
3825 @param path: Directory containing restricted commands
3827 @param cmd: Command name
3828 @return: Same as L{_VerifyRestrictedCmd}
3831 # Verify the directory first
3832 (status, msg) = _verify_dir(path)
3834 # Check command if everything was alright
3835 (status, msg) = _verify_name(cmd)
3840 # Check actual executable
3841 return _verify_cmd(path, cmd)
3844 def RunRestrictedCmd(cmd,
3845 _lock_timeout=_RCMD_LOCK_TIMEOUT,
3846 _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
3847 _path=pathutils.RESTRICTED_COMMANDS_DIR,
3848 _sleep_fn=time.sleep,
3849 _prepare_fn=_PrepareRestrictedCmd,
3850 _runcmd_fn=utils.RunCmd,
3851 _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
3852 """Executes a restricted command after performing strict tests.
3855 @param cmd: Command name
3857 @return: Command output
3858 @raise RPCFail: In case of an error
3861 logging.info("Preparing to run restricted command '%s'", cmd)
3864 _Fail("Restricted commands disabled at configure time")
3870 lock = utils.FileLock.Open(_lock_file)
3871 lock.Exclusive(blocking=True, timeout=_lock_timeout)
3873 (status, value) = _prepare_fn(_path, cmd)
3876 cmdresult = _runcmd_fn([value], env={}, reset_env=True,
3877 postfork_fn=lambda _: lock.Unlock())
3879 logging.error(value)
3880 except Exception: # pylint: disable=W0703
3881 # Keep original error in log
3882 logging.exception("Caught exception")
3884 if cmdresult is None:
3885 logging.info("Sleeping for %0.1f seconds before returning",
3886 _RCMD_INVALID_DELAY)
3887 _sleep_fn(_RCMD_INVALID_DELAY)
3889 # Do not include original error message in returned error
3890 _Fail("Executing command '%s' failed" % cmd)
3891 elif cmdresult.failed or cmdresult.fail_reason:
3892 _Fail("Restricted command '%s' failed: %s; output: %s",
3893 cmd, cmdresult.fail_reason, cmdresult.output)
3895 return cmdresult.output
3897 if lock is not None:
3898 # Release lock at last
3903 def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
3904 """Creates or removes the watcher pause file.
3906 @type until: None or number
3907 @param until: Unix timestamp saying until when the watcher shouldn't run
3911 logging.info("Received request to no longer pause watcher")
3912 utils.RemoveFile(_filename)
3914 logging.info("Received request to pause watcher until %s", until)
3916 if not ht.TNumber(until):
3917 _Fail("Duration must be numeric")
3919 utils.WriteFile(_filename, data="%d\n" % (until, ), mode=0644)
3922 class HooksRunner(object):
3925 This class is instantiated on the node side (ganeti-noded) and not
3929 def __init__(self, hooks_base_dir=None):
3930 """Constructor for hooks runner.
3932 @type hooks_base_dir: str or None
3933 @param hooks_base_dir: if not None, this overrides the
3934 L{pathutils.HOOKS_BASE_DIR} (useful for unittests)
3937 if hooks_base_dir is None:
3938 hooks_base_dir = pathutils.HOOKS_BASE_DIR
3939 # yeah, _BASE_DIR is not valid for attributes, we use it like a
3941 self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
3943 def RunLocalHooks(self, node_list, hpath, phase, env):
3944 """Check that the hooks will be run only locally and then run them.
3947 assert len(node_list) == 1
3949 _, myself = ssconf.GetMasterAndMyself()
3950 assert node == myself
3952 results = self.RunHooks(hpath, phase, env)
3954 # Return values in the form expected by HooksMaster
3955 return {node: (None, False, results)}
3957 def RunHooks(self, hpath, phase, env):
3958 """Run the scripts in the hooks directory.
3961 @param hpath: the path to the hooks directory which
3964 @param phase: either L{constants.HOOKS_PHASE_PRE} or
3965 L{constants.HOOKS_PHASE_POST}
3967 @param env: dictionary with the environment for the hook
3969 @return: list of 3-element tuples:
3971 - script result, either L{constants.HKR_SUCCESS} or
3972 L{constants.HKR_FAIL}
3973 - output of the script
3975 @raise errors.ProgrammerError: for invalid input
3979 if phase == constants.HOOKS_PHASE_PRE:
3981 elif phase == constants.HOOKS_PHASE_POST:
3984 _Fail("Unknown hooks phase '%s'", phase)
3986 subdir = "%s-%s.d" % (hpath, suffix)
3987 dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3991 if not os.path.isdir(dir_name):
3992 # for non-existing/non-dirs, we simply exit instead of logging a
3993 # warning at every operation
3996 runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3998 for (relname, relstatus, runresult) in runparts_results:
3999 if relstatus == constants.RUNPARTS_SKIP:
4000 rrval = constants.HKR_SKIP
4002 elif relstatus == constants.RUNPARTS_ERR:
4003 rrval = constants.HKR_FAIL
4004 output = "Hook script execution error: %s" % runresult
4005 elif relstatus == constants.RUNPARTS_RUN:
4006 if runresult.failed:
4007 rrval = constants.HKR_FAIL
4009 rrval = constants.HKR_SUCCESS
4010 output = utils.SafeEncode(runresult.output.strip())
4011 results.append(("%s/%s" % (subdir, relname), rrval, output))
4016 class IAllocatorRunner(object):
4017 """IAllocator runner.
4019 This class is instantiated on the node side (ganeti-noded) and not on
4024 def Run(name, idata):
4025 """Run an iallocator script.
4028 @param name: the iallocator script name
4030 @param idata: the allocator input data
4033 @return: two element tuple of:
4035 - either error message or stdout of allocator (for success)
4038 alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
4040 if alloc_script is None:
4041 _Fail("iallocator module '%s' not found in the search path", name)
4043 fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
4047 result = utils.RunCmd([alloc_script, fin_name])
4049 _Fail("iallocator module '%s' failed: %s, output '%s'",
4050 name, result.fail_reason, result.output)
4054 return result.stdout
4057 class DevCacheManager(object):
4058 """Simple class for managing a cache of block device information.
4061 _DEV_PREFIX = "/dev/"
4062 _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4065 def _ConvertPath(cls, dev_path):
4066 """Converts a /dev/name path to the cache file name.
4068 This replaces slashes with underscores and strips the /dev
4069 prefix. It then returns the full path to the cache file.
4072 @param dev_path: the C{/dev/} path name
4074 @return: the converted path name
4077 if dev_path.startswith(cls._DEV_PREFIX):
4078 dev_path = dev_path[len(cls._DEV_PREFIX):]
4079 dev_path = dev_path.replace("/", "_")
4080 fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4084 def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4085 """Updates the cache information for a given device.
4088 @param dev_path: the pathname of the device
4090 @param owner: the owner (instance name) of the device
4091 @type on_primary: bool
4092 @param on_primary: whether this is the primary
4095 @param iv_name: the instance-visible name of the
4096 device, as in objects.Disk.iv_name
4101 if dev_path is None:
4102 logging.error("DevCacheManager.UpdateCache got a None dev_path")
4104 fpath = cls._ConvertPath(dev_path)
4110 iv_name = "not_visible"
4111 fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4113 utils.WriteFile(fpath, data=fdata)
4114 except EnvironmentError, err:
4115 logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4118 def RemoveCache(cls, dev_path):
4119 """Remove data for a dev_path.
4121 This is just a wrapper over L{utils.io.RemoveFile} with a converted
4122 path name and logging.
4125 @param dev_path: the pathname of the device
4130 if dev_path is None:
4131 logging.error("DevCacheManager.RemoveCache got a None dev_path")
4133 fpath = cls._ConvertPath(dev_path)
4135 utils.RemoveFile(fpath)
4136 except EnvironmentError, err:
4137 logging.exception("Can't update bdev cache for %s: %s", dev_path, err)