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,C0302
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
37 # C0302: This module has become too big and should be split up
54 from ganeti import errors
55 from ganeti import utils
56 from ganeti import ssh
57 from ganeti import hypervisor
58 from ganeti import constants
59 from ganeti.storage import bdev
60 from ganeti.storage import drbd
61 from ganeti.storage import filestorage
62 from ganeti import objects
63 from ganeti import ssconf
64 from ganeti import serializer
65 from ganeti import netutils
66 from ganeti import runtime
67 from ganeti import compat
68 from ganeti import pathutils
69 from ganeti import vcluster
71 from ganeti.storage.base import BlockDev
72 from ganeti.storage.drbd import DRBD8
73 from ganeti import hooksmaster
76 _BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id"
77 _ALLOWED_CLEAN_DIRS = compat.UniqueFrozenset([
79 pathutils.JOB_QUEUE_ARCHIVE_DIR,
81 pathutils.CRYPTO_KEYS_DIR,
83 _MAX_SSL_CERT_VALIDITY = 7 * 24 * 60 * 60
84 _X509_KEY_FILE = "key"
85 _X509_CERT_FILE = "cert"
86 _IES_STATUS_FILE = "status"
90 #: Valid LVS output line regex
91 _LVSLINE_REGEX = re.compile(r"^ *([^|]+)\|([^|]+)\|([0-9.]+)\|([^|]{6,})\|?$")
93 # Actions for the master setup script
94 _MASTER_START = "start"
97 #: Maximum file permissions for restricted command directory and executables
98 _RCMD_MAX_MODE = (stat.S_IRWXU |
99 stat.S_IRGRP | stat.S_IXGRP |
100 stat.S_IROTH | stat.S_IXOTH)
102 #: Delay before returning an error for restricted commands
103 _RCMD_INVALID_DELAY = 10
105 #: How long to wait to acquire lock for restricted commands (shorter than
106 #: L{_RCMD_INVALID_DELAY}) to reduce blockage of noded forks when many
107 #: command requests arrive
108 _RCMD_LOCK_TIMEOUT = _RCMD_INVALID_DELAY * 0.8
111 class RPCFail(Exception):
112 """Class denoting RPC failure.
114 Its argument is the error message.
119 def _GetInstReasonFilename(instance_name):
120 """Path of the file containing the reason of the instance status change.
122 @type instance_name: string
123 @param instance_name: The name of the instance
125 @return: The path of the file
128 return utils.PathJoin(pathutils.INSTANCE_REASON_DIR, instance_name)
131 def _StoreInstReasonTrail(instance_name, trail):
132 """Serialize a reason trail related to an instance change of state to file.
134 The exact location of the file depends on the name of the instance and on
135 the configuration of the Ganeti cluster defined at deploy time.
137 @type instance_name: string
138 @param instance_name: The name of the instance
142 json = serializer.DumpJson(trail)
143 filename = _GetInstReasonFilename(instance_name)
144 utils.WriteFile(filename, data=json)
147 def _Fail(msg, *args, **kwargs):
148 """Log an error and the raise an RPCFail exception.
150 This exception is then handled specially in the ganeti daemon and
151 turned into a 'failed' return type. As such, this function is a
152 useful shortcut for logging the error and returning it to the master
156 @param msg: the text of the exception
162 if "log" not in kwargs or kwargs["log"]: # if we should log this error
163 if "exc" in kwargs and kwargs["exc"]:
164 logging.exception(msg)
171 """Simple wrapper to return a SimpleStore.
173 @rtype: L{ssconf.SimpleStore}
174 @return: a SimpleStore instance
177 return ssconf.SimpleStore()
180 def _GetSshRunner(cluster_name):
181 """Simple wrapper to return an SshRunner.
183 @type cluster_name: str
184 @param cluster_name: the cluster name, which is needed
185 by the SshRunner constructor
186 @rtype: L{ssh.SshRunner}
187 @return: an SshRunner instance
190 return ssh.SshRunner(cluster_name)
193 def _Decompress(data):
194 """Unpacks data compressed by the RPC client.
196 @type data: list or tuple
197 @param data: Data sent by RPC client
199 @return: Decompressed data
202 assert isinstance(data, (list, tuple))
203 assert len(data) == 2
204 (encoding, content) = data
205 if encoding == constants.RPC_ENCODING_NONE:
207 elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
208 return zlib.decompress(base64.b64decode(content))
210 raise AssertionError("Unknown data encoding")
213 def _CleanDirectory(path, exclude=None):
214 """Removes all regular files in a directory.
217 @param path: the directory to clean
219 @param exclude: list of files to be excluded, defaults
223 if path not in _ALLOWED_CLEAN_DIRS:
224 _Fail("Path passed to _CleanDirectory not in allowed clean targets: '%s'",
227 if not os.path.isdir(path):
232 # Normalize excluded paths
233 exclude = [os.path.normpath(i) for i in exclude]
235 for rel_name in utils.ListVisibleFiles(path):
236 full_name = utils.PathJoin(path, rel_name)
237 if full_name in exclude:
239 if os.path.isfile(full_name) and not os.path.islink(full_name):
240 utils.RemoveFile(full_name)
243 def _BuildUploadFileList():
244 """Build the list of allowed upload files.
246 This is abstracted so that it's built only once at module import time.
249 allowed_files = set([
250 pathutils.CLUSTER_CONF_FILE,
252 pathutils.SSH_KNOWN_HOSTS_FILE,
253 pathutils.VNC_PASSWORD_FILE,
254 pathutils.RAPI_CERT_FILE,
255 pathutils.SPICE_CERT_FILE,
256 pathutils.SPICE_CACERT_FILE,
257 pathutils.RAPI_USERS_FILE,
258 pathutils.CONFD_HMAC_KEY,
259 pathutils.CLUSTER_DOMAIN_SECRET_FILE,
262 for hv_name in constants.HYPER_TYPES:
263 hv_class = hypervisor.GetHypervisorClass(hv_name)
264 allowed_files.update(hv_class.GetAncillaryFiles()[0])
266 assert pathutils.FILE_STORAGE_PATHS_FILE not in allowed_files, \
267 "Allowed file storage paths should never be uploaded via RPC"
269 return frozenset(allowed_files)
272 _ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
276 """Removes job queue files and archived jobs.
282 _CleanDirectory(pathutils.QUEUE_DIR, exclude=[pathutils.JOB_QUEUE_LOCK_FILE])
283 _CleanDirectory(pathutils.JOB_QUEUE_ARCHIVE_DIR)
287 """Returns master information.
289 This is an utility function to compute master information, either
290 for consumption here or from the node daemon.
293 @return: master_netdev, master_ip, master_name, primary_ip_family,
295 @raise RPCFail: in case of errors
300 master_netdev = cfg.GetMasterNetdev()
301 master_ip = cfg.GetMasterIP()
302 master_netmask = cfg.GetMasterNetmask()
303 master_node = cfg.GetMasterNode()
304 primary_ip_family = cfg.GetPrimaryIPFamily()
305 except errors.ConfigurationError, err:
306 _Fail("Cluster configuration incomplete: %s", err, exc=True)
307 return (master_netdev, master_ip, master_node, primary_ip_family,
311 def RunLocalHooks(hook_opcode, hooks_path, env_builder_fn):
312 """Decorator that runs hooks before and after the decorated function.
314 @type hook_opcode: string
315 @param hook_opcode: opcode of the hook
316 @type hooks_path: string
317 @param hooks_path: path of the hooks
318 @type env_builder_fn: function
319 @param env_builder_fn: function that returns a dictionary containing the
320 environment variables for the hooks. Will get all the parameters of the
322 @raise RPCFail: in case of pre-hook failure
326 def wrapper(*args, **kwargs):
327 _, myself = ssconf.GetMasterAndMyself()
328 nodes = ([myself], [myself]) # these hooks run locally
330 env_fn = compat.partial(env_builder_fn, *args, **kwargs)
334 hm = hooksmaster.HooksMaster(hook_opcode, hooks_path, nodes,
335 hr.RunLocalHooks, None, env_fn,
336 logging.warning, cfg.GetClusterName(),
338 hm.RunPhase(constants.HOOKS_PHASE_PRE)
339 result = fn(*args, **kwargs)
340 hm.RunPhase(constants.HOOKS_PHASE_POST)
347 def _BuildMasterIpEnv(master_params, use_external_mip_script=None):
348 """Builds environment variables for master IP hooks.
350 @type master_params: L{objects.MasterNetworkParameters}
351 @param master_params: network parameters of the master
352 @type use_external_mip_script: boolean
353 @param use_external_mip_script: whether to use an external master IP
354 address setup script (unused, but necessary per the implementation of the
355 _RunLocalHooks decorator)
358 # pylint: disable=W0613
359 ver = netutils.IPAddress.GetVersionFromAddressFamily(master_params.ip_family)
361 "MASTER_NETDEV": master_params.netdev,
362 "MASTER_IP": master_params.ip,
363 "MASTER_NETMASK": str(master_params.netmask),
364 "CLUSTER_IP_VERSION": str(ver),
370 def _RunMasterSetupScript(master_params, action, use_external_mip_script):
371 """Execute the master IP address setup script.
373 @type master_params: L{objects.MasterNetworkParameters}
374 @param master_params: network parameters of the master
376 @param action: action to pass to the script. Must be one of
377 L{backend._MASTER_START} or L{backend._MASTER_STOP}
378 @type use_external_mip_script: boolean
379 @param use_external_mip_script: whether to use an external master IP
381 @raise backend.RPCFail: if there are errors during the execution of the
385 env = _BuildMasterIpEnv(master_params)
387 if use_external_mip_script:
388 setup_script = pathutils.EXTERNAL_MASTER_SETUP_SCRIPT
390 setup_script = pathutils.DEFAULT_MASTER_SETUP_SCRIPT
392 result = utils.RunCmd([setup_script, action], env=env, reset_env=True)
395 _Fail("Failed to %s the master IP. Script return value: %s, output: '%s'" %
396 (action, result.exit_code, result.output), log=True)
399 @RunLocalHooks(constants.FAKE_OP_MASTER_TURNUP, "master-ip-turnup",
401 def ActivateMasterIp(master_params, use_external_mip_script):
402 """Activate the IP address of the master daemon.
404 @type master_params: L{objects.MasterNetworkParameters}
405 @param master_params: network parameters of the master
406 @type use_external_mip_script: boolean
407 @param use_external_mip_script: whether to use an external master IP
409 @raise RPCFail: in case of errors during the IP startup
412 _RunMasterSetupScript(master_params, _MASTER_START,
413 use_external_mip_script)
416 def StartMasterDaemons(no_voting):
417 """Activate local node as master node.
419 The function will start the master daemons (ganeti-masterd and ganeti-rapi).
421 @type no_voting: boolean
422 @param no_voting: whether to start ganeti-masterd without a node vote
423 but still non-interactively
429 masterd_args = "--no-voting --yes-do-it"
434 "EXTRA_MASTERD_ARGS": masterd_args,
437 result = utils.RunCmd([pathutils.DAEMON_UTIL, "start-master"], env=env)
439 msg = "Can't start Ganeti master: %s" % result.output
444 @RunLocalHooks(constants.FAKE_OP_MASTER_TURNDOWN, "master-ip-turndown",
446 def DeactivateMasterIp(master_params, use_external_mip_script):
447 """Deactivate the master IP on this node.
449 @type master_params: L{objects.MasterNetworkParameters}
450 @param master_params: network parameters of the master
451 @type use_external_mip_script: boolean
452 @param use_external_mip_script: whether to use an external master IP
454 @raise RPCFail: in case of errors during the IP turndown
457 _RunMasterSetupScript(master_params, _MASTER_STOP,
458 use_external_mip_script)
461 def StopMasterDaemons():
462 """Stop the master daemons on this node.
464 Stop the master daemons (ganeti-masterd and ganeti-rapi) on this node.
469 # TODO: log and report back to the caller the error failures; we
470 # need to decide in which case we fail the RPC for this
472 result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop-master"])
474 logging.error("Could not stop Ganeti master, command %s had exitcode %s"
476 result.cmd, result.exit_code, result.output)
479 def ChangeMasterNetmask(old_netmask, netmask, master_ip, master_netdev):
480 """Change the netmask of the master IP.
482 @param old_netmask: the old value of the netmask
483 @param netmask: the new value of the netmask
484 @param master_ip: the master IP
485 @param master_netdev: the master network device
488 if old_netmask == netmask:
491 if not netutils.IPAddress.Own(master_ip):
492 _Fail("The master IP address is not up, not attempting to change its"
495 result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
496 "%s/%s" % (master_ip, netmask),
497 "dev", master_netdev, "label",
498 "%s:0" % master_netdev])
500 _Fail("Could not set the new netmask on the master IP address")
502 result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
503 "%s/%s" % (master_ip, old_netmask),
504 "dev", master_netdev, "label",
505 "%s:0" % master_netdev])
507 _Fail("Could not bring down the master IP address with the old netmask")
510 def EtcHostsModify(mode, host, ip):
511 """Modify a host entry in /etc/hosts.
513 @param mode: The mode to operate. Either add or remove entry
514 @param host: The host to operate on
515 @param ip: The ip associated with the entry
518 if mode == constants.ETC_HOSTS_ADD:
520 RPCFail("Mode 'add' needs 'ip' parameter, but parameter not"
522 utils.AddHostToEtcHosts(host, ip)
523 elif mode == constants.ETC_HOSTS_REMOVE:
525 RPCFail("Mode 'remove' does not allow 'ip' parameter, but"
526 " parameter is present")
527 utils.RemoveHostFromEtcHosts(host)
529 RPCFail("Mode not supported")
532 def LeaveCluster(modify_ssh_setup):
533 """Cleans up and remove the current node.
535 This function cleans up and prepares the current node to be removed
538 If processing is successful, then it raises an
539 L{errors.QuitGanetiException} which is used as a special case to
540 shutdown the node daemon.
542 @param modify_ssh_setup: boolean
545 _CleanDirectory(pathutils.DATA_DIR)
546 _CleanDirectory(pathutils.CRYPTO_KEYS_DIR)
551 priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.SSH_LOGIN_USER)
553 utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
555 utils.RemoveFile(priv_key)
556 utils.RemoveFile(pub_key)
557 except errors.OpExecError:
558 logging.exception("Error while processing ssh files")
561 utils.RemoveFile(pathutils.CONFD_HMAC_KEY)
562 utils.RemoveFile(pathutils.RAPI_CERT_FILE)
563 utils.RemoveFile(pathutils.SPICE_CERT_FILE)
564 utils.RemoveFile(pathutils.SPICE_CACERT_FILE)
565 utils.RemoveFile(pathutils.NODED_CERT_FILE)
566 except: # pylint: disable=W0702
567 logging.exception("Error while removing cluster secrets")
569 result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop", constants.CONFD])
571 logging.error("Command %s failed with exitcode %s and error %s",
572 result.cmd, result.exit_code, result.output)
574 # Raise a custom exception (handled in ganeti-noded)
575 raise errors.QuitGanetiException(True, "Shutdown scheduled")
578 def _CheckStorageParams(params, num_params):
579 """Performs sanity checks for storage parameters.
582 @param params: list of storage parameters
583 @type num_params: int
584 @param num_params: expected number of parameters
588 raise errors.ProgrammerError("No storage parameters for storage"
589 " reporting is provided.")
590 if not isinstance(params, list):
591 raise errors.ProgrammerError("The storage parameters are not of type"
592 " list: '%s'" % params)
593 if not len(params) == num_params:
594 raise errors.ProgrammerError("Did not receive the expected number of"
595 "storage parameters: expected %s,"
596 " received '%s'" % (num_params, len(params)))
599 def _CheckLvmStorageParams(params):
600 """Performs sanity check for the 'exclusive storage' flag.
602 @see: C{_CheckStorageParams}
605 _CheckStorageParams(params, 1)
606 excl_stor = params[0]
607 if not isinstance(params[0], bool):
608 raise errors.ProgrammerError("Exclusive storage parameter is not"
609 " boolean: '%s'." % excl_stor)
613 def _GetLvmVgSpaceInfo(name, params):
614 """Wrapper around C{_GetVgInfo} which checks the storage parameters.
617 @param name: name of the volume group
619 @param params: list of storage parameters, which in this case should be
620 containing only one for exclusive storage
623 excl_stor = _CheckLvmStorageParams(params)
624 return _GetVgInfo(name, excl_stor)
628 name, excl_stor, info_fn=bdev.LogicalVolume.GetVGInfo):
629 """Retrieves information about a LVM volume group.
632 # TODO: GetVGInfo supports returning information for multiple VGs at once
633 vginfo = info_fn([name], excl_stor)
635 vg_free = int(round(vginfo[0][0], 0))
636 vg_size = int(round(vginfo[0][1], 0))
642 "type": constants.ST_LVM_VG,
644 "storage_free": vg_free,
645 "storage_size": vg_size,
649 def _GetLvmPvSpaceInfo(name, params):
650 """Wrapper around C{_GetVgSpindlesInfo} with sanity checks.
652 @see: C{_GetLvmVgSpaceInfo}
655 excl_stor = _CheckLvmStorageParams(params)
656 return _GetVgSpindlesInfo(name, excl_stor)
659 def _GetVgSpindlesInfo(
660 name, excl_stor, info_fn=bdev.LogicalVolume.GetVgSpindlesInfo):
661 """Retrieves information about spindles in an LVM volume group.
665 @type excl_stor: bool
666 @param excl_stor: exclusive storage
668 @return: dictionary whose keys are "name", "vg_free", "vg_size" for VG name,
669 free spindles, total spindles respectively
673 (vg_free, vg_size) = info_fn(name)
678 "type": constants.ST_LVM_PV,
680 "storage_free": vg_free,
681 "storage_size": vg_size,
685 def _GetHvInfo(name, hvparams, get_hv_fn=hypervisor.GetHypervisor):
686 """Retrieves node information from a hypervisor.
688 The information returned depends on the hypervisor. Common items:
690 - vg_size is the size of the configured volume group in MiB
691 - vg_free is the free size of the volume group in MiB
692 - memory_dom0 is the memory allocated for domain0 in MiB
693 - memory_free is the currently available (free) ram in MiB
694 - memory_total is the total number of ram in MiB
695 - hv_version: the hypervisor version, if available
697 @type hvparams: dict of string
698 @param hvparams: the hypervisor's hvparams
701 return get_hv_fn(name).GetNodeInfo(hvparams=hvparams)
704 def _GetHvInfoAll(hv_specs, get_hv_fn=hypervisor.GetHypervisor):
705 """Retrieves node information for all hypervisors.
707 See C{_GetHvInfo} for information on the output.
709 @type hv_specs: list of pairs (string, dict of strings)
710 @param hv_specs: list of pairs of a hypervisor's name and its hvparams
717 for hvname, hvparams in hv_specs:
718 result.append(_GetHvInfo(hvname, hvparams, get_hv_fn))
722 def _GetNamedNodeInfo(names, fn):
723 """Calls C{fn} for all names in C{names} and returns a dictionary.
731 return map(fn, names)
734 def GetNodeInfo(storage_units, hv_specs):
735 """Gives back a hash with different information about the node.
737 @type storage_units: list of tuples (string, string, list)
738 @param storage_units: List of tuples (storage unit, identifier, parameters) to
739 ask for disk space information. In case of lvm-vg, the identifier is
740 the VG name. The parameters can contain additional, storage-type-specific
741 parameters, for example exclusive storage for lvm storage.
742 @type hv_specs: list of pairs (string, dict of strings)
743 @param hv_specs: list of pairs of a hypervisor's name and its hvparams
744 @rtype: tuple; (string, None/dict, None/dict)
745 @return: Tuple containing boot ID, volume group information and hypervisor
749 bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
750 storage_info = _GetNamedNodeInfo(
752 (lambda (storage_type, storage_key, storage_params):
753 _ApplyStorageInfoFunction(storage_type, storage_key, storage_params)))
754 hv_info = _GetHvInfoAll(hv_specs)
755 return (bootid, storage_info, hv_info)
758 def _GetFileStorageSpaceInfo(path, params):
759 """Wrapper around filestorage.GetSpaceInfo.
761 The purpose of this wrapper is to call filestorage.GetFileStorageSpaceInfo
762 and ignore the *args parameter to not leak it into the filestorage
765 @see: C{filestorage.GetFileStorageSpaceInfo} for description of the
769 _CheckStorageParams(params, 0)
770 return filestorage.GetFileStorageSpaceInfo(path)
773 # FIXME: implement storage reporting for all missing storage types.
774 _STORAGE_TYPE_INFO_FN = {
775 constants.ST_BLOCK: None,
776 constants.ST_DISKLESS: None,
777 constants.ST_EXT: None,
778 constants.ST_FILE: _GetFileStorageSpaceInfo,
779 constants.ST_LVM_PV: _GetLvmPvSpaceInfo,
780 constants.ST_LVM_VG: _GetLvmVgSpaceInfo,
781 constants.ST_RADOS: None,
785 def _ApplyStorageInfoFunction(storage_type, storage_key, *args):
786 """Looks up and applies the correct function to calculate free and total
787 storage for the given storage type.
789 @type storage_type: string
790 @param storage_type: the storage type for which the storage shall be reported.
791 @type storage_key: string
792 @param storage_key: identifier of a storage unit, e.g. the volume group name
793 of an LVM storage unit
795 @param args: various parameters that can be used for storage reporting. These
796 parameters and their semantics vary from storage type to storage type and
797 are just propagated in this function.
798 @return: the results of the application of the storage space function (see
799 _STORAGE_TYPE_INFO_FN) if storage space reporting is implemented for that
801 @raises NotImplementedError: for storage types who don't support space
804 fn = _STORAGE_TYPE_INFO_FN[storage_type]
806 return fn(storage_key, *args)
808 raise NotImplementedError
811 def _CheckExclusivePvs(pvi_list):
812 """Check that PVs are not shared among LVs
814 @type pvi_list: list of L{objects.LvmPvInfo} objects
815 @param pvi_list: information about the PVs
817 @rtype: list of tuples (string, list of strings)
818 @return: offending volumes, as tuples: (pv_name, [lv1_name, lv2_name...])
823 if len(pvi.lv_list) > 1:
824 res.append((pvi.name, pvi.lv_list))
828 def _VerifyHypervisors(what, vm_capable, result, all_hvparams,
829 get_hv_fn=hypervisor.GetHypervisor):
830 """Verifies the hypervisor. Appends the results to the 'results' list.
833 @param what: a dictionary of things to check
834 @type vm_capable: boolean
835 @param vm_capable: whether or not this node is vm capable
837 @param result: dictionary of verification results; results of the
838 verifications in this function will be added here
839 @type all_hvparams: dict of dict of string
840 @param all_hvparams: dictionary mapping hypervisor names to hvparams
841 @type get_hv_fn: function
842 @param get_hv_fn: function to retrieve the hypervisor, to improve testability
848 if constants.NV_HYPERVISOR in what:
849 result[constants.NV_HYPERVISOR] = {}
850 for hv_name in what[constants.NV_HYPERVISOR]:
851 hvparams = all_hvparams[hv_name]
853 val = get_hv_fn(hv_name).Verify(hvparams=hvparams)
854 except errors.HypervisorError, err:
855 val = "Error while checking hypervisor: %s" % str(err)
856 result[constants.NV_HYPERVISOR][hv_name] = val
859 def _VerifyHvparams(what, vm_capable, result,
860 get_hv_fn=hypervisor.GetHypervisor):
861 """Verifies the hvparams. Appends the results to the 'results' list.
864 @param what: a dictionary of things to check
865 @type vm_capable: boolean
866 @param vm_capable: whether or not this node is vm capable
868 @param result: dictionary of verification results; results of the
869 verifications in this function will be added here
870 @type get_hv_fn: function
871 @param get_hv_fn: function to retrieve the hypervisor, to improve testability
877 if constants.NV_HVPARAMS in what:
878 result[constants.NV_HVPARAMS] = []
879 for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
881 logging.info("Validating hv %s, %s", hv_name, hvparms)
882 get_hv_fn(hv_name).ValidateParameters(hvparms)
883 except errors.HypervisorError, err:
884 result[constants.NV_HVPARAMS].append((source, hv_name, str(err)))
887 def _VerifyInstanceList(what, vm_capable, result, all_hvparams):
888 """Verifies the instance list.
891 @param what: a dictionary of things to check
892 @type vm_capable: boolean
893 @param vm_capable: whether or not this node is vm capable
895 @param result: dictionary of verification results; results of the
896 verifications in this function will be added here
897 @type all_hvparams: dict of dict of string
898 @param all_hvparams: dictionary mapping hypervisor names to hvparams
901 if constants.NV_INSTANCELIST in what and vm_capable:
902 # GetInstanceList can fail
904 val = GetInstanceList(what[constants.NV_INSTANCELIST],
905 all_hvparams=all_hvparams)
908 result[constants.NV_INSTANCELIST] = val
911 def _VerifyNodeInfo(what, vm_capable, result, all_hvparams):
912 """Verifies the node info.
915 @param what: a dictionary of things to check
916 @type vm_capable: boolean
917 @param vm_capable: whether or not this node is vm capable
919 @param result: dictionary of verification results; results of the
920 verifications in this function will be added here
921 @type all_hvparams: dict of dict of string
922 @param all_hvparams: dictionary mapping hypervisor names to hvparams
925 if constants.NV_HVINFO in what and vm_capable:
926 hvname = what[constants.NV_HVINFO]
927 hyper = hypervisor.GetHypervisor(hvname)
928 hvparams = all_hvparams[hvname]
929 result[constants.NV_HVINFO] = hyper.GetNodeInfo(hvparams=hvparams)
932 def VerifyNode(what, cluster_name, all_hvparams):
933 """Verify the status of the local node.
935 Based on the input L{what} parameter, various checks are done on the
938 If the I{filelist} key is present, this list of
939 files is checksummed and the file/checksum pairs are returned.
941 If the I{nodelist} key is present, we check that we have
942 connectivity via ssh with the target nodes (and check the hostname
945 If the I{node-net-test} key is present, we check that we have
946 connectivity to the given nodes via both primary IP and, if
947 applicable, secondary IPs.
950 @param what: a dictionary of things to check:
951 - filelist: list of files for which to compute checksums
952 - nodelist: list of nodes we should check ssh communication with
953 - node-net-test: list of nodes we should check node daemon port
955 - hypervisor: list with hypervisors to run the verify for
956 @type cluster_name: string
957 @param cluster_name: the cluster's name
958 @type all_hvparams: dict of dict of strings
959 @param all_hvparams: a dictionary mapping hypervisor names to hvparams
961 @return: a dictionary with the same keys as the input dict, and
962 values representing the result of the checks
966 my_name = netutils.Hostname.GetSysName()
967 port = netutils.GetDaemonPort(constants.NODED)
968 vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
970 _VerifyHypervisors(what, vm_capable, result, all_hvparams)
971 _VerifyHvparams(what, vm_capable, result)
973 if constants.NV_FILELIST in what:
974 fingerprints = utils.FingerprintFiles(map(vcluster.LocalizeVirtualPath,
975 what[constants.NV_FILELIST]))
976 result[constants.NV_FILELIST] = \
977 dict((vcluster.MakeVirtualPath(key), value)
978 for (key, value) in fingerprints.items())
980 if constants.NV_NODELIST in what:
981 (nodes, bynode) = what[constants.NV_NODELIST]
983 # Add nodes from other groups (different for each node)
985 nodes.extend(bynode[my_name])
990 random.shuffle(nodes)
992 # Try to contact all nodes
995 success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
999 result[constants.NV_NODELIST] = val
1001 if constants.NV_NODENETTEST in what:
1002 result[constants.NV_NODENETTEST] = tmp = {}
1003 my_pip = my_sip = None
1004 for name, pip, sip in what[constants.NV_NODENETTEST]:
1010 tmp[my_name] = ("Can't find my own primary/secondary IP"
1011 " in the node list")
1013 for name, pip, sip in what[constants.NV_NODENETTEST]:
1015 if not netutils.TcpPing(pip, port, source=my_pip):
1016 fail.append("primary")
1018 if not netutils.TcpPing(sip, port, source=my_sip):
1019 fail.append("secondary")
1021 tmp[name] = ("failure using the %s interface(s)" %
1024 if constants.NV_MASTERIP in what:
1025 # FIXME: add checks on incoming data structures (here and in the
1026 # rest of the function)
1027 master_name, master_ip = what[constants.NV_MASTERIP]
1028 if master_name == my_name:
1029 source = constants.IP4_ADDRESS_LOCALHOST
1032 result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
1035 if constants.NV_USERSCRIPTS in what:
1036 result[constants.NV_USERSCRIPTS] = \
1037 [script for script in what[constants.NV_USERSCRIPTS]
1038 if not utils.IsExecutable(script)]
1040 if constants.NV_OOB_PATHS in what:
1041 result[constants.NV_OOB_PATHS] = tmp = []
1042 for path in what[constants.NV_OOB_PATHS]:
1045 except OSError, err:
1046 tmp.append("error stating out of band helper: %s" % err)
1048 if stat.S_ISREG(st.st_mode):
1049 if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
1052 tmp.append("out of band helper %s is not executable" % path)
1054 tmp.append("out of band helper %s is not a file" % path)
1056 if constants.NV_LVLIST in what and vm_capable:
1058 val = GetVolumeList(utils.ListVolumeGroups().keys())
1059 except RPCFail, err:
1061 result[constants.NV_LVLIST] = val
1063 _VerifyInstanceList(what, vm_capable, result, all_hvparams)
1065 if constants.NV_VGLIST in what and vm_capable:
1066 result[constants.NV_VGLIST] = utils.ListVolumeGroups()
1068 if constants.NV_PVLIST in what and vm_capable:
1069 check_exclusive_pvs = constants.NV_EXCLUSIVEPVS in what
1070 val = bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
1071 filter_allocatable=False,
1072 include_lvs=check_exclusive_pvs)
1073 if check_exclusive_pvs:
1074 result[constants.NV_EXCLUSIVEPVS] = _CheckExclusivePvs(val)
1076 # Avoid sending useless data on the wire
1078 result[constants.NV_PVLIST] = map(objects.LvmPvInfo.ToDict, val)
1080 if constants.NV_VERSION in what:
1081 result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
1082 constants.RELEASE_VERSION)
1084 _VerifyNodeInfo(what, vm_capable, result, all_hvparams)
1086 if constants.NV_DRBDVERSION in what and vm_capable:
1088 drbd_version = DRBD8.GetProcInfo().GetVersionString()
1089 except errors.BlockDeviceError, err:
1090 logging.warning("Can't get DRBD version", exc_info=True)
1091 drbd_version = str(err)
1092 result[constants.NV_DRBDVERSION] = drbd_version
1094 if constants.NV_DRBDLIST in what and vm_capable:
1096 used_minors = drbd.DRBD8.GetUsedDevs()
1097 except errors.BlockDeviceError, err:
1098 logging.warning("Can't get used minors list", exc_info=True)
1099 used_minors = str(err)
1100 result[constants.NV_DRBDLIST] = used_minors
1102 if constants.NV_DRBDHELPER in what and vm_capable:
1105 payload = drbd.DRBD8.GetUsermodeHelper()
1106 except errors.BlockDeviceError, err:
1107 logging.error("Can't get DRBD usermode helper: %s", str(err))
1110 result[constants.NV_DRBDHELPER] = (status, payload)
1112 if constants.NV_NODESETUP in what:
1113 result[constants.NV_NODESETUP] = tmpr = []
1114 if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
1115 tmpr.append("The sysfs filesytem doesn't seem to be mounted"
1116 " under /sys, missing required directories /sys/block"
1117 " and /sys/class/net")
1118 if (not os.path.isdir("/proc/sys") or
1119 not os.path.isfile("/proc/sysrq-trigger")):
1120 tmpr.append("The procfs filesystem doesn't seem to be mounted"
1121 " under /proc, missing required directory /proc/sys and"
1122 " the file /proc/sysrq-trigger")
1124 if constants.NV_TIME in what:
1125 result[constants.NV_TIME] = utils.SplitTime(time.time())
1127 if constants.NV_OSLIST in what and vm_capable:
1128 result[constants.NV_OSLIST] = DiagnoseOS()
1130 if constants.NV_BRIDGES in what and vm_capable:
1131 result[constants.NV_BRIDGES] = [bridge
1132 for bridge in what[constants.NV_BRIDGES]
1133 if not utils.BridgeExists(bridge)]
1135 if what.get(constants.NV_ACCEPTED_STORAGE_PATHS) == my_name:
1136 result[constants.NV_ACCEPTED_STORAGE_PATHS] = \
1137 filestorage.ComputeWrongFileStoragePaths()
1139 if what.get(constants.NV_FILE_STORAGE_PATH):
1140 pathresult = filestorage.CheckFileStoragePath(
1141 what[constants.NV_FILE_STORAGE_PATH])
1143 result[constants.NV_FILE_STORAGE_PATH] = pathresult
1145 if what.get(constants.NV_SHARED_FILE_STORAGE_PATH):
1146 pathresult = filestorage.CheckFileStoragePath(
1147 what[constants.NV_SHARED_FILE_STORAGE_PATH])
1149 result[constants.NV_SHARED_FILE_STORAGE_PATH] = pathresult
1154 def GetBlockDevSizes(devices):
1155 """Return the size of the given block devices
1158 @param devices: list of block device nodes to query
1161 dictionary of all block devices under /dev (key). The value is their
1164 {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
1167 DEV_PREFIX = "/dev/"
1170 for devpath in devices:
1171 if not utils.IsBelowDir(DEV_PREFIX, devpath):
1175 st = os.stat(devpath)
1176 except EnvironmentError, err:
1177 logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
1180 if stat.S_ISBLK(st.st_mode):
1181 result = utils.RunCmd(["blockdev", "--getsize64", devpath])
1183 # We don't want to fail, just do not list this device as available
1184 logging.warning("Cannot get size for block device %s", devpath)
1187 size = int(result.stdout) / (1024 * 1024)
1188 blockdevs[devpath] = size
1192 def GetVolumeList(vg_names):
1193 """Compute list of logical volumes and their size.
1195 @type vg_names: list
1196 @param vg_names: the volume groups whose LVs we should list, or
1197 empty for all volume groups
1200 dictionary of all partions (key) with value being a tuple of
1201 their size (in MiB), inactive and online status::
1203 {'xenvg/test1': ('20.06', True, True)}
1205 in case of errors, a string is returned with the error
1213 result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1214 "--separator=%s" % sep,
1215 "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
1217 _Fail("Failed to list logical volumes, lvs output: %s", result.output)
1219 for line in result.stdout.splitlines():
1221 match = _LVSLINE_REGEX.match(line)
1223 logging.error("Invalid line returned from lvs output: '%s'", line)
1225 vg_name, name, size, attr = match.groups()
1226 inactive = attr[4] == "-"
1227 online = attr[5] == "o"
1228 virtual = attr[0] == "v"
1230 # we don't want to report such volumes as existing, since they
1231 # don't really hold data
1233 lvs[vg_name + "/" + name] = (size, inactive, online)
1238 def ListVolumeGroups():
1239 """List the volume groups and their size.
1242 @return: dictionary with keys volume name and values the
1246 return utils.ListVolumeGroups()
1250 """List all volumes on this node.
1254 A list of dictionaries, each having four keys:
1255 - name: the logical volume name,
1256 - size: the size of the logical volume
1257 - dev: the physical device on which the LV lives
1258 - vg: the volume group to which it belongs
1260 In case of errors, we return an empty list and log the
1263 Note that since a logical volume can live on multiple physical
1264 volumes, the resulting list might include a logical volume
1268 result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1270 "--options=lv_name,lv_size,devices,vg_name"])
1272 _Fail("Failed to list logical volumes, lvs output: %s",
1276 return dev.split("(")[0]
1278 def handle_dev(dev):
1279 return [parse_dev(x) for x in dev.split(",")]
1282 line = [v.strip() for v in line]
1283 return [{"name": line[0], "size": line[1],
1284 "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
1287 for line in result.stdout.splitlines():
1288 if line.count("|") >= 3:
1289 all_devs.extend(map_line(line.split("|")))
1291 logging.warning("Strange line in the output from lvs: '%s'", line)
1295 def BridgesExist(bridges_list):
1296 """Check if a list of bridges exist on the current node.
1299 @return: C{True} if all of them exist, C{False} otherwise
1303 for bridge in bridges_list:
1304 if not utils.BridgeExists(bridge):
1305 missing.append(bridge)
1308 _Fail("Missing bridges %s", utils.CommaJoin(missing))
1311 def GetInstanceListForHypervisor(hname, hvparams=None,
1312 get_hv_fn=hypervisor.GetHypervisor):
1313 """Provides a list of instances of the given hypervisor.
1316 @param hname: name of the hypervisor
1317 @type hvparams: dict of strings
1318 @param hvparams: hypervisor parameters for the given hypervisor
1319 @type get_hv_fn: function
1320 @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1321 name; optional parameter to increase testability
1324 @return: a list of all running instances on the current node
1325 - instance1.example.com
1326 - instance2.example.com
1331 hv = get_hv_fn(hname)
1332 names = hv.ListInstances(hvparams=hvparams)
1333 results.extend(names)
1334 except errors.HypervisorError, err:
1335 _Fail("Error enumerating instances (hypervisor %s): %s",
1336 hname, err, exc=True)
1340 def GetInstanceList(hypervisor_list, all_hvparams=None,
1341 get_hv_fn=hypervisor.GetHypervisor):
1342 """Provides a list of instances.
1344 @type hypervisor_list: list
1345 @param hypervisor_list: the list of hypervisors to query information
1346 @type all_hvparams: dict of dict of strings
1347 @param all_hvparams: a dictionary mapping hypervisor types to respective
1348 cluster-wide hypervisor parameters
1349 @type get_hv_fn: function
1350 @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1351 name; optional parameter to increase testability
1354 @return: a list of all running instances on the current node
1355 - instance1.example.com
1356 - instance2.example.com
1360 for hname in hypervisor_list:
1361 hvparams = all_hvparams[hname]
1362 results.extend(GetInstanceListForHypervisor(hname, hvparams=hvparams,
1363 get_hv_fn=get_hv_fn))
1367 def GetInstanceInfo(instance, hname, hvparams=None):
1368 """Gives back the information about an instance as a dictionary.
1370 @type instance: string
1371 @param instance: the instance name
1373 @param hname: the hypervisor type of the instance
1374 @type hvparams: dict of strings
1375 @param hvparams: the instance's hvparams
1378 @return: dictionary with the following keys:
1379 - memory: memory size of instance (int)
1380 - state: xen state of instance (string)
1381 - time: cpu time of instance (float)
1382 - vcpus: the number of vcpus (int)
1387 iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance,
1389 if iinfo is not None:
1390 output["memory"] = iinfo[2]
1391 output["vcpus"] = iinfo[3]
1392 output["state"] = iinfo[4]
1393 output["time"] = iinfo[5]
1398 def GetInstanceMigratable(instance):
1399 """Computes whether an instance can be migrated.
1401 @type instance: L{objects.Instance}
1402 @param instance: object representing the instance to be checked.
1405 @return: tuple of (result, description) where:
1406 - result: whether the instance can be migrated or not
1407 - description: a description of the issue, if relevant
1410 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1411 iname = instance.name
1412 if iname not in hyper.ListInstances(instance.hvparams):
1413 _Fail("Instance %s is not running", iname)
1415 for idx in range(len(instance.disks)):
1416 link_name = _GetBlockDevSymlinkPath(iname, idx)
1417 if not os.path.islink(link_name):
1418 logging.warning("Instance %s is missing symlink %s for disk %d",
1419 iname, link_name, idx)
1422 def GetAllInstancesInfo(hypervisor_list, all_hvparams):
1423 """Gather data about all instances.
1425 This is the equivalent of L{GetInstanceInfo}, except that it
1426 computes data for all instances at once, thus being faster if one
1427 needs data about more than one instance.
1429 @type hypervisor_list: list
1430 @param hypervisor_list: list of hypervisors to query for instance data
1431 @type all_hvparams: dict of dict of strings
1432 @param all_hvparams: mapping of hypervisor names to hvparams
1435 @return: dictionary of instance: data, with data having the following keys:
1436 - memory: memory size of instance (int)
1437 - state: xen state of instance (string)
1438 - time: cpu time of instance (float)
1439 - vcpus: the number of vcpus
1444 for hname in hypervisor_list:
1445 hvparams = all_hvparams[hname]
1446 iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo(hvparams)
1448 for name, _, memory, vcpus, state, times in iinfo:
1456 # we only check static parameters, like memory and vcpus,
1457 # and not state and time which can change between the
1458 # invocations of the different hypervisors
1459 for key in "memory", "vcpus":
1460 if value[key] != output[name][key]:
1461 _Fail("Instance %s is running twice"
1462 " with different parameters", name)
1463 output[name] = value
1468 def _InstanceLogName(kind, os_name, instance, component):
1469 """Compute the OS log filename for a given instance and operation.
1471 The instance name and os name are passed in as strings since not all
1472 operations have these as part of an instance object.
1475 @param kind: the operation type (e.g. add, import, etc.)
1476 @type os_name: string
1477 @param os_name: the os name
1478 @type instance: string
1479 @param instance: the name of the instance being imported/added/etc.
1480 @type component: string or None
1481 @param component: the name of the component of the instance being
1485 # TODO: Use tempfile.mkstemp to create unique filename
1487 assert "/" not in component
1488 c_msg = "-%s" % component
1491 base = ("%s-%s-%s%s-%s.log" %
1492 (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1493 return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1496 def InstanceOsAdd(instance, reinstall, debug):
1497 """Add an OS to an instance.
1499 @type instance: L{objects.Instance}
1500 @param instance: Instance whose OS is to be installed
1501 @type reinstall: boolean
1502 @param reinstall: whether this is an instance reinstall
1503 @type debug: integer
1504 @param debug: debug level, passed to the OS scripts
1508 inst_os = OSFromDisk(instance.os)
1510 create_env = OSEnvironment(instance, inst_os, debug)
1512 create_env["INSTANCE_REINSTALL"] = "1"
1514 logfile = _InstanceLogName("add", instance.os, instance.name, None)
1516 result = utils.RunCmd([inst_os.create_script], env=create_env,
1517 cwd=inst_os.path, output=logfile, reset_env=True)
1519 logging.error("os create command '%s' returned error: %s, logfile: %s,"
1520 " output: %s", result.cmd, result.fail_reason, logfile,
1522 lines = [utils.SafeEncode(val)
1523 for val in utils.TailFile(logfile, lines=20)]
1524 _Fail("OS create script failed (%s), last lines in the"
1525 " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1528 def RunRenameInstance(instance, old_name, debug):
1529 """Run the OS rename script for an instance.
1531 @type instance: L{objects.Instance}
1532 @param instance: Instance whose OS is to be installed
1533 @type old_name: string
1534 @param old_name: previous instance name
1535 @type debug: integer
1536 @param debug: debug level, passed to the OS scripts
1538 @return: the success of the operation
1541 inst_os = OSFromDisk(instance.os)
1543 rename_env = OSEnvironment(instance, inst_os, debug)
1544 rename_env["OLD_INSTANCE_NAME"] = old_name
1546 logfile = _InstanceLogName("rename", instance.os,
1547 "%s-%s" % (old_name, instance.name), None)
1549 result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1550 cwd=inst_os.path, output=logfile, reset_env=True)
1553 logging.error("os create command '%s' returned error: %s output: %s",
1554 result.cmd, result.fail_reason, result.output)
1555 lines = [utils.SafeEncode(val)
1556 for val in utils.TailFile(logfile, lines=20)]
1557 _Fail("OS rename script failed (%s), last lines in the"
1558 " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1561 def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1562 """Returns symlink path for block device.
1566 _dir = pathutils.DISK_LINKS_DIR
1568 return utils.PathJoin(_dir,
1570 (instance_name, constants.DISK_SEPARATOR, idx)))
1573 def _SymlinkBlockDev(instance_name, device_path, idx):
1574 """Set up symlinks to a instance's block device.
1576 This is an auxiliary function run when an instance is start (on the primary
1577 node) or when an instance is migrated (on the target node).
1580 @param instance_name: the name of the target instance
1581 @param device_path: path of the physical block device, on the node
1582 @param idx: the disk index
1583 @return: absolute path to the disk's symlink
1586 link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1588 os.symlink(device_path, link_name)
1589 except OSError, err:
1590 if err.errno == errno.EEXIST:
1591 if (not os.path.islink(link_name) or
1592 os.readlink(link_name) != device_path):
1593 os.remove(link_name)
1594 os.symlink(device_path, link_name)
1601 def _RemoveBlockDevLinks(instance_name, disks):
1602 """Remove the block device symlinks belonging to the given instance.
1605 for idx, _ in enumerate(disks):
1606 link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1607 if os.path.islink(link_name):
1609 os.remove(link_name)
1611 logging.exception("Can't remove symlink '%s'", link_name)
1614 def _GatherAndLinkBlockDevs(instance):
1615 """Set up an instance's block device(s).
1617 This is run on the primary node at instance startup. The block
1618 devices must be already assembled.
1620 @type instance: L{objects.Instance}
1621 @param instance: the instance whose disks we should assemble
1623 @return: list of (disk_object, device_path)
1627 for idx, disk in enumerate(instance.disks):
1628 device = _RecursiveFindBD(disk)
1630 raise errors.BlockDeviceError("Block device '%s' is not set up." %
1634 link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1636 raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1639 block_devices.append((disk, link_name, device))
1641 return block_devices
1644 def StartInstance(instance, startup_paused, reason, store_reason=True):
1645 """Start an instance.
1647 @type instance: L{objects.Instance}
1648 @param instance: the instance object
1649 @type startup_paused: bool
1650 @param instance: pause instance at startup?
1651 @type reason: list of reasons
1652 @param reason: the reason trail for this startup
1653 @type store_reason: boolean
1654 @param store_reason: whether to store the shutdown reason trail on file
1658 running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1661 if instance.name in running_instances:
1662 logging.info("Instance %s already running, not starting", instance.name)
1666 block_devices = _GatherAndLinkBlockDevs(instance)
1667 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1668 hyper.StartInstance(instance, block_devices, startup_paused)
1670 _StoreInstReasonTrail(instance.name, reason)
1671 except errors.BlockDeviceError, err:
1672 _Fail("Block device error: %s", err, exc=True)
1673 except errors.HypervisorError, err:
1674 _RemoveBlockDevLinks(instance.name, instance.disks)
1675 _Fail("Hypervisor error: %s", err, exc=True)
1678 def InstanceShutdown(instance, timeout, reason, store_reason=True):
1679 """Shut an instance down.
1681 @note: this functions uses polling with a hardcoded timeout.
1683 @type instance: L{objects.Instance}
1684 @param instance: the instance object
1685 @type timeout: integer
1686 @param timeout: maximum timeout for soft shutdown
1687 @type reason: list of reasons
1688 @param reason: the reason trail for this shutdown
1689 @type store_reason: boolean
1690 @param store_reason: whether to store the shutdown reason trail on file
1694 hv_name = instance.hypervisor
1695 hyper = hypervisor.GetHypervisor(hv_name)
1696 iname = instance.name
1698 if instance.name not in hyper.ListInstances(instance.hvparams):
1699 logging.info("Instance %s not running, doing nothing", iname)
1704 self.tried_once = False
1707 if iname not in hyper.ListInstances(instance.hvparams):
1711 hyper.StopInstance(instance, retry=self.tried_once)
1713 _StoreInstReasonTrail(instance.name, reason)
1714 except errors.HypervisorError, err:
1715 if iname not in hyper.ListInstances(instance.hvparams):
1716 # if the instance is no longer existing, consider this a
1717 # success and go to cleanup
1720 _Fail("Failed to stop instance %s: %s", iname, err)
1722 self.tried_once = True
1724 raise utils.RetryAgain()
1727 utils.Retry(_TryShutdown(), 5, timeout)
1728 except utils.RetryTimeout:
1729 # the shutdown did not succeed
1730 logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1733 hyper.StopInstance(instance, force=True)
1734 except errors.HypervisorError, err:
1735 if iname in hyper.ListInstances(instance.hvparams):
1736 # only raise an error if the instance still exists, otherwise
1737 # the error could simply be "instance ... unknown"!
1738 _Fail("Failed to force stop instance %s: %s", iname, err)
1742 if iname in hyper.ListInstances(instance.hvparams):
1743 _Fail("Could not shutdown instance %s even by destroy", iname)
1746 hyper.CleanupInstance(instance.name)
1747 except errors.HypervisorError, err:
1748 logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1750 _RemoveBlockDevLinks(iname, instance.disks)
1753 def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1754 """Reboot an instance.
1756 @type instance: L{objects.Instance}
1757 @param instance: the instance object to reboot
1758 @type reboot_type: str
1759 @param reboot_type: the type of reboot, one the following
1761 - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1762 instance OS, do not recreate the VM
1763 - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1764 restart the VM (at the hypervisor level)
1765 - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1766 not accepted here, since that mode is handled differently, in
1767 cmdlib, and translates into full stop and start of the
1768 instance (instead of a call_instance_reboot RPC)
1769 @type shutdown_timeout: integer
1770 @param shutdown_timeout: maximum timeout for soft shutdown
1771 @type reason: list of reasons
1772 @param reason: the reason trail for this reboot
1776 running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1779 if instance.name not in running_instances:
1780 _Fail("Cannot reboot instance %s that is not running", instance.name)
1782 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1783 if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1785 hyper.RebootInstance(instance)
1786 except errors.HypervisorError, err:
1787 _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1788 elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1790 InstanceShutdown(instance, shutdown_timeout, reason, store_reason=False)
1791 result = StartInstance(instance, False, reason, store_reason=False)
1792 _StoreInstReasonTrail(instance.name, reason)
1794 except errors.HypervisorError, err:
1795 _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1797 _Fail("Invalid reboot_type received: %s", reboot_type)
1800 def InstanceBalloonMemory(instance, memory):
1801 """Resize an instance's memory.
1803 @type instance: L{objects.Instance}
1804 @param instance: the instance object
1806 @param memory: new memory amount in MB
1810 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1811 running = hyper.ListInstances(instance.hvparams)
1812 if instance.name not in running:
1813 logging.info("Instance %s is not running, cannot balloon", instance.name)
1816 hyper.BalloonInstanceMemory(instance, memory)
1817 except errors.HypervisorError, err:
1818 _Fail("Failed to balloon instance memory: %s", err, exc=True)
1821 def MigrationInfo(instance):
1822 """Gather information about an instance to be migrated.
1824 @type instance: L{objects.Instance}
1825 @param instance: the instance definition
1828 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1830 info = hyper.MigrationInfo(instance)
1831 except errors.HypervisorError, err:
1832 _Fail("Failed to fetch migration information: %s", err, exc=True)
1836 def AcceptInstance(instance, info, target):
1837 """Prepare the node to accept an instance.
1839 @type instance: L{objects.Instance}
1840 @param instance: the instance definition
1841 @type info: string/data (opaque)
1842 @param info: migration information, from the source node
1843 @type target: string
1844 @param target: target host (usually ip), on this node
1847 # TODO: why is this required only for DTS_EXT_MIRROR?
1848 if instance.disk_template in constants.DTS_EXT_MIRROR:
1849 # Create the symlinks, as the disks are not active
1852 _GatherAndLinkBlockDevs(instance)
1853 except errors.BlockDeviceError, err:
1854 _Fail("Block device error: %s", err, exc=True)
1856 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1858 hyper.AcceptInstance(instance, info, target)
1859 except errors.HypervisorError, err:
1860 if instance.disk_template in constants.DTS_EXT_MIRROR:
1861 _RemoveBlockDevLinks(instance.name, instance.disks)
1862 _Fail("Failed to accept instance: %s", err, exc=True)
1865 def FinalizeMigrationDst(instance, info, success):
1866 """Finalize any preparation to accept an instance.
1868 @type instance: L{objects.Instance}
1869 @param instance: the instance definition
1870 @type info: string/data (opaque)
1871 @param info: migration information, from the source node
1872 @type success: boolean
1873 @param success: whether the migration was a success or a failure
1876 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1878 hyper.FinalizeMigrationDst(instance, info, success)
1879 except errors.HypervisorError, err:
1880 _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1883 def MigrateInstance(cluster_name, instance, target, live):
1884 """Migrates an instance to another node.
1886 @type cluster_name: string
1887 @param cluster_name: name of the cluster
1888 @type instance: L{objects.Instance}
1889 @param instance: the instance definition
1890 @type target: string
1891 @param target: the target node name
1893 @param live: whether the migration should be done live or not (the
1894 interpretation of this parameter is left to the hypervisor)
1895 @raise RPCFail: if migration fails for some reason
1898 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1901 hyper.MigrateInstance(cluster_name, instance, target, live)
1902 except errors.HypervisorError, err:
1903 _Fail("Failed to migrate instance: %s", err, exc=True)
1906 def FinalizeMigrationSource(instance, success, live):
1907 """Finalize the instance migration on the source node.
1909 @type instance: L{objects.Instance}
1910 @param instance: the instance definition of the migrated instance
1912 @param success: whether the migration succeeded or not
1914 @param live: whether the user requested a live migration or not
1915 @raise RPCFail: If the execution fails for some reason
1918 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1921 hyper.FinalizeMigrationSource(instance, success, live)
1922 except Exception, err: # pylint: disable=W0703
1923 _Fail("Failed to finalize the migration on the source node: %s", err,
1927 def GetMigrationStatus(instance):
1928 """Get the migration status
1930 @type instance: L{objects.Instance}
1931 @param instance: the instance that is being migrated
1932 @rtype: L{objects.MigrationStatus}
1933 @return: the status of the current migration (one of
1934 L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1935 progress info that can be retrieved from the hypervisor
1936 @raise RPCFail: If the migration status cannot be retrieved
1939 hyper = hypervisor.GetHypervisor(instance.hypervisor)
1941 return hyper.GetMigrationStatus(instance)
1942 except Exception, err: # pylint: disable=W0703
1943 _Fail("Failed to get migration status: %s", err, exc=True)
1946 def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
1947 """Creates a block device for an instance.
1949 @type disk: L{objects.Disk}
1950 @param disk: the object describing the disk we should create
1952 @param size: the size of the physical underlying device, in MiB
1954 @param owner: the name of the instance for which disk is created,
1955 used for device cache data
1956 @type on_primary: boolean
1957 @param on_primary: indicates if it is the primary node or not
1959 @param info: string that will be sent to the physical device
1960 creation, used for example to set (LVM) tags on LVs
1961 @type excl_stor: boolean
1962 @param excl_stor: Whether exclusive_storage is active
1964 @return: the new unique_id of the device (this can sometime be
1965 computed only after creation), or None. On secondary nodes,
1966 it's not required to return anything.
1969 # TODO: remove the obsolete "size" argument
1970 # pylint: disable=W0613
1973 for child in disk.children:
1975 crdev = _RecursiveAssembleBD(child, owner, on_primary)
1976 except errors.BlockDeviceError, err:
1977 _Fail("Can't assemble device %s: %s", child, err)
1978 if on_primary or disk.AssembleOnSecondary():
1979 # we need the children open in case the device itself has to
1982 # pylint: disable=E1103
1984 except errors.BlockDeviceError, err:
1985 _Fail("Can't make child '%s' read-write: %s", child, err)
1989 device = bdev.Create(disk, clist, excl_stor)
1990 except errors.BlockDeviceError, err:
1991 _Fail("Can't create block device: %s", err)
1993 if on_primary or disk.AssembleOnSecondary():
1996 except errors.BlockDeviceError, err:
1997 _Fail("Can't assemble device after creation, unusual event: %s", err)
1998 if on_primary or disk.OpenOnSecondary():
2000 device.Open(force=True)
2001 except errors.BlockDeviceError, err:
2002 _Fail("Can't make device r/w after creation, unusual event: %s", err)
2003 DevCacheManager.UpdateCache(device.dev_path, owner,
2004 on_primary, disk.iv_name)
2006 device.SetInfo(info)
2008 return device.unique_id
2011 def _WipeDevice(path, offset, size):
2012 """This function actually wipes the device.
2014 @param path: The path to the device to wipe
2015 @param offset: The offset in MiB in the file
2016 @param size: The size in MiB to write
2019 # Internal sizes are always in Mebibytes; if the following "dd" command
2020 # should use a different block size the offset and size given to this
2021 # function must be adjusted accordingly before being passed to "dd".
2022 block_size = 1024 * 1024
2024 cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
2025 "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
2027 result = utils.RunCmd(cmd)
2030 _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
2031 result.fail_reason, result.output)
2034 def BlockdevWipe(disk, offset, size):
2035 """Wipes a block device.
2037 @type disk: L{objects.Disk}
2038 @param disk: the disk object we want to wipe
2040 @param offset: The offset in MiB in the file
2042 @param size: The size in MiB to write
2046 rdev = _RecursiveFindBD(disk)
2047 except errors.BlockDeviceError:
2051 _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
2053 # Do cross verify some of the parameters
2055 _Fail("Negative offset")
2057 _Fail("Negative size")
2058 if offset > rdev.size:
2059 _Fail("Offset is bigger than device size")
2060 if (offset + size) > rdev.size:
2061 _Fail("The provided offset and size to wipe is bigger than device size")
2063 _WipeDevice(rdev.dev_path, offset, size)
2066 def BlockdevPauseResumeSync(disks, pause):
2067 """Pause or resume the sync of the block device.
2069 @type disks: list of L{objects.Disk}
2070 @param disks: the disks object we want to pause/resume
2072 @param pause: Wheater to pause or resume
2078 rdev = _RecursiveFindBD(disk)
2079 except errors.BlockDeviceError:
2083 success.append((False, ("Cannot change sync for device %s:"
2084 " device not found" % disk.iv_name)))
2087 result = rdev.PauseResumeSync(pause)
2090 success.append((result, None))
2096 success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
2101 def BlockdevRemove(disk):
2102 """Remove a block device.
2104 @note: This is intended to be called recursively.
2106 @type disk: L{objects.Disk}
2107 @param disk: the disk object we should remove
2109 @return: the success of the operation
2114 rdev = _RecursiveFindBD(disk)
2115 except errors.BlockDeviceError, err:
2116 # probably can't attach
2117 logging.info("Can't attach to device %s in remove", disk)
2119 if rdev is not None:
2120 r_path = rdev.dev_path
2123 except errors.BlockDeviceError, err:
2124 msgs.append(str(err))
2126 DevCacheManager.RemoveCache(r_path)
2129 for child in disk.children:
2131 BlockdevRemove(child)
2132 except RPCFail, err:
2133 msgs.append(str(err))
2136 _Fail("; ".join(msgs))
2139 def _RecursiveAssembleBD(disk, owner, as_primary):
2140 """Activate a block device for an instance.
2142 This is run on the primary and secondary nodes for an instance.
2144 @note: this function is called recursively.
2146 @type disk: L{objects.Disk}
2147 @param disk: the disk we try to assemble
2149 @param owner: the name of the instance which owns the disk
2150 @type as_primary: boolean
2151 @param as_primary: if we should make the block device
2154 @return: the assembled device or None (in case no device
2156 @raise errors.BlockDeviceError: in case there is an error
2157 during the activation of the children or the device
2163 mcn = disk.ChildrenNeeded()
2165 mcn = 0 # max number of Nones allowed
2167 mcn = len(disk.children) - mcn # max number of Nones
2168 for chld_disk in disk.children:
2170 cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
2171 except errors.BlockDeviceError, err:
2172 if children.count(None) >= mcn:
2175 logging.error("Error in child activation (but continuing): %s",
2177 children.append(cdev)
2179 if as_primary or disk.AssembleOnSecondary():
2180 r_dev = bdev.Assemble(disk, children)
2182 if as_primary or disk.OpenOnSecondary():
2184 DevCacheManager.UpdateCache(r_dev.dev_path, owner,
2185 as_primary, disk.iv_name)
2192 def BlockdevAssemble(disk, owner, as_primary, idx):
2193 """Activate a block device for an instance.
2195 This is a wrapper over _RecursiveAssembleBD.
2197 @rtype: str or boolean
2198 @return: a C{/dev/...} path for primary nodes, and
2199 C{True} for secondary nodes
2203 result = _RecursiveAssembleBD(disk, owner, as_primary)
2204 if isinstance(result, BlockDev):
2205 # pylint: disable=E1103
2206 result = result.dev_path
2208 _SymlinkBlockDev(owner, result, idx)
2209 except errors.BlockDeviceError, err:
2210 _Fail("Error while assembling disk: %s", err, exc=True)
2211 except OSError, err:
2212 _Fail("Error while symlinking disk: %s", err, exc=True)
2217 def BlockdevShutdown(disk):
2218 """Shut down a block device.
2220 First, if the device is assembled (Attach() is successful), then
2221 the device is shutdown. Then the children of the device are
2224 This function is called recursively. Note that we don't cache the
2225 children or such, as oppossed to assemble, shutdown of different
2226 devices doesn't require that the upper device was active.
2228 @type disk: L{objects.Disk}
2229 @param disk: the description of the disk we should
2235 r_dev = _RecursiveFindBD(disk)
2236 if r_dev is not None:
2237 r_path = r_dev.dev_path
2240 DevCacheManager.RemoveCache(r_path)
2241 except errors.BlockDeviceError, err:
2242 msgs.append(str(err))
2245 for child in disk.children:
2247 BlockdevShutdown(child)
2248 except RPCFail, err:
2249 msgs.append(str(err))
2252 _Fail("; ".join(msgs))
2255 def BlockdevAddchildren(parent_cdev, new_cdevs):
2256 """Extend a mirrored block device.
2258 @type parent_cdev: L{objects.Disk}
2259 @param parent_cdev: the disk to which we should add children
2260 @type new_cdevs: list of L{objects.Disk}
2261 @param new_cdevs: the list of children which we should add
2265 parent_bdev = _RecursiveFindBD(parent_cdev)
2266 if parent_bdev is None:
2267 _Fail("Can't find parent device '%s' in add children", parent_cdev)
2268 new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
2269 if new_bdevs.count(None) > 0:
2270 _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
2271 parent_bdev.AddChildren(new_bdevs)
2274 def BlockdevRemovechildren(parent_cdev, new_cdevs):
2275 """Shrink a mirrored block device.
2277 @type parent_cdev: L{objects.Disk}
2278 @param parent_cdev: the disk from which we should remove children
2279 @type new_cdevs: list of L{objects.Disk}
2280 @param new_cdevs: the list of children which we should remove
2284 parent_bdev = _RecursiveFindBD(parent_cdev)
2285 if parent_bdev is None:
2286 _Fail("Can't find parent device '%s' in remove children", parent_cdev)
2288 for disk in new_cdevs:
2289 rpath = disk.StaticDevPath()
2291 bd = _RecursiveFindBD(disk)
2293 _Fail("Can't find device %s while removing children", disk)
2295 devs.append(bd.dev_path)
2297 if not utils.IsNormAbsPath(rpath):
2298 _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
2300 parent_bdev.RemoveChildren(devs)
2303 def BlockdevGetmirrorstatus(disks):
2304 """Get the mirroring status of a list of devices.
2306 @type disks: list of L{objects.Disk}
2307 @param disks: the list of disks which we should query
2309 @return: List of L{objects.BlockDevStatus}, one for each disk
2310 @raise errors.BlockDeviceError: if any of the disks cannot be
2316 rbd = _RecursiveFindBD(dsk)
2318 _Fail("Can't find device %s", dsk)
2320 stats.append(rbd.CombinedSyncStatus())
2325 def BlockdevGetmirrorstatusMulti(disks):
2326 """Get the mirroring status of a list of devices.
2328 @type disks: list of L{objects.Disk}
2329 @param disks: the list of disks which we should query
2331 @return: List of tuples, (bool, status), one for each disk; bool denotes
2332 success/failure, status is L{objects.BlockDevStatus} on success, string
2339 rbd = _RecursiveFindBD(disk)
2341 result.append((False, "Can't find device %s" % disk))
2344 status = rbd.CombinedSyncStatus()
2345 except errors.BlockDeviceError, err:
2346 logging.exception("Error while getting disk status")
2347 result.append((False, str(err)))
2349 result.append((True, status))
2351 assert len(disks) == len(result)
2356 def _RecursiveFindBD(disk):
2357 """Check if a device is activated.
2359 If so, return information about the real device.
2361 @type disk: L{objects.Disk}
2362 @param disk: the disk object we need to find
2364 @return: None if the device can't be found,
2365 otherwise the device instance
2370 for chdisk in disk.children:
2371 children.append(_RecursiveFindBD(chdisk))
2373 return bdev.FindDevice(disk, children)
2376 def _OpenRealBD(disk):
2377 """Opens the underlying block device of a disk.
2379 @type disk: L{objects.Disk}
2380 @param disk: the disk object we want to open
2383 real_disk = _RecursiveFindBD(disk)
2384 if real_disk is None:
2385 _Fail("Block device '%s' is not set up", disk)
2392 def BlockdevFind(disk):
2393 """Check if a device is activated.
2395 If it is, return information about the real device.
2397 @type disk: L{objects.Disk}
2398 @param disk: the disk to find
2399 @rtype: None or objects.BlockDevStatus
2400 @return: None if the disk cannot be found, otherwise a the current
2405 rbd = _RecursiveFindBD(disk)
2406 except errors.BlockDeviceError, err:
2407 _Fail("Failed to find device: %s", err, exc=True)
2412 return rbd.GetSyncStatus()
2415 def BlockdevGetdimensions(disks):
2416 """Computes the size of the given disks.
2418 If a disk is not found, returns None instead.
2420 @type disks: list of L{objects.Disk}
2421 @param disks: the list of disk to compute the size for
2423 @return: list with elements None if the disk cannot be found,
2424 otherwise the pair (size, spindles), where spindles is None if the
2425 device doesn't support that
2431 rbd = _RecursiveFindBD(cf)
2432 except errors.BlockDeviceError:
2438 result.append(rbd.GetActualDimensions())
2442 def BlockdevExport(disk, dest_node_ip, dest_path, cluster_name):
2443 """Export a block device to a remote node.
2445 @type disk: L{objects.Disk}
2446 @param disk: the description of the disk to export
2447 @type dest_node_ip: str
2448 @param dest_node_ip: the destination node IP to export to
2449 @type dest_path: str
2450 @param dest_path: the destination path on the target node
2451 @type cluster_name: str
2452 @param cluster_name: the cluster name, needed for SSH hostalias
2456 real_disk = _OpenRealBD(disk)
2458 # the block size on the read dd is 1MiB to match our units
2459 expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2460 "dd if=%s bs=1048576 count=%s",
2461 real_disk.dev_path, str(disk.size))
2463 # we set here a smaller block size as, due to ssh buffering, more
2464 # than 64-128k will mostly ignored; we use nocreat to fail if the
2465 # device is not already there or we pass a wrong path; we use
2466 # notrunc to no attempt truncate on an LV device; we use oflag=dsync
2467 # to not buffer too much memory; this means that at best, we flush
2468 # every 64k, which will not be very fast
2469 destcmd = utils.BuildShellCmd("dd of=%s conv=nocreat,notrunc bs=65536"
2470 " oflag=dsync", dest_path)
2472 remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node_ip,
2473 constants.SSH_LOGIN_USER,
2476 # all commands have been checked, so we're safe to combine them
2477 command = "|".join([expcmd, utils.ShellQuoteArgs(remotecmd)])
2479 result = utils.RunCmd(["bash", "-c", command])
2482 _Fail("Disk copy command '%s' returned error: %s"
2483 " output: %s", command, result.fail_reason, result.output)
2486 def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2487 """Write a file to the filesystem.
2489 This allows the master to overwrite(!) a file. It will only perform
2490 the operation if the file belongs to a list of configuration files.
2492 @type file_name: str
2493 @param file_name: the target file name
2495 @param data: the new contents of the file
2497 @param mode: the mode to give the file (can be None)
2499 @param uid: the owner of the file
2501 @param gid: the group of the file
2503 @param atime: the atime to set on the file (can be None)
2505 @param mtime: the mtime to set on the file (can be None)
2509 file_name = vcluster.LocalizeVirtualPath(file_name)
2511 if not os.path.isabs(file_name):
2512 _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2514 if file_name not in _ALLOWED_UPLOAD_FILES:
2515 _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2518 raw_data = _Decompress(data)
2520 if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2521 _Fail("Invalid username/groupname type")
2523 getents = runtime.GetEnts()
2524 uid = getents.LookupUser(uid)
2525 gid = getents.LookupGroup(gid)
2527 utils.SafeWriteFile(file_name, None,
2528 data=raw_data, mode=mode, uid=uid, gid=gid,
2529 atime=atime, mtime=mtime)
2532 def RunOob(oob_program, command, node, timeout):
2533 """Executes oob_program with given command on given node.
2535 @param oob_program: The path to the executable oob_program
2536 @param command: The command to invoke on oob_program
2537 @param node: The node given as an argument to the program
2538 @param timeout: Timeout after which we kill the oob program
2541 @raise RPCFail: If execution fails for some reason
2544 result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2547 _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2548 result.fail_reason, result.output)
2550 return result.stdout
2553 def _OSOndiskAPIVersion(os_dir):
2554 """Compute and return the API version of a given OS.
2556 This function will try to read the API version of the OS residing in
2557 the 'os_dir' directory.
2560 @param os_dir: the directory in which we should look for the OS
2562 @return: tuple (status, data) with status denoting the validity and
2563 data holding either the vaid versions or an error message
2566 api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2569 st = os.stat(api_file)
2570 except EnvironmentError, err:
2571 return False, ("Required file '%s' not found under path %s: %s" %
2572 (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2574 if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2575 return False, ("File '%s' in %s is not a regular file" %
2576 (constants.OS_API_FILE, os_dir))
2579 api_versions = utils.ReadFile(api_file).splitlines()
2580 except EnvironmentError, err:
2581 return False, ("Error while reading the API version file at %s: %s" %
2582 (api_file, utils.ErrnoOrStr(err)))
2585 api_versions = [int(version.strip()) for version in api_versions]
2586 except (TypeError, ValueError), err:
2587 return False, ("API version(s) can't be converted to integer: %s" %
2590 return True, api_versions
2593 def DiagnoseOS(top_dirs=None):
2594 """Compute the validity for all OSes.
2596 @type top_dirs: list
2597 @param top_dirs: the list of directories in which to
2598 search (if not given defaults to
2599 L{pathutils.OS_SEARCH_PATH})
2600 @rtype: list of L{objects.OS}
2601 @return: a list of tuples (name, path, status, diagnose, variants,
2602 parameters, api_version) for all (potential) OSes under all
2603 search paths, where:
2604 - name is the (potential) OS name
2605 - path is the full path to the OS
2606 - status True/False is the validity of the OS
2607 - diagnose is the error message for an invalid OS, otherwise empty
2608 - variants is a list of supported OS variants, if any
2609 - parameters is a list of (name, help) parameters, if any
2610 - api_version is a list of support OS API versions
2613 if top_dirs is None:
2614 top_dirs = pathutils.OS_SEARCH_PATH
2617 for dir_name in top_dirs:
2618 if os.path.isdir(dir_name):
2620 f_names = utils.ListVisibleFiles(dir_name)
2621 except EnvironmentError, err:
2622 logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2624 for name in f_names:
2625 os_path = utils.PathJoin(dir_name, name)
2626 status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2629 variants = os_inst.supported_variants
2630 parameters = os_inst.supported_parameters
2631 api_versions = os_inst.api_versions
2634 variants = parameters = api_versions = []
2635 result.append((name, os_path, status, diagnose, variants,
2636 parameters, api_versions))
2641 def _TryOSFromDisk(name, base_dir=None):
2642 """Create an OS instance from disk.
2644 This function will return an OS instance if the given name is a
2647 @type base_dir: string
2648 @keyword base_dir: Base directory containing OS installations.
2649 Defaults to a search in all the OS_SEARCH_PATH dirs.
2651 @return: success and either the OS instance if we find a valid one,
2655 if base_dir is None:
2656 os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2658 os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2661 return False, "Directory for OS %s not found in search path" % name
2663 status, api_versions = _OSOndiskAPIVersion(os_dir)
2666 return status, api_versions
2668 if not constants.OS_API_VERSIONS.intersection(api_versions):
2669 return False, ("API version mismatch for path '%s': found %s, want %s." %
2670 (os_dir, api_versions, constants.OS_API_VERSIONS))
2672 # OS Files dictionary, we will populate it with the absolute path
2673 # names; if the value is True, then it is a required file, otherwise
2675 os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2677 if max(api_versions) >= constants.OS_API_V15:
2678 os_files[constants.OS_VARIANTS_FILE] = False
2680 if max(api_versions) >= constants.OS_API_V20:
2681 os_files[constants.OS_PARAMETERS_FILE] = True
2683 del os_files[constants.OS_SCRIPT_VERIFY]
2685 for (filename, required) in os_files.items():
2686 os_files[filename] = utils.PathJoin(os_dir, filename)
2689 st = os.stat(os_files[filename])
2690 except EnvironmentError, err:
2691 if err.errno == errno.ENOENT and not required:
2692 del os_files[filename]
2694 return False, ("File '%s' under path '%s' is missing (%s)" %
2695 (filename, os_dir, utils.ErrnoOrStr(err)))
2697 if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2698 return False, ("File '%s' under path '%s' is not a regular file" %
2701 if filename in constants.OS_SCRIPTS:
2702 if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2703 return False, ("File '%s' under path '%s' is not executable" %
2707 if constants.OS_VARIANTS_FILE in os_files:
2708 variants_file = os_files[constants.OS_VARIANTS_FILE]
2711 utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2712 except EnvironmentError, err:
2713 # we accept missing files, but not other errors
2714 if err.errno != errno.ENOENT:
2715 return False, ("Error while reading the OS variants file at %s: %s" %
2716 (variants_file, utils.ErrnoOrStr(err)))
2719 if constants.OS_PARAMETERS_FILE in os_files:
2720 parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2722 parameters = utils.ReadFile(parameters_file).splitlines()
2723 except EnvironmentError, err:
2724 return False, ("Error while reading the OS parameters file at %s: %s" %
2725 (parameters_file, utils.ErrnoOrStr(err)))
2726 parameters = [v.split(None, 1) for v in parameters]
2728 os_obj = objects.OS(name=name, path=os_dir,
2729 create_script=os_files[constants.OS_SCRIPT_CREATE],
2730 export_script=os_files[constants.OS_SCRIPT_EXPORT],
2731 import_script=os_files[constants.OS_SCRIPT_IMPORT],
2732 rename_script=os_files[constants.OS_SCRIPT_RENAME],
2733 verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2735 supported_variants=variants,
2736 supported_parameters=parameters,
2737 api_versions=api_versions)
2741 def OSFromDisk(name, base_dir=None):
2742 """Create an OS instance from disk.
2744 This function will return an OS instance if the given name is a
2745 valid OS name. Otherwise, it will raise an appropriate
2746 L{RPCFail} exception, detailing why this is not a valid OS.
2748 This is just a wrapper over L{_TryOSFromDisk}, which doesn't raise
2749 an exception but returns true/false status data.
2751 @type base_dir: string
2752 @keyword base_dir: Base directory containing OS installations.
2753 Defaults to a search in all the OS_SEARCH_PATH dirs.
2754 @rtype: L{objects.OS}
2755 @return: the OS instance if we find a valid one
2756 @raise RPCFail: if we don't find a valid OS
2759 name_only = objects.OS.GetName(name)
2760 status, payload = _TryOSFromDisk(name_only, base_dir)
2768 def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2769 """Calculate the basic environment for an os script.
2772 @param os_name: full operating system name (including variant)
2773 @type inst_os: L{objects.OS}
2774 @param inst_os: operating system for which the environment is being built
2775 @type os_params: dict
2776 @param os_params: the OS parameters
2777 @type debug: integer
2778 @param debug: debug level (0 or 1, for OS Api 10)
2780 @return: dict of environment variables
2781 @raise errors.BlockDeviceError: if the block device
2787 max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2788 result["OS_API_VERSION"] = "%d" % api_version
2789 result["OS_NAME"] = inst_os.name
2790 result["DEBUG_LEVEL"] = "%d" % debug
2793 if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2794 variant = objects.OS.GetVariant(os_name)
2796 variant = inst_os.supported_variants[0]
2799 result["OS_VARIANT"] = variant
2802 for pname, pvalue in os_params.items():
2803 result["OSP_%s" % pname.upper()] = pvalue
2805 # Set a default path otherwise programs called by OS scripts (or
2806 # even hooks called from OS scripts) might break, and we don't want
2807 # to have each script require setting a PATH variable
2808 result["PATH"] = constants.HOOKS_PATH
2813 def OSEnvironment(instance, inst_os, debug=0):
2814 """Calculate the environment for an os script.
2816 @type instance: L{objects.Instance}
2817 @param instance: target instance for the os script run
2818 @type inst_os: L{objects.OS}
2819 @param inst_os: operating system for which the environment is being built
2820 @type debug: integer
2821 @param debug: debug level (0 or 1, for OS Api 10)
2823 @return: dict of environment variables
2824 @raise errors.BlockDeviceError: if the block device
2828 result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2830 for attr in ["name", "os", "uuid", "ctime", "mtime", "primary_node"]:
2831 result["INSTANCE_%s" % attr.upper()] = str(getattr(instance, attr))
2833 result["HYPERVISOR"] = instance.hypervisor
2834 result["DISK_COUNT"] = "%d" % len(instance.disks)
2835 result["NIC_COUNT"] = "%d" % len(instance.nics)
2836 result["INSTANCE_SECONDARY_NODES"] = \
2837 ("%s" % " ".join(instance.secondary_nodes))
2840 for idx, disk in enumerate(instance.disks):
2841 real_disk = _OpenRealBD(disk)
2842 result["DISK_%d_PATH" % idx] = real_disk.dev_path
2843 result["DISK_%d_ACCESS" % idx] = disk.mode
2844 result["DISK_%d_UUID" % idx] = disk.uuid
2846 result["DISK_%d_NAME" % idx] = disk.name
2847 if constants.HV_DISK_TYPE in instance.hvparams:
2848 result["DISK_%d_FRONTEND_TYPE" % idx] = \
2849 instance.hvparams[constants.HV_DISK_TYPE]
2850 if disk.dev_type in constants.DTS_BLOCK:
2851 result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2852 elif disk.dev_type in [constants.DT_FILE, constants.DT_SHARED_FILE]:
2853 result["DISK_%d_BACKEND_TYPE" % idx] = \
2854 "file:%s" % disk.logical_id[0]
2857 for idx, nic in enumerate(instance.nics):
2858 result["NIC_%d_MAC" % idx] = nic.mac
2859 result["NIC_%d_UUID" % idx] = nic.uuid
2861 result["NIC_%d_NAME" % idx] = nic.name
2863 result["NIC_%d_IP" % idx] = nic.ip
2864 result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2865 if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2866 result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2867 if nic.nicparams[constants.NIC_LINK]:
2868 result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2870 nobj = objects.Network.FromDict(nic.netinfo)
2871 result.update(nobj.HooksDict("NIC_%d_" % idx))
2872 if constants.HV_NIC_TYPE in instance.hvparams:
2873 result["NIC_%d_FRONTEND_TYPE" % idx] = \
2874 instance.hvparams[constants.HV_NIC_TYPE]
2877 for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2878 for key, value in source.items():
2879 result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2884 def DiagnoseExtStorage(top_dirs=None):
2885 """Compute the validity for all ExtStorage Providers.
2887 @type top_dirs: list
2888 @param top_dirs: the list of directories in which to
2889 search (if not given defaults to
2890 L{pathutils.ES_SEARCH_PATH})
2891 @rtype: list of L{objects.ExtStorage}
2892 @return: a list of tuples (name, path, status, diagnose, parameters)
2893 for all (potential) ExtStorage Providers under all
2894 search paths, where:
2895 - name is the (potential) ExtStorage Provider
2896 - path is the full path to the ExtStorage Provider
2897 - status True/False is the validity of the ExtStorage Provider
2898 - diagnose is the error message for an invalid ExtStorage Provider,
2900 - parameters is a list of (name, help) parameters, if any
2903 if top_dirs is None:
2904 top_dirs = pathutils.ES_SEARCH_PATH
2907 for dir_name in top_dirs:
2908 if os.path.isdir(dir_name):
2910 f_names = utils.ListVisibleFiles(dir_name)
2911 except EnvironmentError, err:
2912 logging.exception("Can't list the ExtStorage directory %s: %s",
2915 for name in f_names:
2916 es_path = utils.PathJoin(dir_name, name)
2917 status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2920 parameters = es_inst.supported_parameters
2924 result.append((name, es_path, status, diagnose, parameters))
2929 def BlockdevGrow(disk, amount, dryrun, backingstore, excl_stor):
2930 """Grow a stack of block devices.
2932 This function is called recursively, with the childrens being the
2933 first ones to resize.
2935 @type disk: L{objects.Disk}
2936 @param disk: the disk to be grown
2937 @type amount: integer
2938 @param amount: the amount (in mebibytes) to grow with
2939 @type dryrun: boolean
2940 @param dryrun: whether to execute the operation in simulation mode
2941 only, without actually increasing the size
2942 @param backingstore: whether to execute the operation on backing storage
2943 only, or on "logical" storage only; e.g. DRBD is logical storage,
2944 whereas LVM, file, RBD are backing storage
2945 @rtype: (status, result)
2946 @type excl_stor: boolean
2947 @param excl_stor: Whether exclusive_storage is active
2948 @return: a tuple with the status of the operation (True/False), and
2949 the errors message if status is False
2952 r_dev = _RecursiveFindBD(disk)
2954 _Fail("Cannot find block device %s", disk)
2957 r_dev.Grow(amount, dryrun, backingstore, excl_stor)
2958 except errors.BlockDeviceError, err:
2959 _Fail("Failed to grow block device: %s", err, exc=True)
2962 def BlockdevSnapshot(disk):
2963 """Create a snapshot copy of a block device.
2965 This function is called recursively, and the snapshot is actually created
2966 just for the leaf lvm backend device.
2968 @type disk: L{objects.Disk}
2969 @param disk: the disk to be snapshotted
2971 @return: snapshot disk ID as (vg, lv)
2974 if disk.dev_type == constants.DT_DRBD8:
2975 if not disk.children:
2976 _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2978 return BlockdevSnapshot(disk.children[0])
2979 elif disk.dev_type == constants.DT_PLAIN:
2980 r_dev = _RecursiveFindBD(disk)
2981 if r_dev is not None:
2982 # FIXME: choose a saner value for the snapshot size
2983 # let's stay on the safe side and ask for the full size, for now
2984 return r_dev.Snapshot(disk.size)
2986 _Fail("Cannot find block device %s", disk)
2988 _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2989 disk.unique_id, disk.dev_type)
2992 def BlockdevSetInfo(disk, info):
2993 """Sets 'metadata' information on block devices.
2995 This function sets 'info' metadata on block devices. Initial
2996 information is set at device creation; this function should be used
2997 for example after renames.
2999 @type disk: L{objects.Disk}
3000 @param disk: the disk to be grown
3002 @param info: new 'info' metadata
3003 @rtype: (status, result)
3004 @return: a tuple with the status of the operation (True/False), and
3005 the errors message if status is False
3008 r_dev = _RecursiveFindBD(disk)
3010 _Fail("Cannot find block device %s", disk)
3014 except errors.BlockDeviceError, err:
3015 _Fail("Failed to set information on block device: %s", err, exc=True)
3018 def FinalizeExport(instance, snap_disks):
3019 """Write out the export configuration information.
3021 @type instance: L{objects.Instance}
3022 @param instance: the instance which we export, used for
3023 saving configuration
3024 @type snap_disks: list of L{objects.Disk}
3025 @param snap_disks: list of snapshot block devices, which
3026 will be used to get the actual name of the dump file
3031 destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
3032 finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
3034 config = objects.SerializableConfigParser()
3036 config.add_section(constants.INISECT_EXP)
3037 config.set(constants.INISECT_EXP, "version", "0")
3038 config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
3039 config.set(constants.INISECT_EXP, "source", instance.primary_node)
3040 config.set(constants.INISECT_EXP, "os", instance.os)
3041 config.set(constants.INISECT_EXP, "compression", "none")
3043 config.add_section(constants.INISECT_INS)
3044 config.set(constants.INISECT_INS, "name", instance.name)
3045 config.set(constants.INISECT_INS, "maxmem", "%d" %
3046 instance.beparams[constants.BE_MAXMEM])
3047 config.set(constants.INISECT_INS, "minmem", "%d" %
3048 instance.beparams[constants.BE_MINMEM])
3049 # "memory" is deprecated, but useful for exporting to old ganeti versions
3050 config.set(constants.INISECT_INS, "memory", "%d" %
3051 instance.beparams[constants.BE_MAXMEM])
3052 config.set(constants.INISECT_INS, "vcpus", "%d" %
3053 instance.beparams[constants.BE_VCPUS])
3054 config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
3055 config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
3056 config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
3059 for nic_count, nic in enumerate(instance.nics):
3061 config.set(constants.INISECT_INS, "nic%d_mac" %
3062 nic_count, "%s" % nic.mac)
3063 config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
3064 config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
3066 for param in constants.NICS_PARAMETER_TYPES:
3067 config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
3068 "%s" % nic.nicparams.get(param, None))
3069 # TODO: redundant: on load can read nics until it doesn't exist
3070 config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
3073 for disk_count, disk in enumerate(snap_disks):
3076 config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
3077 ("%s" % disk.iv_name))
3078 config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
3079 ("%s" % disk.logical_id[1]))
3080 config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
3083 config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
3085 # New-style hypervisor/backend parameters
3087 config.add_section(constants.INISECT_HYP)
3088 for name, value in instance.hvparams.items():
3089 if name not in constants.HVC_GLOBALS:
3090 config.set(constants.INISECT_HYP, name, str(value))
3092 config.add_section(constants.INISECT_BEP)
3093 for name, value in instance.beparams.items():
3094 config.set(constants.INISECT_BEP, name, str(value))
3096 config.add_section(constants.INISECT_OSP)
3097 for name, value in instance.osparams.items():
3098 config.set(constants.INISECT_OSP, name, str(value))
3100 utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
3101 data=config.Dumps())
3102 shutil.rmtree(finaldestdir, ignore_errors=True)
3103 shutil.move(destdir, finaldestdir)
3106 def ExportInfo(dest):
3107 """Get export configuration information.
3110 @param dest: directory containing the export
3112 @rtype: L{objects.SerializableConfigParser}
3113 @return: a serializable config file containing the
3117 cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
3119 config = objects.SerializableConfigParser()
3122 if (not config.has_section(constants.INISECT_EXP) or
3123 not config.has_section(constants.INISECT_INS)):
3124 _Fail("Export info file doesn't have the required fields")
3126 return config.Dumps()
3130 """Return a list of exports currently available on this machine.
3133 @return: list of the exports
3136 if os.path.isdir(pathutils.EXPORT_DIR):
3137 return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
3139 _Fail("No exports directory")
3142 def RemoveExport(export):
3143 """Remove an existing export from the node.
3146 @param export: the name of the export to remove
3150 target = utils.PathJoin(pathutils.EXPORT_DIR, export)
3153 shutil.rmtree(target)
3154 except EnvironmentError, err:
3155 _Fail("Error while removing the export: %s", err, exc=True)
3158 def BlockdevRename(devlist):
3159 """Rename a list of block devices.
3161 @type devlist: list of tuples
3162 @param devlist: list of tuples of the form (disk, new_unique_id); disk is
3163 an L{objects.Disk} object describing the current disk, and new
3164 unique_id is the name we rename it to
3166 @return: True if all renames succeeded, False otherwise
3171 for disk, unique_id in devlist:
3172 dev = _RecursiveFindBD(disk)
3174 msgs.append("Can't find device %s in rename" % str(disk))
3178 old_rpath = dev.dev_path
3179 dev.Rename(unique_id)
3180 new_rpath = dev.dev_path
3181 if old_rpath != new_rpath:
3182 DevCacheManager.RemoveCache(old_rpath)
3183 # FIXME: we should add the new cache information here, like:
3184 # DevCacheManager.UpdateCache(new_rpath, owner, ...)
3185 # but we don't have the owner here - maybe parse from existing
3186 # cache? for now, we only lose lvm data when we rename, which
3187 # is less critical than DRBD or MD
3188 except errors.BlockDeviceError, err:
3189 msgs.append("Can't rename device '%s' to '%s': %s" %
3190 (dev, unique_id, err))
3191 logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
3194 _Fail("; ".join(msgs))
3197 def _TransformFileStorageDir(fs_dir):
3198 """Checks whether given file_storage_dir is valid.
3200 Checks wheter the given fs_dir is within the cluster-wide default
3201 file_storage_dir or the shared_file_storage_dir, which are stored in
3202 SimpleStore. Only paths under those directories are allowed.
3205 @param fs_dir: the path to check
3207 @return: the normalized path if valid, None otherwise
3210 filestorage.CheckFileStoragePath(fs_dir)
3212 return os.path.normpath(fs_dir)
3215 def CreateFileStorageDir(file_storage_dir):
3216 """Create file storage directory.
3218 @type file_storage_dir: str
3219 @param file_storage_dir: directory to create
3222 @return: tuple with first element a boolean indicating wheter dir
3223 creation was successful or not
3226 file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3227 if os.path.exists(file_storage_dir):
3228 if not os.path.isdir(file_storage_dir):
3229 _Fail("Specified storage dir '%s' is not a directory",
3233 os.makedirs(file_storage_dir, 0750)
3234 except OSError, err:
3235 _Fail("Cannot create file storage directory '%s': %s",
3236 file_storage_dir, err, exc=True)
3239 def RemoveFileStorageDir(file_storage_dir):
3240 """Remove file storage directory.
3242 Remove it only if it's empty. If not log an error and return.
3244 @type file_storage_dir: str
3245 @param file_storage_dir: the directory we should cleanup
3246 @rtype: tuple (success,)
3247 @return: tuple of one element, C{success}, denoting
3248 whether the operation was successful
3251 file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3252 if os.path.exists(file_storage_dir):
3253 if not os.path.isdir(file_storage_dir):
3254 _Fail("Specified Storage directory '%s' is not a directory",
3256 # deletes dir only if empty, otherwise we want to fail the rpc call
3258 os.rmdir(file_storage_dir)
3259 except OSError, err:
3260 _Fail("Cannot remove file storage directory '%s': %s",
3261 file_storage_dir, err)
3264 def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
3265 """Rename the file storage directory.
3267 @type old_file_storage_dir: str
3268 @param old_file_storage_dir: the current path
3269 @type new_file_storage_dir: str
3270 @param new_file_storage_dir: the name we should rename to
3271 @rtype: tuple (success,)
3272 @return: tuple of one element, C{success}, denoting
3273 whether the operation was successful
3276 old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
3277 new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
3278 if not os.path.exists(new_file_storage_dir):
3279 if os.path.isdir(old_file_storage_dir):
3281 os.rename(old_file_storage_dir, new_file_storage_dir)
3282 except OSError, err:
3283 _Fail("Cannot rename '%s' to '%s': %s",
3284 old_file_storage_dir, new_file_storage_dir, err)
3286 _Fail("Specified storage dir '%s' is not a directory",
3287 old_file_storage_dir)
3289 if os.path.exists(old_file_storage_dir):
3290 _Fail("Cannot rename '%s' to '%s': both locations exist",
3291 old_file_storage_dir, new_file_storage_dir)
3294 def _EnsureJobQueueFile(file_name):
3295 """Checks whether the given filename is in the queue directory.
3297 @type file_name: str
3298 @param file_name: the file name we should check
3300 @raises RPCFail: if the file is not valid
3303 if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
3304 _Fail("Passed job queue file '%s' does not belong to"
3305 " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
3308 def JobQueueUpdate(file_name, content):
3309 """Updates a file in the queue directory.
3311 This is just a wrapper over L{utils.io.WriteFile}, with proper
3314 @type file_name: str
3315 @param file_name: the job file name
3317 @param content: the new job contents
3319 @return: the success of the operation
3322 file_name = vcluster.LocalizeVirtualPath(file_name)
3324 _EnsureJobQueueFile(file_name)
3325 getents = runtime.GetEnts()
3327 # Write and replace the file atomically
3328 utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3329 gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3332 def JobQueueRename(old, new):
3333 """Renames a job queue file.
3335 This is just a wrapper over os.rename with proper checking.
3338 @param old: the old (actual) file name
3340 @param new: the desired file name
3342 @return: the success of the operation and payload
3345 old = vcluster.LocalizeVirtualPath(old)
3346 new = vcluster.LocalizeVirtualPath(new)
3348 _EnsureJobQueueFile(old)
3349 _EnsureJobQueueFile(new)
3351 getents = runtime.GetEnts()
3353 utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3354 dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3357 def BlockdevClose(instance_name, disks):
3358 """Closes the given block devices.
3360 This means they will be switched to secondary mode (in case of
3363 @param instance_name: if the argument is not empty, the symlinks
3364 of this instance will be removed
3365 @type disks: list of L{objects.Disk}
3366 @param disks: the list of disks to be closed
3367 @rtype: tuple (success, message)
3368 @return: a tuple of success and message, where success
3369 indicates the succes of the operation, and message
3370 which will contain the error details in case we
3376 rd = _RecursiveFindBD(cf)
3378 _Fail("Can't find device %s", cf)
3385 except errors.BlockDeviceError, err:
3386 msg.append(str(err))
3388 _Fail("Can't make devices secondary: %s", ",".join(msg))
3391 _RemoveBlockDevLinks(instance_name, disks)
3394 def ValidateHVParams(hvname, hvparams):
3395 """Validates the given hypervisor parameters.
3397 @type hvname: string
3398 @param hvname: the hypervisor name
3399 @type hvparams: dict
3400 @param hvparams: the hypervisor parameters to be validated
3405 hv_type = hypervisor.GetHypervisor(hvname)
3406 hv_type.ValidateParameters(hvparams)
3407 except errors.HypervisorError, err:
3408 _Fail(str(err), log=False)
3411 def _CheckOSPList(os_obj, parameters):
3412 """Check whether a list of parameters is supported by the OS.
3414 @type os_obj: L{objects.OS}
3415 @param os_obj: OS object to check
3416 @type parameters: list
3417 @param parameters: the list of parameters to check
3420 supported = [v[0] for v in os_obj.supported_parameters]
3421 delta = frozenset(parameters).difference(supported)
3423 _Fail("The following parameters are not supported"
3424 " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3427 def ValidateOS(required, osname, checks, osparams):
3428 """Validate the given OS' parameters.
3430 @type required: boolean
3431 @param required: whether absence of the OS should translate into
3433 @type osname: string
3434 @param osname: the OS to be validated
3436 @param checks: list of the checks to run (currently only 'parameters')
3437 @type osparams: dict
3438 @param osparams: dictionary with OS parameters
3440 @return: True if the validation passed, or False if the OS was not
3441 found and L{required} was false
3444 if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3445 _Fail("Unknown checks required for OS %s: %s", osname,
3446 set(checks).difference(constants.OS_VALIDATE_CALLS))
3448 name_only = objects.OS.GetName(osname)
3449 status, tbv = _TryOSFromDisk(name_only, None)
3457 if max(tbv.api_versions) < constants.OS_API_V20:
3460 if constants.OS_VALIDATE_PARAMETERS in checks:
3461 _CheckOSPList(tbv, osparams.keys())
3463 validate_env = OSCoreEnv(osname, tbv, osparams)
3464 result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3465 cwd=tbv.path, reset_env=True)
3467 logging.error("os validate command '%s' returned error: %s output: %s",
3468 result.cmd, result.fail_reason, result.output)
3469 _Fail("OS validation script failed (%s), output: %s",
3470 result.fail_reason, result.output, log=False)
3476 """Demotes the current node from master candidate role.
3479 # try to ensure we're not the master by mistake
3480 master, myself = ssconf.GetMasterAndMyself()
3481 if master == myself:
3482 _Fail("ssconf status shows I'm the master node, will not demote")
3484 result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3485 if not result.failed:
3486 _Fail("The master daemon is running, will not demote")
3489 if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3490 utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3491 except EnvironmentError, err:
3492 if err.errno != errno.ENOENT:
3493 _Fail("Error while backing up cluster file: %s", err, exc=True)
3495 utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3498 def _GetX509Filenames(cryptodir, name):
3499 """Returns the full paths for the private key and certificate.
3502 return (utils.PathJoin(cryptodir, name),
3503 utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3504 utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3507 def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3508 """Creates a new X509 certificate for SSL/TLS.
3511 @param validity: Validity in seconds
3512 @rtype: tuple; (string, string)
3513 @return: Certificate name and public part
3516 (key_pem, cert_pem) = \
3517 utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3518 min(validity, _MAX_SSL_CERT_VALIDITY))
3520 cert_dir = tempfile.mkdtemp(dir=cryptodir,
3521 prefix="x509-%s-" % utils.TimestampForFilename())
3523 name = os.path.basename(cert_dir)
3524 assert len(name) > 5
3526 (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3528 utils.WriteFile(key_file, mode=0400, data=key_pem)
3529 utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3531 # Never return private key as it shouldn't leave the node
3532 return (name, cert_pem)
3534 shutil.rmtree(cert_dir, ignore_errors=True)
3538 def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3539 """Removes a X509 certificate.
3542 @param name: Certificate name
3545 (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3547 utils.RemoveFile(key_file)
3548 utils.RemoveFile(cert_file)
3552 except EnvironmentError, err:
3553 _Fail("Cannot remove certificate directory '%s': %s",
3557 def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3558 """Returns the command for the requested input/output.
3560 @type instance: L{objects.Instance}
3561 @param instance: The instance object
3562 @param mode: Import/export mode
3563 @param ieio: Input/output type
3564 @param ieargs: Input/output arguments
3567 assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3574 if ieio == constants.IEIO_FILE:
3575 (filename, ) = ieargs
3577 if not utils.IsNormAbsPath(filename):
3578 _Fail("Path '%s' is not normalized or absolute", filename)
3580 real_filename = os.path.realpath(filename)
3581 directory = os.path.dirname(real_filename)
3583 if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3584 _Fail("File '%s' is not under exports directory '%s': %s",
3585 filename, pathutils.EXPORT_DIR, real_filename)
3588 utils.Makedirs(directory, mode=0750)
3590 quoted_filename = utils.ShellQuote(filename)
3592 if mode == constants.IEM_IMPORT:
3593 suffix = "> %s" % quoted_filename
3594 elif mode == constants.IEM_EXPORT:
3595 suffix = "< %s" % quoted_filename
3597 # Retrieve file size
3599 st = os.stat(filename)
3600 except EnvironmentError, err:
3601 logging.error("Can't stat(2) %s: %s", filename, err)
3603 exp_size = utils.BytesToMebibyte(st.st_size)
3605 elif ieio == constants.IEIO_RAW_DISK:
3608 real_disk = _OpenRealBD(disk)
3610 if mode == constants.IEM_IMPORT:
3611 # we set here a smaller block size as, due to transport buffering, more
3612 # than 64-128k will mostly ignored; we use nocreat to fail if the device
3613 # is not already there or we pass a wrong path; we use notrunc to no
3614 # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3615 # much memory; this means that at best, we flush every 64k, which will
3617 suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3618 " bs=%s oflag=dsync"),
3622 elif mode == constants.IEM_EXPORT:
3623 # the block size on the read dd is 1MiB to match our units
3624 prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3626 str(1024 * 1024), # 1 MB
3628 exp_size = disk.size
3630 elif ieio == constants.IEIO_SCRIPT:
3631 (disk, disk_index, ) = ieargs
3633 assert isinstance(disk_index, (int, long))
3635 inst_os = OSFromDisk(instance.os)
3636 env = OSEnvironment(instance, inst_os)
3638 if mode == constants.IEM_IMPORT:
3639 env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3640 env["IMPORT_INDEX"] = str(disk_index)
3641 script = inst_os.import_script
3643 elif mode == constants.IEM_EXPORT:
3644 real_disk = _OpenRealBD(disk)
3645 env["EXPORT_DEVICE"] = real_disk.dev_path
3646 env["EXPORT_INDEX"] = str(disk_index)
3647 script = inst_os.export_script
3649 # TODO: Pass special environment only to script
3650 script_cmd = utils.BuildShellCmd("( cd %s && %s; )", inst_os.path, script)
3652 if mode == constants.IEM_IMPORT:
3653 suffix = "| %s" % script_cmd
3655 elif mode == constants.IEM_EXPORT:
3656 prefix = "%s |" % script_cmd
3658 # Let script predict size
3659 exp_size = constants.IE_CUSTOM_SIZE
3662 _Fail("Invalid %s I/O mode %r", mode, ieio)
3664 return (env, prefix, suffix, exp_size)
3667 def _CreateImportExportStatusDir(prefix):
3668 """Creates status directory for import/export.
3671 return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3673 (prefix, utils.TimestampForFilename())))
3676 def StartImportExportDaemon(mode, opts, host, port, instance, component,
3678 """Starts an import or export daemon.
3680 @param mode: Import/output mode
3681 @type opts: L{objects.ImportExportOptions}
3682 @param opts: Daemon options
3684 @param host: Remote host for export (None for import)
3686 @param port: Remote port for export (None for import)
3687 @type instance: L{objects.Instance}
3688 @param instance: Instance object
3689 @type component: string
3690 @param component: which part of the instance is transferred now,
3692 @param ieio: Input/output type
3693 @param ieioargs: Input/output arguments
3696 if mode == constants.IEM_IMPORT:
3699 if not (host is None and port is None):
3700 _Fail("Can not specify host or port on import")
3702 elif mode == constants.IEM_EXPORT:
3705 if host is None or port is None:
3706 _Fail("Host and port must be specified for an export")
3709 _Fail("Invalid mode %r", mode)
3711 if (opts.key_name is None) ^ (opts.ca_pem is None):
3712 _Fail("Cluster certificate can only be used for both key and CA")
3714 (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3715 _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3717 if opts.key_name is None:
3719 key_path = pathutils.NODED_CERT_FILE
3720 cert_path = pathutils.NODED_CERT_FILE
3721 assert opts.ca_pem is None
3723 (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3725 assert opts.ca_pem is not None
3727 for i in [key_path, cert_path]:
3728 if not os.path.exists(i):
3729 _Fail("File '%s' does not exist" % i)
3731 status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3733 status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3734 pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3735 ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3737 if opts.ca_pem is None:
3739 ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3744 utils.WriteFile(ca_file, data=ca, mode=0400)
3747 pathutils.IMPORT_EXPORT_DAEMON,
3749 "--key=%s" % key_path,
3750 "--cert=%s" % cert_path,
3751 "--ca=%s" % ca_file,
3755 cmd.append("--host=%s" % host)
3758 cmd.append("--port=%s" % port)
3761 cmd.append("--ipv6")
3763 cmd.append("--ipv4")
3766 cmd.append("--compress=%s" % opts.compress)
3769 cmd.append("--magic=%s" % opts.magic)
3771 if exp_size is not None:
3772 cmd.append("--expected-size=%s" % exp_size)
3775 cmd.append("--cmd-prefix=%s" % cmd_prefix)
3778 cmd.append("--cmd-suffix=%s" % cmd_suffix)
3780 if mode == constants.IEM_EXPORT:
3781 # Retry connection a few times when connecting to remote peer
3782 cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3783 cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3784 elif opts.connect_timeout is not None:
3785 assert mode == constants.IEM_IMPORT
3786 # Overall timeout for establishing connection while listening
3787 cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3789 logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3791 # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3792 # support for receiving a file descriptor for output
3793 utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3796 # The import/export name is simply the status directory name
3797 return os.path.basename(status_dir)
3800 shutil.rmtree(status_dir, ignore_errors=True)
3804 def GetImportExportStatus(names):
3805 """Returns import/export daemon status.
3807 @type names: sequence
3808 @param names: List of names
3809 @rtype: List of dicts
3810 @return: Returns a list of the state of each named import/export or None if a
3811 status couldn't be read
3817 status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3821 data = utils.ReadFile(status_file)
3822 except EnvironmentError, err:
3823 if err.errno != errno.ENOENT:
3831 result.append(serializer.LoadJson(data))
3836 def AbortImportExport(name):
3837 """Sends SIGTERM to a running import/export daemon.
3840 logging.info("Abort import/export %s", name)
3842 status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3843 pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3846 logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3848 utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3851 def CleanupImportExport(name):
3852 """Cleanup after an import or export.
3854 If the import/export daemon is still running it's killed. Afterwards the
3855 whole status directory is removed.
3858 logging.info("Finalizing import/export %s", name)
3860 status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3862 pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3865 logging.info("Import/export %s is still running with PID %s",
3867 utils.KillProcess(pid, waitpid=False)
3869 shutil.rmtree(status_dir, ignore_errors=True)
3872 def _FindDisks(disks):
3873 """Finds attached L{BlockDev}s for the given disks.
3875 @type disks: list of L{objects.Disk}
3876 @param disks: the disk objects we need to find
3878 @return: list of L{BlockDev} objects or C{None} if a given disk
3879 was not found or was no attached.
3885 rd = _RecursiveFindBD(disk)
3887 _Fail("Can't find device %s", disk)
3892 def DrbdDisconnectNet(disks):
3893 """Disconnects the network on a list of drbd devices.
3896 bdevs = _FindDisks(disks)
3902 except errors.BlockDeviceError, err:
3903 _Fail("Can't change network configuration to standalone mode: %s",
3907 def DrbdAttachNet(disks, instance_name, multimaster):
3908 """Attaches the network on a list of drbd devices.
3911 bdevs = _FindDisks(disks)
3914 for idx, rd in enumerate(bdevs):
3916 _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3917 except EnvironmentError, err:
3918 _Fail("Can't create symlink: %s", err)
3919 # reconnect disks, switch to new master configuration and if
3920 # needed primary mode
3923 rd.AttachNet(multimaster)
3924 except errors.BlockDeviceError, err:
3925 _Fail("Can't change network configuration: %s", err)
3927 # wait until the disks are connected; we need to retry the re-attach
3928 # if the device becomes standalone, as this might happen if the one
3929 # node disconnects and reconnects in a different mode before the
3930 # other node reconnects; in this case, one or both of the nodes will
3931 # decide it has wrong configuration and switch to standalone
3934 all_connected = True
3937 stats = rd.GetProcStatus()
3939 all_connected = (all_connected and
3940 (stats.is_connected or stats.is_in_resync))
3942 if stats.is_standalone:
3943 # peer had different config info and this node became
3944 # standalone, even though this should not happen with the
3945 # new staged way of changing disk configs
3947 rd.AttachNet(multimaster)
3948 except errors.BlockDeviceError, err:
3949 _Fail("Can't change network configuration: %s", err)
3951 if not all_connected:
3952 raise utils.RetryAgain()
3955 # Start with a delay of 100 miliseconds and go up to 5 seconds
3956 utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3957 except utils.RetryTimeout:
3958 _Fail("Timeout in disk reconnecting")
3961 # change to primary mode
3965 except errors.BlockDeviceError, err:
3966 _Fail("Can't change to primary mode: %s", err)
3969 def DrbdWaitSync(disks):
3970 """Wait until DRBDs have synchronized.
3974 stats = rd.GetProcStatus()
3975 if not (stats.is_connected or stats.is_in_resync):
3976 raise utils.RetryAgain()
3979 bdevs = _FindDisks(disks)
3985 # poll each second for 15 seconds
3986 stats = utils.Retry(_helper, 1, 15, args=[rd])
3987 except utils.RetryTimeout:
3988 stats = rd.GetProcStatus()
3990 if not (stats.is_connected or stats.is_in_resync):
3991 _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3992 alldone = alldone and (not stats.is_in_resync)
3993 if stats.sync_percent is not None:
3994 min_resync = min(min_resync, stats.sync_percent)
3996 return (alldone, min_resync)
3999 def DrbdNeedsActivation(disks):
4000 """Checks which of the passed disks needs activation and returns their UUIDs.
4006 rd = _RecursiveFindBD(disk)
4008 faulty_disks.append(disk)
4011 stats = rd.GetProcStatus()
4012 if stats.is_standalone or stats.is_diskless:
4013 faulty_disks.append(disk)
4015 return [disk.uuid for disk in faulty_disks]
4018 def GetDrbdUsermodeHelper():
4019 """Returns DRBD usermode helper currently configured.
4023 return drbd.DRBD8.GetUsermodeHelper()
4024 except errors.BlockDeviceError, err:
4028 def PowercycleNode(hypervisor_type, hvparams=None):
4029 """Hard-powercycle the node.
4031 Because we need to return first, and schedule the powercycle in the
4032 background, we won't be able to report failures nicely.
4035 hyper = hypervisor.GetHypervisor(hypervisor_type)
4039 # if we can't fork, we'll pretend that we're in the child process
4042 return "Reboot scheduled in 5 seconds"
4043 # ensure the child is running on ram
4046 except Exception: # pylint: disable=W0703
4049 hyper.PowercycleNode(hvparams=hvparams)
4052 def _VerifyRestrictedCmdName(cmd):
4053 """Verifies a restricted command name.
4056 @param cmd: Command name
4057 @rtype: tuple; (boolean, string or None)
4058 @return: The tuple's first element is the status; if C{False}, the second
4059 element is an error message string, otherwise it's C{None}
4063 return (False, "Missing command name")
4065 if os.path.basename(cmd) != cmd:
4066 return (False, "Invalid command name")
4068 if not constants.EXT_PLUGIN_MASK.match(cmd):
4069 return (False, "Command name contains forbidden characters")
4074 def _CommonRestrictedCmdCheck(path, owner):
4075 """Common checks for restricted command file system directories and files.
4078 @param path: Path to check
4079 @param owner: C{None} or tuple containing UID and GID
4080 @rtype: tuple; (boolean, string or C{os.stat} result)
4081 @return: The tuple's first element is the status; if C{False}, the second
4082 element is an error message string, otherwise it's the result of C{os.stat}
4086 # Default to root as owner
4091 except EnvironmentError, err:
4092 return (False, "Can't stat(2) '%s': %s" % (path, err))
4094 if stat.S_IMODE(st.st_mode) & (~_RCMD_MAX_MODE):
4095 return (False, "Permissions on '%s' are too permissive" % path)
4097 if (st.st_uid, st.st_gid) != owner:
4098 (owner_uid, owner_gid) = owner
4099 return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
4104 def _VerifyRestrictedCmdDirectory(path, _owner=None):
4105 """Verifies restricted command directory.
4108 @param path: Path to check
4109 @rtype: tuple; (boolean, string or None)
4110 @return: The tuple's first element is the status; if C{False}, the second
4111 element is an error message string, otherwise it's C{None}
4114 (status, value) = _CommonRestrictedCmdCheck(path, _owner)
4117 return (False, value)
4119 if not stat.S_ISDIR(value.st_mode):
4120 return (False, "Path '%s' is not a directory" % path)
4125 def _VerifyRestrictedCmd(path, cmd, _owner=None):
4126 """Verifies a whole restricted command and returns its executable filename.
4129 @param path: Directory containing restricted commands
4131 @param cmd: Command name
4132 @rtype: tuple; (boolean, string)
4133 @return: The tuple's first element is the status; if C{False}, the second
4134 element is an error message string, otherwise the second element is the
4135 absolute path to the executable
4138 executable = utils.PathJoin(path, cmd)
4140 (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
4145 if not utils.IsExecutable(executable):
4146 return (False, "access(2) thinks '%s' can't be executed" % executable)
4148 return (True, executable)
4151 def _PrepareRestrictedCmd(path, cmd,
4152 _verify_dir=_VerifyRestrictedCmdDirectory,
4153 _verify_name=_VerifyRestrictedCmdName,
4154 _verify_cmd=_VerifyRestrictedCmd):
4155 """Performs a number of tests on a restricted command.
4158 @param path: Directory containing restricted commands
4160 @param cmd: Command name
4161 @return: Same as L{_VerifyRestrictedCmd}
4164 # Verify the directory first
4165 (status, msg) = _verify_dir(path)
4167 # Check command if everything was alright
4168 (status, msg) = _verify_name(cmd)
4173 # Check actual executable
4174 return _verify_cmd(path, cmd)
4177 def RunRestrictedCmd(cmd,
4178 _lock_timeout=_RCMD_LOCK_TIMEOUT,
4179 _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
4180 _path=pathutils.RESTRICTED_COMMANDS_DIR,
4181 _sleep_fn=time.sleep,
4182 _prepare_fn=_PrepareRestrictedCmd,
4183 _runcmd_fn=utils.RunCmd,
4184 _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
4185 """Executes a restricted command after performing strict tests.
4188 @param cmd: Command name
4190 @return: Command output
4191 @raise RPCFail: In case of an error
4194 logging.info("Preparing to run restricted command '%s'", cmd)
4197 _Fail("Restricted commands disabled at configure time")
4203 lock = utils.FileLock.Open(_lock_file)
4204 lock.Exclusive(blocking=True, timeout=_lock_timeout)
4206 (status, value) = _prepare_fn(_path, cmd)
4209 cmdresult = _runcmd_fn([value], env={}, reset_env=True,
4210 postfork_fn=lambda _: lock.Unlock())
4212 logging.error(value)
4213 except Exception: # pylint: disable=W0703
4214 # Keep original error in log
4215 logging.exception("Caught exception")
4217 if cmdresult is None:
4218 logging.info("Sleeping for %0.1f seconds before returning",
4219 _RCMD_INVALID_DELAY)
4220 _sleep_fn(_RCMD_INVALID_DELAY)
4222 # Do not include original error message in returned error
4223 _Fail("Executing command '%s' failed" % cmd)
4224 elif cmdresult.failed or cmdresult.fail_reason:
4225 _Fail("Restricted command '%s' failed: %s; output: %s",
4226 cmd, cmdresult.fail_reason, cmdresult.output)
4228 return cmdresult.output
4230 if lock is not None:
4231 # Release lock at last
4236 def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
4237 """Creates or removes the watcher pause file.
4239 @type until: None or number
4240 @param until: Unix timestamp saying until when the watcher shouldn't run
4244 logging.info("Received request to no longer pause watcher")
4245 utils.RemoveFile(_filename)
4247 logging.info("Received request to pause watcher until %s", until)
4249 if not ht.TNumber(until):
4250 _Fail("Duration must be numeric")
4252 utils.WriteFile(_filename, data="%d\n" % (until, ), mode=0644)
4255 def ConfigureOVS(ovs_name, ovs_link):
4256 """Creates a OpenvSwitch on the node.
4258 This function sets up a OpenvSwitch on the node with given name nad
4259 connects it via a given eth device.
4261 @type ovs_name: string
4262 @param ovs_name: Name of the OpenvSwitch to create.
4263 @type ovs_link: None or string
4264 @param ovs_link: Ethernet device for outside connection (can be missing)
4267 # Initialize the OpenvSwitch
4268 result = utils.RunCmd(["ovs-vsctl", "add-br", ovs_name])
4270 _Fail("Failed to create openvswitch %s. Script return value: %s, output:"
4271 " '%s'" % result.exit_code, result.output, log=True)
4273 # And connect it to a physical interface, if given
4275 result = utils.RunCmd(["ovs-vsctl", "add-port", ovs_name, ovs_link])
4277 _Fail("Failed to connect openvswitch to interface %s. Script return"
4278 " value: %s, output: '%s'" % ovs_link, result.exit_code,
4279 result.output, log=True)
4282 class HooksRunner(object):
4285 This class is instantiated on the node side (ganeti-noded) and not
4289 def __init__(self, hooks_base_dir=None):
4290 """Constructor for hooks runner.
4292 @type hooks_base_dir: str or None
4293 @param hooks_base_dir: if not None, this overrides the
4294 L{pathutils.HOOKS_BASE_DIR} (useful for unittests)
4297 if hooks_base_dir is None:
4298 hooks_base_dir = pathutils.HOOKS_BASE_DIR
4299 # yeah, _BASE_DIR is not valid for attributes, we use it like a
4301 self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
4303 def RunLocalHooks(self, node_list, hpath, phase, env):
4304 """Check that the hooks will be run only locally and then run them.
4307 assert len(node_list) == 1
4309 _, myself = ssconf.GetMasterAndMyself()
4310 assert node == myself
4312 results = self.RunHooks(hpath, phase, env)
4314 # Return values in the form expected by HooksMaster
4315 return {node: (None, False, results)}
4317 def RunHooks(self, hpath, phase, env):
4318 """Run the scripts in the hooks directory.
4321 @param hpath: the path to the hooks directory which
4324 @param phase: either L{constants.HOOKS_PHASE_PRE} or
4325 L{constants.HOOKS_PHASE_POST}
4327 @param env: dictionary with the environment for the hook
4329 @return: list of 3-element tuples:
4331 - script result, either L{constants.HKR_SUCCESS} or
4332 L{constants.HKR_FAIL}
4333 - output of the script
4335 @raise errors.ProgrammerError: for invalid input
4339 if phase == constants.HOOKS_PHASE_PRE:
4341 elif phase == constants.HOOKS_PHASE_POST:
4344 _Fail("Unknown hooks phase '%s'", phase)
4346 subdir = "%s-%s.d" % (hpath, suffix)
4347 dir_name = utils.PathJoin(self._BASE_DIR, subdir)
4351 if not os.path.isdir(dir_name):
4352 # for non-existing/non-dirs, we simply exit instead of logging a
4353 # warning at every operation
4356 runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
4358 for (relname, relstatus, runresult) in runparts_results:
4359 if relstatus == constants.RUNPARTS_SKIP:
4360 rrval = constants.HKR_SKIP
4362 elif relstatus == constants.RUNPARTS_ERR:
4363 rrval = constants.HKR_FAIL
4364 output = "Hook script execution error: %s" % runresult
4365 elif relstatus == constants.RUNPARTS_RUN:
4366 if runresult.failed:
4367 rrval = constants.HKR_FAIL
4369 rrval = constants.HKR_SUCCESS
4370 output = utils.SafeEncode(runresult.output.strip())
4371 results.append(("%s/%s" % (subdir, relname), rrval, output))
4376 class IAllocatorRunner(object):
4377 """IAllocator runner.
4379 This class is instantiated on the node side (ganeti-noded) and not on
4384 def Run(name, idata):
4385 """Run an iallocator script.
4388 @param name: the iallocator script name
4390 @param idata: the allocator input data
4393 @return: two element tuple of:
4395 - either error message or stdout of allocator (for success)
4398 alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
4400 if alloc_script is None:
4401 _Fail("iallocator module '%s' not found in the search path", name)
4403 fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
4407 result = utils.RunCmd([alloc_script, fin_name])
4409 _Fail("iallocator module '%s' failed: %s, output '%s'",
4410 name, result.fail_reason, result.output)
4414 return result.stdout
4417 class DevCacheManager(object):
4418 """Simple class for managing a cache of block device information.
4421 _DEV_PREFIX = "/dev/"
4422 _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4425 def _ConvertPath(cls, dev_path):
4426 """Converts a /dev/name path to the cache file name.
4428 This replaces slashes with underscores and strips the /dev
4429 prefix. It then returns the full path to the cache file.
4432 @param dev_path: the C{/dev/} path name
4434 @return: the converted path name
4437 if dev_path.startswith(cls._DEV_PREFIX):
4438 dev_path = dev_path[len(cls._DEV_PREFIX):]
4439 dev_path = dev_path.replace("/", "_")
4440 fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4444 def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4445 """Updates the cache information for a given device.
4448 @param dev_path: the pathname of the device
4450 @param owner: the owner (instance name) of the device
4451 @type on_primary: bool
4452 @param on_primary: whether this is the primary
4455 @param iv_name: the instance-visible name of the
4456 device, as in objects.Disk.iv_name
4461 if dev_path is None:
4462 logging.error("DevCacheManager.UpdateCache got a None dev_path")
4464 fpath = cls._ConvertPath(dev_path)
4470 iv_name = "not_visible"
4471 fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4473 utils.WriteFile(fpath, data=fdata)
4474 except EnvironmentError, err:
4475 logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4478 def RemoveCache(cls, dev_path):
4479 """Remove data for a dev_path.
4481 This is just a wrapper over L{utils.io.RemoveFile} with a converted
4482 path name and logging.
4485 @param dev_path: the pathname of the device
4490 if dev_path is None:
4491 logging.error("DevCacheManager.RemoveCache got a None dev_path")
4493 fpath = cls._ConvertPath(dev_path)
4495 utils.RemoveFile(fpath)
4496 except EnvironmentError, err:
4497 logging.exception("Can't update bdev cache for %s: %s", dev_path, err)