4d3a2dd444b4f5ec9893f099e01b1a19bd0320d3
[ganeti-github.git] / lib / backend.py
1 #
2 #
3
4 # Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 Google Inc.
5 # All rights reserved.
6 #
7 # Redistribution and use in source and binary forms, with or without
8 # modification, are permitted provided that the following conditions are
9 # met:
10 #
11 # 1. Redistributions of source code must retain the above copyright notice,
12 # this list of conditions and the following disclaimer.
13 #
14 # 2. Redistributions in binary form must reproduce the above copyright
15 # notice, this list of conditions and the following disclaimer in the
16 # documentation and/or other materials provided with the distribution.
17 #
18 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
19 # IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
20 # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21 # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
22 # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23 # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25 # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26 # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27 # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28 # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30
31 """Functions used by the node daemon
32
33 @var _ALLOWED_UPLOAD_FILES: denotes which files are accepted in
34 the L{UploadFile} function
35 @var _ALLOWED_CLEAN_DIRS: denotes which directories are accepted
36 in the L{_CleanDirectory} function
37
38 """
39
40 # pylint: disable=E1103,C0302
41
42 # E1103: %s %r has no %r member (but some types could not be
43 # inferred), because the _TryOSFromDisk returns either (True, os_obj)
44 # or (False, "string") which confuses pylint
45
46 # C0302: This module has become too big and should be split up
47
48
49 import base64
50 import errno
51 import logging
52 import os
53 import os.path
54 import pycurl
55 import random
56 import re
57 import shutil
58 import signal
59 import stat
60 import tempfile
61 import time
62 import zlib
63 import contextlib
64 import collections
65
66 from ganeti import errors
67 from ganeti import http
68 from ganeti import utils
69 from ganeti import ssh
70 from ganeti import hypervisor
71 from ganeti.hypervisor import hv_base
72 from ganeti import constants
73 from ganeti.storage import bdev
74 from ganeti.storage import drbd
75 from ganeti.storage import extstorage
76 from ganeti.storage import filestorage
77 from ganeti import objects
78 from ganeti import ssconf
79 from ganeti import serializer
80 from ganeti import netutils
81 from ganeti import runtime
82 from ganeti import compat
83 from ganeti import pathutils
84 from ganeti import vcluster
85 from ganeti import ht
86 from ganeti.storage.base import BlockDev
87 from ganeti.storage.drbd import DRBD8
88 from ganeti import hooksmaster
89 import ganeti.metad as metad
90
91
92 _BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id"
93 _ALLOWED_CLEAN_DIRS = compat.UniqueFrozenset([
94 pathutils.DATA_DIR,
95 pathutils.JOB_QUEUE_ARCHIVE_DIR,
96 pathutils.QUEUE_DIR,
97 pathutils.CRYPTO_KEYS_DIR,
98 ])
99 _MAX_SSL_CERT_VALIDITY = 7 * 24 * 60 * 60
100 _X509_KEY_FILE = "key"
101 _X509_CERT_FILE = "cert"
102 _IES_STATUS_FILE = "status"
103 _IES_PID_FILE = "pid"
104 _IES_CA_FILE = "ca"
105
106 #: Valid LVS output line regex
107 _LVSLINE_REGEX = re.compile(r"^ *([^|]+)\|([^|]+)\|([0-9.]+)\|([^|]{6,})\|?$")
108
109 # Actions for the master setup script
110 _MASTER_START = "start"
111 _MASTER_STOP = "stop"
112
113 #: Maximum file permissions for restricted command directory and executables
114 _RCMD_MAX_MODE = (stat.S_IRWXU |
115 stat.S_IRGRP | stat.S_IXGRP |
116 stat.S_IROTH | stat.S_IXOTH)
117
118 #: Delay before returning an error for restricted commands
119 _RCMD_INVALID_DELAY = 10
120
121 #: How long to wait to acquire lock for restricted commands (shorter than
122 #: L{_RCMD_INVALID_DELAY}) to reduce blockage of noded forks when many
123 #: command requests arrive
124 _RCMD_LOCK_TIMEOUT = _RCMD_INVALID_DELAY * 0.8
125
126
127 class RPCFail(Exception):
128 """Class denoting RPC failure.
129
130 Its argument is the error message.
131
132 """
133
134
135 def _GetInstReasonFilename(instance_name):
136 """Path of the file containing the reason of the instance status change.
137
138 @type instance_name: string
139 @param instance_name: The name of the instance
140 @rtype: string
141 @return: The path of the file
142
143 """
144 return utils.PathJoin(pathutils.INSTANCE_REASON_DIR, instance_name)
145
146
147 def _StoreInstReasonTrail(instance_name, trail):
148 """Serialize a reason trail related to an instance change of state to file.
149
150 The exact location of the file depends on the name of the instance and on
151 the configuration of the Ganeti cluster defined at deploy time.
152
153 @type instance_name: string
154 @param instance_name: The name of the instance
155
156 @type trail: list of reasons
157 @param trail: reason trail
158
159 @rtype: None
160
161 """
162 json = serializer.DumpJson(trail)
163 filename = _GetInstReasonFilename(instance_name)
164 utils.WriteFile(filename, data=json)
165
166
167 def _Fail(msg, *args, **kwargs):
168 """Log an error and the raise an RPCFail exception.
169
170 This exception is then handled specially in the ganeti daemon and
171 turned into a 'failed' return type. As such, this function is a
172 useful shortcut for logging the error and returning it to the master
173 daemon.
174
175 @type msg: string
176 @param msg: the text of the exception
177 @raise RPCFail
178
179 """
180 if args:
181 msg = msg % args
182 if "log" not in kwargs or kwargs["log"]: # if we should log this error
183 if "exc" in kwargs and kwargs["exc"]:
184 logging.exception(msg)
185 else:
186 logging.error(msg)
187 raise RPCFail(msg)
188
189
190 def _GetConfig():
191 """Simple wrapper to return a SimpleStore.
192
193 @rtype: L{ssconf.SimpleStore}
194 @return: a SimpleStore instance
195
196 """
197 return ssconf.SimpleStore()
198
199
200 def _GetSshRunner(cluster_name):
201 """Simple wrapper to return an SshRunner.
202
203 @type cluster_name: str
204 @param cluster_name: the cluster name, which is needed
205 by the SshRunner constructor
206 @rtype: L{ssh.SshRunner}
207 @return: an SshRunner instance
208
209 """
210 return ssh.SshRunner(cluster_name)
211
212
213 def _Decompress(data):
214 """Unpacks data compressed by the RPC client.
215
216 @type data: list or tuple
217 @param data: Data sent by RPC client
218 @rtype: str
219 @return: Decompressed data
220
221 """
222 assert isinstance(data, (list, tuple))
223 assert len(data) == 2
224 (encoding, content) = data
225 if encoding == constants.RPC_ENCODING_NONE:
226 return content
227 elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
228 return zlib.decompress(base64.b64decode(content))
229 else:
230 raise AssertionError("Unknown data encoding")
231
232
233 def _CleanDirectory(path, exclude=None):
234 """Removes all regular files in a directory.
235
236 @type path: str
237 @param path: the directory to clean
238 @type exclude: list
239 @param exclude: list of files to be excluded, defaults
240 to the empty list
241
242 """
243 if path not in _ALLOWED_CLEAN_DIRS:
244 _Fail("Path passed to _CleanDirectory not in allowed clean targets: '%s'",
245 path)
246
247 if not os.path.isdir(path):
248 return
249 if exclude is None:
250 exclude = []
251 else:
252 # Normalize excluded paths
253 exclude = [os.path.normpath(i) for i in exclude]
254
255 for rel_name in utils.ListVisibleFiles(path):
256 full_name = utils.PathJoin(path, rel_name)
257 if full_name in exclude:
258 continue
259 if os.path.isfile(full_name) and not os.path.islink(full_name):
260 utils.RemoveFile(full_name)
261
262
263 def _BuildUploadFileList():
264 """Build the list of allowed upload files.
265
266 This is abstracted so that it's built only once at module import time.
267
268 """
269 allowed_files = set([
270 pathutils.CLUSTER_CONF_FILE,
271 pathutils.ETC_HOSTS,
272 pathutils.SSH_KNOWN_HOSTS_FILE,
273 pathutils.VNC_PASSWORD_FILE,
274 pathutils.RAPI_CERT_FILE,
275 pathutils.SPICE_CERT_FILE,
276 pathutils.SPICE_CACERT_FILE,
277 pathutils.RAPI_USERS_FILE,
278 pathutils.CONFD_HMAC_KEY,
279 pathutils.CLUSTER_DOMAIN_SECRET_FILE,
280 ])
281
282 for hv_name in constants.HYPER_TYPES:
283 hv_class = hypervisor.GetHypervisorClass(hv_name)
284 allowed_files.update(hv_class.GetAncillaryFiles()[0])
285
286 assert pathutils.FILE_STORAGE_PATHS_FILE not in allowed_files, \
287 "Allowed file storage paths should never be uploaded via RPC"
288
289 return frozenset(allowed_files)
290
291
292 _ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
293
294
295 def JobQueuePurge():
296 """Removes job queue files and archived jobs.
297
298 @rtype: tuple
299 @return: True, None
300
301 """
302 _CleanDirectory(pathutils.QUEUE_DIR, exclude=[pathutils.JOB_QUEUE_LOCK_FILE])
303 _CleanDirectory(pathutils.JOB_QUEUE_ARCHIVE_DIR)
304
305
306 def GetMasterNodeName():
307 """Returns the master node name.
308
309 @rtype: string
310 @return: name of the master node
311 @raise RPCFail: in case of errors
312
313 """
314 try:
315 return _GetConfig().GetMasterNode()
316 except errors.ConfigurationError, err:
317 _Fail("Cluster configuration incomplete: %s", err, exc=True)
318
319
320 def RunLocalHooks(hook_opcode, hooks_path, env_builder_fn):
321 """Decorator that runs hooks before and after the decorated function.
322
323 @type hook_opcode: string
324 @param hook_opcode: opcode of the hook
325 @type hooks_path: string
326 @param hooks_path: path of the hooks
327 @type env_builder_fn: function
328 @param env_builder_fn: function that returns a dictionary containing the
329 environment variables for the hooks. Will get all the parameters of the
330 decorated function.
331 @raise RPCFail: in case of pre-hook failure
332
333 """
334 def decorator(fn):
335 def wrapper(*args, **kwargs):
336 _, myself = ssconf.GetMasterAndMyself()
337 nodes = ([myself], [myself]) # these hooks run locally
338
339 env_fn = compat.partial(env_builder_fn, *args, **kwargs)
340
341 cfg = _GetConfig()
342 hr = HooksRunner()
343 hm = hooksmaster.HooksMaster(hook_opcode, hooks_path, nodes,
344 hr.RunLocalHooks, None, env_fn, None,
345 logging.warning, cfg.GetClusterName(),
346 cfg.GetMasterNode())
347 hm.RunPhase(constants.HOOKS_PHASE_PRE)
348 result = fn(*args, **kwargs)
349 hm.RunPhase(constants.HOOKS_PHASE_POST)
350
351 return result
352 return wrapper
353 return decorator
354
355
356 def _BuildMasterIpEnv(master_params, use_external_mip_script=None):
357 """Builds environment variables for master IP hooks.
358
359 @type master_params: L{objects.MasterNetworkParameters}
360 @param master_params: network parameters of the master
361 @type use_external_mip_script: boolean
362 @param use_external_mip_script: whether to use an external master IP
363 address setup script (unused, but necessary per the implementation of the
364 _RunLocalHooks decorator)
365
366 """
367 # pylint: disable=W0613
368 ver = netutils.IPAddress.GetVersionFromAddressFamily(master_params.ip_family)
369 env = {
370 "MASTER_NETDEV": master_params.netdev,
371 "MASTER_IP": master_params.ip,
372 "MASTER_NETMASK": str(master_params.netmask),
373 "CLUSTER_IP_VERSION": str(ver),
374 }
375
376 return env
377
378
379 def _RunMasterSetupScript(master_params, action, use_external_mip_script):
380 """Execute the master IP address setup script.
381
382 @type master_params: L{objects.MasterNetworkParameters}
383 @param master_params: network parameters of the master
384 @type action: string
385 @param action: action to pass to the script. Must be one of
386 L{backend._MASTER_START} or L{backend._MASTER_STOP}
387 @type use_external_mip_script: boolean
388 @param use_external_mip_script: whether to use an external master IP
389 address setup script
390 @raise backend.RPCFail: if there are errors during the execution of the
391 script
392
393 """
394 env = _BuildMasterIpEnv(master_params)
395
396 if use_external_mip_script:
397 setup_script = pathutils.EXTERNAL_MASTER_SETUP_SCRIPT
398 else:
399 setup_script = pathutils.DEFAULT_MASTER_SETUP_SCRIPT
400
401 result = utils.RunCmd([setup_script, action], env=env, reset_env=True)
402
403 if result.failed:
404 _Fail("Failed to %s the master IP. Script return value: %s, output: '%s'" %
405 (action, result.exit_code, result.output), log=True)
406
407
408 @RunLocalHooks(constants.FAKE_OP_MASTER_TURNUP, "master-ip-turnup",
409 _BuildMasterIpEnv)
410 def ActivateMasterIp(master_params, use_external_mip_script):
411 """Activate the IP address of the master daemon.
412
413 @type master_params: L{objects.MasterNetworkParameters}
414 @param master_params: network parameters of the master
415 @type use_external_mip_script: boolean
416 @param use_external_mip_script: whether to use an external master IP
417 address setup script
418 @raise RPCFail: in case of errors during the IP startup
419
420 """
421 _RunMasterSetupScript(master_params, _MASTER_START,
422 use_external_mip_script)
423
424
425 def StartMasterDaemons(no_voting):
426 """Activate local node as master node.
427
428 The function will start the master daemons (ganeti-masterd and ganeti-rapi).
429
430 @type no_voting: boolean
431 @param no_voting: whether to start ganeti-masterd without a node vote
432 but still non-interactively
433 @rtype: None
434
435 """
436
437 if no_voting:
438 masterd_args = "--no-voting --yes-do-it"
439 else:
440 masterd_args = ""
441
442 env = {
443 "EXTRA_MASTERD_ARGS": masterd_args,
444 }
445
446 result = utils.RunCmd([pathutils.DAEMON_UTIL, "start-master"], env=env)
447 if result.failed:
448 msg = "Can't start Ganeti master: %s" % result.output
449 logging.error(msg)
450 _Fail(msg)
451
452
453 @RunLocalHooks(constants.FAKE_OP_MASTER_TURNDOWN, "master-ip-turndown",
454 _BuildMasterIpEnv)
455 def DeactivateMasterIp(master_params, use_external_mip_script):
456 """Deactivate the master IP on this node.
457
458 @type master_params: L{objects.MasterNetworkParameters}
459 @param master_params: network parameters of the master
460 @type use_external_mip_script: boolean
461 @param use_external_mip_script: whether to use an external master IP
462 address setup script
463 @raise RPCFail: in case of errors during the IP turndown
464
465 """
466 _RunMasterSetupScript(master_params, _MASTER_STOP,
467 use_external_mip_script)
468
469
470 def StopMasterDaemons():
471 """Stop the master daemons on this node.
472
473 Stop the master daemons (ganeti-masterd and ganeti-rapi) on this node.
474
475 @rtype: None
476
477 """
478 # TODO: log and report back to the caller the error failures; we
479 # need to decide in which case we fail the RPC for this
480
481 result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop-master"])
482 if result.failed:
483 logging.error("Could not stop Ganeti master, command %s had exitcode %s"
484 " and error %s",
485 result.cmd, result.exit_code, result.output)
486
487
488 def ChangeMasterNetmask(old_netmask, netmask, master_ip, master_netdev):
489 """Change the netmask of the master IP.
490
491 @param old_netmask: the old value of the netmask
492 @param netmask: the new value of the netmask
493 @param master_ip: the master IP
494 @param master_netdev: the master network device
495
496 """
497 if old_netmask == netmask:
498 return
499
500 if not netutils.IPAddress.Own(master_ip):
501 _Fail("The master IP address is not up, not attempting to change its"
502 " netmask")
503
504 result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
505 "%s/%s" % (master_ip, netmask),
506 "dev", master_netdev, "label",
507 "%s:0" % master_netdev])
508 if result.failed:
509 _Fail("Could not set the new netmask on the master IP address")
510
511 result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
512 "%s/%s" % (master_ip, old_netmask),
513 "dev", master_netdev, "label",
514 "%s:0" % master_netdev])
515 if result.failed:
516 _Fail("Could not bring down the master IP address with the old netmask")
517
518
519 def EtcHostsModify(mode, host, ip):
520 """Modify a host entry in /etc/hosts.
521
522 @param mode: The mode to operate. Either add or remove entry
523 @param host: The host to operate on
524 @param ip: The ip associated with the entry
525
526 """
527 if mode == constants.ETC_HOSTS_ADD:
528 if not ip:
529 RPCFail("Mode 'add' needs 'ip' parameter, but parameter not"
530 " present")
531 utils.AddHostToEtcHosts(host, ip)
532 elif mode == constants.ETC_HOSTS_REMOVE:
533 if ip:
534 RPCFail("Mode 'remove' does not allow 'ip' parameter, but"
535 " parameter is present")
536 utils.RemoveHostFromEtcHosts(host)
537 else:
538 RPCFail("Mode not supported")
539
540
541 def LeaveCluster(modify_ssh_setup):
542 """Cleans up and remove the current node.
543
544 This function cleans up and prepares the current node to be removed
545 from the cluster.
546
547 If processing is successful, then it raises an
548 L{errors.QuitGanetiException} which is used as a special case to
549 shutdown the node daemon.
550
551 @param modify_ssh_setup: boolean
552
553 """
554 _CleanDirectory(pathutils.DATA_DIR)
555 _CleanDirectory(pathutils.CRYPTO_KEYS_DIR)
556 JobQueuePurge()
557
558 if modify_ssh_setup:
559 try:
560 priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.SSH_LOGIN_USER)
561
562 ssh.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
563
564 utils.RemoveFile(priv_key)
565 utils.RemoveFile(pub_key)
566 except errors.OpExecError:
567 logging.exception("Error while processing ssh files")
568
569 try:
570 utils.RemoveFile(pathutils.CONFD_HMAC_KEY)
571 utils.RemoveFile(pathutils.RAPI_CERT_FILE)
572 utils.RemoveFile(pathutils.SPICE_CERT_FILE)
573 utils.RemoveFile(pathutils.SPICE_CACERT_FILE)
574 utils.RemoveFile(pathutils.NODED_CERT_FILE)
575 except: # pylint: disable=W0702
576 logging.exception("Error while removing cluster secrets")
577
578 utils.StopDaemon(constants.CONFD)
579 utils.StopDaemon(constants.MOND)
580 utils.StopDaemon(constants.KVMD)
581
582 # Raise a custom exception (handled in ganeti-noded)
583 raise errors.QuitGanetiException(True, "Shutdown scheduled")
584
585
586 def _CheckStorageParams(params, num_params):
587 """Performs sanity checks for storage parameters.
588
589 @type params: list
590 @param params: list of storage parameters
591 @type num_params: int
592 @param num_params: expected number of parameters
593
594 """
595 if params is None:
596 raise errors.ProgrammerError("No storage parameters for storage"
597 " reporting is provided.")
598 if not isinstance(params, list):
599 raise errors.ProgrammerError("The storage parameters are not of type"
600 " list: '%s'" % params)
601 if not len(params) == num_params:
602 raise errors.ProgrammerError("Did not receive the expected number of"
603 "storage parameters: expected %s,"
604 " received '%s'" % (num_params, len(params)))
605
606
607 def _CheckLvmStorageParams(params):
608 """Performs sanity check for the 'exclusive storage' flag.
609
610 @see: C{_CheckStorageParams}
611
612 """
613 _CheckStorageParams(params, 1)
614 excl_stor = params[0]
615 if not isinstance(params[0], bool):
616 raise errors.ProgrammerError("Exclusive storage parameter is not"
617 " boolean: '%s'." % excl_stor)
618 return excl_stor
619
620
621 def _GetLvmVgSpaceInfo(name, params):
622 """Wrapper around C{_GetVgInfo} which checks the storage parameters.
623
624 @type name: string
625 @param name: name of the volume group
626 @type params: list
627 @param params: list of storage parameters, which in this case should be
628 containing only one for exclusive storage
629
630 """
631 excl_stor = _CheckLvmStorageParams(params)
632 return _GetVgInfo(name, excl_stor)
633
634
635 def _GetVgInfo(
636 name, excl_stor, info_fn=bdev.LogicalVolume.GetVGInfo):
637 """Retrieves information about a LVM volume group.
638
639 """
640 # TODO: GetVGInfo supports returning information for multiple VGs at once
641 vginfo = info_fn([name], excl_stor)
642 if vginfo:
643 vg_free = int(round(vginfo[0][0], 0))
644 vg_size = int(round(vginfo[0][1], 0))
645 else:
646 vg_free = None
647 vg_size = None
648
649 return {
650 "type": constants.ST_LVM_VG,
651 "name": name,
652 "storage_free": vg_free,
653 "storage_size": vg_size,
654 }
655
656
657 def _GetLvmPvSpaceInfo(name, params):
658 """Wrapper around C{_GetVgSpindlesInfo} with sanity checks.
659
660 @see: C{_GetLvmVgSpaceInfo}
661
662 """
663 excl_stor = _CheckLvmStorageParams(params)
664 return _GetVgSpindlesInfo(name, excl_stor)
665
666
667 def _GetVgSpindlesInfo(
668 name, excl_stor, info_fn=bdev.LogicalVolume.GetVgSpindlesInfo):
669 """Retrieves information about spindles in an LVM volume group.
670
671 @type name: string
672 @param name: VG name
673 @type excl_stor: bool
674 @param excl_stor: exclusive storage
675 @rtype: dict
676 @return: dictionary whose keys are "name", "vg_free", "vg_size" for VG name,
677 free spindles, total spindles respectively
678
679 """
680 if excl_stor:
681 (vg_free, vg_size) = info_fn(name)
682 else:
683 vg_free = 0
684 vg_size = 0
685 return {
686 "type": constants.ST_LVM_PV,
687 "name": name,
688 "storage_free": vg_free,
689 "storage_size": vg_size,
690 }
691
692
693 def _GetHvInfo(name, hvparams, get_hv_fn=hypervisor.GetHypervisor):
694 """Retrieves node information from a hypervisor.
695
696 The information returned depends on the hypervisor. Common items:
697
698 - vg_size is the size of the configured volume group in MiB
699 - vg_free is the free size of the volume group in MiB
700 - memory_dom0 is the memory allocated for domain0 in MiB
701 - memory_free is the currently available (free) ram in MiB
702 - memory_total is the total number of ram in MiB
703 - hv_version: the hypervisor version, if available
704
705 @type hvparams: dict of string
706 @param hvparams: the hypervisor's hvparams
707
708 """
709 return get_hv_fn(name).GetNodeInfo(hvparams=hvparams)
710
711
712 def _GetHvInfoAll(hv_specs, get_hv_fn=hypervisor.GetHypervisor):
713 """Retrieves node information for all hypervisors.
714
715 See C{_GetHvInfo} for information on the output.
716
717 @type hv_specs: list of pairs (string, dict of strings)
718 @param hv_specs: list of pairs of a hypervisor's name and its hvparams
719
720 """
721 if hv_specs is None:
722 return None
723
724 result = []
725 for hvname, hvparams in hv_specs:
726 result.append(_GetHvInfo(hvname, hvparams, get_hv_fn))
727 return result
728
729
730 def _GetNamedNodeInfo(names, fn):
731 """Calls C{fn} for all names in C{names} and returns a dictionary.
732
733 @rtype: None or dict
734
735 """
736 if names is None:
737 return None
738 else:
739 return map(fn, names)
740
741
742 def GetNodeInfo(storage_units, hv_specs):
743 """Gives back a hash with different information about the node.
744
745 @type storage_units: list of tuples (string, string, list)
746 @param storage_units: List of tuples (storage unit, identifier, parameters) to
747 ask for disk space information. In case of lvm-vg, the identifier is
748 the VG name. The parameters can contain additional, storage-type-specific
749 parameters, for example exclusive storage for lvm storage.
750 @type hv_specs: list of pairs (string, dict of strings)
751 @param hv_specs: list of pairs of a hypervisor's name and its hvparams
752 @rtype: tuple; (string, None/dict, None/dict)
753 @return: Tuple containing boot ID, volume group information and hypervisor
754 information
755
756 """
757 bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
758 storage_info = _GetNamedNodeInfo(
759 storage_units,
760 (lambda (storage_type, storage_key, storage_params):
761 _ApplyStorageInfoFunction(storage_type, storage_key, storage_params)))
762 hv_info = _GetHvInfoAll(hv_specs)
763 return (bootid, storage_info, hv_info)
764
765
766 def _GetFileStorageSpaceInfo(path, params):
767 """Wrapper around filestorage.GetSpaceInfo.
768
769 The purpose of this wrapper is to call filestorage.GetFileStorageSpaceInfo
770 and ignore the *args parameter to not leak it into the filestorage
771 module's code.
772
773 @see: C{filestorage.GetFileStorageSpaceInfo} for description of the
774 parameters.
775
776 """
777 _CheckStorageParams(params, 0)
778 return filestorage.GetFileStorageSpaceInfo(path)
779
780
781 # FIXME: implement storage reporting for all missing storage types.
782 _STORAGE_TYPE_INFO_FN = {
783 constants.ST_BLOCK: None,
784 constants.ST_DISKLESS: None,
785 constants.ST_EXT: None,
786 constants.ST_FILE: _GetFileStorageSpaceInfo,
787 constants.ST_LVM_PV: _GetLvmPvSpaceInfo,
788 constants.ST_LVM_VG: _GetLvmVgSpaceInfo,
789 constants.ST_SHARED_FILE: None,
790 constants.ST_GLUSTER: None,
791 constants.ST_RADOS: None,
792 }
793
794
795 def _ApplyStorageInfoFunction(storage_type, storage_key, *args):
796 """Looks up and applies the correct function to calculate free and total
797 storage for the given storage type.
798
799 @type storage_type: string
800 @param storage_type: the storage type for which the storage shall be reported.
801 @type storage_key: string
802 @param storage_key: identifier of a storage unit, e.g. the volume group name
803 of an LVM storage unit
804 @type args: any
805 @param args: various parameters that can be used for storage reporting. These
806 parameters and their semantics vary from storage type to storage type and
807 are just propagated in this function.
808 @return: the results of the application of the storage space function (see
809 _STORAGE_TYPE_INFO_FN) if storage space reporting is implemented for that
810 storage type
811 @raises NotImplementedError: for storage types who don't support space
812 reporting yet
813 """
814 fn = _STORAGE_TYPE_INFO_FN[storage_type]
815 if fn is not None:
816 return fn(storage_key, *args)
817 else:
818 raise NotImplementedError
819
820
821 def _CheckExclusivePvs(pvi_list):
822 """Check that PVs are not shared among LVs
823
824 @type pvi_list: list of L{objects.LvmPvInfo} objects
825 @param pvi_list: information about the PVs
826
827 @rtype: list of tuples (string, list of strings)
828 @return: offending volumes, as tuples: (pv_name, [lv1_name, lv2_name...])
829
830 """
831 res = []
832 for pvi in pvi_list:
833 if len(pvi.lv_list) > 1:
834 res.append((pvi.name, pvi.lv_list))
835 return res
836
837
838 def _VerifyHypervisors(what, vm_capable, result, all_hvparams,
839 get_hv_fn=hypervisor.GetHypervisor):
840 """Verifies the hypervisor. Appends the results to the 'results' list.
841
842 @type what: C{dict}
843 @param what: a dictionary of things to check
844 @type vm_capable: boolean
845 @param vm_capable: whether or not this node is vm capable
846 @type result: dict
847 @param result: dictionary of verification results; results of the
848 verifications in this function will be added here
849 @type all_hvparams: dict of dict of string
850 @param all_hvparams: dictionary mapping hypervisor names to hvparams
851 @type get_hv_fn: function
852 @param get_hv_fn: function to retrieve the hypervisor, to improve testability
853
854 """
855 if not vm_capable:
856 return
857
858 if constants.NV_HYPERVISOR in what:
859 result[constants.NV_HYPERVISOR] = {}
860 for hv_name in what[constants.NV_HYPERVISOR]:
861 hvparams = all_hvparams[hv_name]
862 try:
863 val = get_hv_fn(hv_name).Verify(hvparams=hvparams)
864 except errors.HypervisorError, err:
865 val = "Error while checking hypervisor: %s" % str(err)
866 result[constants.NV_HYPERVISOR][hv_name] = val
867
868
869 def _VerifyHvparams(what, vm_capable, result,
870 get_hv_fn=hypervisor.GetHypervisor):
871 """Verifies the hvparams. Appends the results to the 'results' list.
872
873 @type what: C{dict}
874 @param what: a dictionary of things to check
875 @type vm_capable: boolean
876 @param vm_capable: whether or not this node is vm capable
877 @type result: dict
878 @param result: dictionary of verification results; results of the
879 verifications in this function will be added here
880 @type get_hv_fn: function
881 @param get_hv_fn: function to retrieve the hypervisor, to improve testability
882
883 """
884 if not vm_capable:
885 return
886
887 if constants.NV_HVPARAMS in what:
888 result[constants.NV_HVPARAMS] = []
889 for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
890 try:
891 logging.info("Validating hv %s, %s", hv_name, hvparms)
892 get_hv_fn(hv_name).ValidateParameters(hvparms)
893 except errors.HypervisorError, err:
894 result[constants.NV_HVPARAMS].append((source, hv_name, str(err)))
895
896
897 def _VerifyInstanceList(what, vm_capable, result, all_hvparams):
898 """Verifies the instance list.
899
900 @type what: C{dict}
901 @param what: a dictionary of things to check
902 @type vm_capable: boolean
903 @param vm_capable: whether or not this node is vm capable
904 @type result: dict
905 @param result: dictionary of verification results; results of the
906 verifications in this function will be added here
907 @type all_hvparams: dict of dict of string
908 @param all_hvparams: dictionary mapping hypervisor names to hvparams
909
910 """
911 if constants.NV_INSTANCELIST in what and vm_capable:
912 # GetInstanceList can fail
913 try:
914 val = GetInstanceList(what[constants.NV_INSTANCELIST],
915 all_hvparams=all_hvparams)
916 except RPCFail, err:
917 val = str(err)
918 result[constants.NV_INSTANCELIST] = val
919
920
921 def _VerifyNodeInfo(what, vm_capable, result, all_hvparams):
922 """Verifies the node info.
923
924 @type what: C{dict}
925 @param what: a dictionary of things to check
926 @type vm_capable: boolean
927 @param vm_capable: whether or not this node is vm capable
928 @type result: dict
929 @param result: dictionary of verification results; results of the
930 verifications in this function will be added here
931 @type all_hvparams: dict of dict of string
932 @param all_hvparams: dictionary mapping hypervisor names to hvparams
933
934 """
935 if constants.NV_HVINFO in what and vm_capable:
936 hvname = what[constants.NV_HVINFO]
937 hyper = hypervisor.GetHypervisor(hvname)
938 hvparams = all_hvparams[hvname]
939 result[constants.NV_HVINFO] = hyper.GetNodeInfo(hvparams=hvparams)
940
941
942 def _VerifyClientCertificate(cert_file=pathutils.NODED_CLIENT_CERT_FILE):
943 """Verify the existance and validity of the client SSL certificate.
944
945 Also, verify that the client certificate is not self-signed. Self-
946 signed client certificates stem from Ganeti versions 2.12.0 - 2.12.4
947 and should be replaced by client certificates signed by the server
948 certificate. Hence we output a warning when we encounter a self-signed
949 one.
950
951 """
952 create_cert_cmd = "gnt-cluster renew-crypto --new-node-certificates"
953 if not os.path.exists(cert_file):
954 return (constants.CV_ERROR,
955 "The client certificate does not exist. Run '%s' to create"
956 " client certificates for all nodes." % create_cert_cmd)
957
958 (errcode, msg) = utils.VerifyCertificate(cert_file)
959 if errcode is not None:
960 return (errcode, msg)
961
962 (errcode, msg) = utils.IsCertificateSelfSigned(cert_file)
963 if errcode is not None:
964 return (errcode, msg)
965
966 # if everything is fine, we return the digest to be compared to the config
967 return (None, utils.GetCertificateDigest(cert_filename=cert_file))
968
969
970 def _VerifySshSetup(node_status_list, my_name, ssh_key_type,
971 ganeti_pub_keys_file=pathutils.SSH_PUB_KEYS):
972 """Verifies the state of the SSH key files.
973
974 @type node_status_list: list of tuples
975 @param node_status_list: list of nodes of the cluster associated with a
976 couple of flags: (uuid, name, is_master_candidate,
977 is_potential_master_candidate, online)
978 @type my_name: str
979 @param my_name: name of this node
980 @type ssh_key_type: one of L{constants.SSHK_ALL}
981 @param ssh_key_type: type of key used on nodes
982 @type ganeti_pub_keys_file: str
983 @param ganeti_pub_keys_file: filename of the public keys file
984
985 """
986 if node_status_list is None:
987 return ["No node list to check against the pub_key_file received."]
988
989 my_status_list = [(my_uuid, name, mc, pot_mc, online) for
990 (my_uuid, name, mc, pot_mc, online)
991 in node_status_list if name == my_name]
992 if len(my_status_list) == 0:
993 return ["Cannot find node information for node '%s'." % my_name]
994 (my_uuid, _, _, potential_master_candidate, online) = \
995 my_status_list[0]
996
997 result = []
998
999 if not os.path.exists(ganeti_pub_keys_file):
1000 result.append("The public key file '%s' does not exist. Consider running"
1001 " 'gnt-cluster renew-crypto --new-ssh-keys"
1002 " [--no-ssh-key-check]' to fix this." % ganeti_pub_keys_file)
1003 return result
1004
1005 pot_mc_uuids = [uuid for (uuid, _, _, _, _) in node_status_list]
1006 offline_nodes = [uuid for (uuid, _, _, _, online) in node_status_list
1007 if not online]
1008 pub_keys = ssh.QueryPubKeyFile(None, key_file=ganeti_pub_keys_file)
1009
1010 if potential_master_candidate:
1011 # Check that the set of potential master candidates matches the
1012 # public key file
1013 pub_uuids_set = set(pub_keys.keys()) - set(offline_nodes)
1014 pot_mc_uuids_set = set(pot_mc_uuids) - set(offline_nodes)
1015 missing_uuids = set([])
1016 if pub_uuids_set != pot_mc_uuids_set:
1017 unknown_uuids = pub_uuids_set - pot_mc_uuids_set
1018 if unknown_uuids:
1019 result.append("The following node UUIDs are listed in the public key"
1020 " file on node '%s', but are not potential master"
1021 " candidates: %s."
1022 % (my_name, ", ".join(list(unknown_uuids))))
1023 missing_uuids = pot_mc_uuids_set - pub_uuids_set
1024 if missing_uuids:
1025 result.append("The following node UUIDs of potential master candidates"
1026 " are missing in the public key file on node %s: %s."
1027 % (my_name, ", ".join(list(missing_uuids))))
1028
1029 (_, key_files) = \
1030 ssh.GetAllUserFiles(constants.SSH_LOGIN_USER, mkdir=False, dircheck=False)
1031 (_, node_pub_key_file) = key_files[ssh_key_type]
1032
1033 my_keys = pub_keys[my_uuid]
1034
1035 node_pub_key = utils.ReadFile(node_pub_key_file)
1036 if node_pub_key.strip() not in my_keys:
1037 result.append("The dsa key of node %s does not match this node's key"
1038 " in the pub key file." % my_name)
1039 if len(my_keys) != 1:
1040 result.append("There is more than one key for node %s in the public key"
1041 " file." % my_name)
1042 else:
1043 if len(pub_keys.keys()) > 0:
1044 result.append("The public key file of node '%s' is not empty, although"
1045 " the node is not a potential master candidate."
1046 % my_name)
1047
1048 # Check that all master candidate keys are in the authorized_keys file
1049 (auth_key_file, _) = \
1050 ssh.GetAllUserFiles(constants.SSH_LOGIN_USER, mkdir=False, dircheck=False)
1051 for (uuid, name, mc, _, online) in node_status_list:
1052 if not online:
1053 continue
1054 if uuid in missing_uuids:
1055 continue
1056 if mc:
1057 for key in pub_keys[uuid]:
1058 if not ssh.HasAuthorizedKey(auth_key_file, key):
1059 result.append("A SSH key of master candidate '%s' (UUID: '%s') is"
1060 " not in the 'authorized_keys' file of node '%s'."
1061 % (name, uuid, my_name))
1062 else:
1063 for key in pub_keys[uuid]:
1064 if name != my_name and ssh.HasAuthorizedKey(auth_key_file, key):
1065 result.append("A SSH key of normal node '%s' (UUID: '%s') is in the"
1066 " 'authorized_keys' file of node '%s'."
1067 % (name, uuid, my_name))
1068 if name == my_name and not ssh.HasAuthorizedKey(auth_key_file, key):
1069 result.append("A SSH key of normal node '%s' (UUID: '%s') is not"
1070 " in the 'authorized_keys' file of itself."
1071 % (my_name, uuid))
1072
1073 return result
1074
1075
1076 def _VerifySshClutter(node_status_list, my_name):
1077 """Verifies that the 'authorized_keys' files are not cluttered up.
1078
1079 @type node_status_list: list of tuples
1080 @param node_status_list: list of nodes of the cluster associated with a
1081 couple of flags: (uuid, name, is_master_candidate,
1082 is_potential_master_candidate, online)
1083 @type my_name: str
1084 @param my_name: name of this node
1085
1086 """
1087 result = []
1088 (auth_key_file, _) = \
1089 ssh.GetAllUserFiles(constants.SSH_LOGIN_USER, mkdir=False, dircheck=False)
1090 node_names = [name for (_, name, _, _) in node_status_list]
1091 multiple_occurrences = ssh.CheckForMultipleKeys(auth_key_file, node_names)
1092 if multiple_occurrences:
1093 msg = "There are hosts which have more than one SSH key stored for the" \
1094 " same user in the 'authorized_keys' file of node %s. This can be" \
1095 " due to an unsuccessful operation which cluttered up the" \
1096 " 'authorized_keys' file. We recommend to clean this up manually. " \
1097 % my_name
1098 for host, occ in multiple_occurrences.items():
1099 msg += "Entry for '%s' in lines %s. " % (host, utils.CommaJoin(occ))
1100 result.append(msg)
1101
1102 return result
1103
1104
1105 def VerifyNode(what, cluster_name, all_hvparams):
1106 """Verify the status of the local node.
1107
1108 Based on the input L{what} parameter, various checks are done on the
1109 local node.
1110
1111 If the I{filelist} key is present, this list of
1112 files is checksummed and the file/checksum pairs are returned.
1113
1114 If the I{nodelist} key is present, we check that we have
1115 connectivity via ssh with the target nodes (and check the hostname
1116 report).
1117
1118 If the I{node-net-test} key is present, we check that we have
1119 connectivity to the given nodes via both primary IP and, if
1120 applicable, secondary IPs.
1121
1122 @type what: C{dict}
1123 @param what: a dictionary of things to check:
1124 - filelist: list of files for which to compute checksums
1125 - nodelist: list of nodes we should check ssh communication with
1126 - node-net-test: list of nodes we should check node daemon port
1127 connectivity with
1128 - hypervisor: list with hypervisors to run the verify for
1129 @type cluster_name: string
1130 @param cluster_name: the cluster's name
1131 @type all_hvparams: dict of dict of strings
1132 @param all_hvparams: a dictionary mapping hypervisor names to hvparams
1133 @rtype: dict
1134 @return: a dictionary with the same keys as the input dict, and
1135 values representing the result of the checks
1136
1137 """
1138 result = {}
1139 my_name = netutils.Hostname.GetSysName()
1140 port = netutils.GetDaemonPort(constants.NODED)
1141 vm_capable = my_name not in what.get(constants.NV_NONVMNODES, [])
1142
1143 _VerifyHypervisors(what, vm_capable, result, all_hvparams)
1144 _VerifyHvparams(what, vm_capable, result)
1145
1146 if constants.NV_FILELIST in what:
1147 fingerprints = utils.FingerprintFiles(map(vcluster.LocalizeVirtualPath,
1148 what[constants.NV_FILELIST]))
1149 result[constants.NV_FILELIST] = \
1150 dict((vcluster.MakeVirtualPath(key), value)
1151 for (key, value) in fingerprints.items())
1152
1153 if constants.NV_CLIENT_CERT in what:
1154 result[constants.NV_CLIENT_CERT] = _VerifyClientCertificate()
1155
1156 if constants.NV_SSH_SETUP in what:
1157 node_status_list, key_type = what[constants.NV_SSH_SETUP]
1158 result[constants.NV_SSH_SETUP] = \
1159 _VerifySshSetup(node_status_list, my_name, key_type)
1160 if constants.NV_SSH_CLUTTER in what:
1161 result[constants.NV_SSH_CLUTTER] = \
1162 _VerifySshClutter(what[constants.NV_SSH_SETUP], my_name)
1163
1164 if constants.NV_NODELIST in what:
1165 (nodes, bynode, mcs) = what[constants.NV_NODELIST]
1166
1167 # Add nodes from other groups (different for each node)
1168 try:
1169 nodes.extend(bynode[my_name])
1170 except KeyError:
1171 pass
1172
1173 # Use a random order
1174 random.shuffle(nodes)
1175
1176 # Try to contact all nodes
1177 val = {}
1178 ssh_port_map = ssconf.SimpleStore().GetSshPortMap()
1179 for node in nodes:
1180 # We only test if master candidates can communicate to other nodes.
1181 # We cannot test if normal nodes cannot communicate with other nodes,
1182 # because the administrator might have installed additional SSH keys,
1183 # over which Ganeti has no power.
1184 if my_name in mcs:
1185 success, message = _GetSshRunner(cluster_name). \
1186 VerifyNodeHostname(node, ssh_port_map[node])
1187 if not success:
1188 val[node] = message
1189
1190 result[constants.NV_NODELIST] = val
1191
1192 if constants.NV_NODENETTEST in what:
1193 result[constants.NV_NODENETTEST] = tmp = {}
1194 my_pip = my_sip = None
1195 for name, pip, sip in what[constants.NV_NODENETTEST]:
1196 if name == my_name:
1197 my_pip = pip
1198 my_sip = sip
1199 break
1200 if not my_pip:
1201 tmp[my_name] = ("Can't find my own primary/secondary IP"
1202 " in the node list")
1203 else:
1204 for name, pip, sip in what[constants.NV_NODENETTEST]:
1205 fail = []
1206 if not netutils.TcpPing(pip, port, source=my_pip):
1207 fail.append("primary")
1208 if sip != pip:
1209 if not netutils.TcpPing(sip, port, source=my_sip):
1210 fail.append("secondary")
1211 if fail:
1212 tmp[name] = ("failure using the %s interface(s)" %
1213 " and ".join(fail))
1214
1215 if constants.NV_MASTERIP in what:
1216 # FIXME: add checks on incoming data structures (here and in the
1217 # rest of the function)
1218 master_name, master_ip = what[constants.NV_MASTERIP]
1219 if master_name == my_name:
1220 source = constants.IP4_ADDRESS_LOCALHOST
1221 else:
1222 source = None
1223 result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
1224 source=source)
1225
1226 if constants.NV_USERSCRIPTS in what:
1227 result[constants.NV_USERSCRIPTS] = \
1228 [script for script in what[constants.NV_USERSCRIPTS]
1229 if not utils.IsExecutable(script)]
1230
1231 if constants.NV_OOB_PATHS in what:
1232 result[constants.NV_OOB_PATHS] = tmp = []
1233 for path in what[constants.NV_OOB_PATHS]:
1234 try:
1235 st = os.stat(path)
1236 except OSError, err:
1237 tmp.append("error stating out of band helper: %s" % err)
1238 else:
1239 if stat.S_ISREG(st.st_mode):
1240 if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
1241 tmp.append(None)
1242 else:
1243 tmp.append("out of band helper %s is not executable" % path)
1244 else:
1245 tmp.append("out of band helper %s is not a file" % path)
1246
1247 if constants.NV_LVLIST in what and vm_capable:
1248 try:
1249 val = GetVolumeList(utils.ListVolumeGroups().keys())
1250 except RPCFail, err:
1251 val = str(err)
1252 result[constants.NV_LVLIST] = val
1253
1254 _VerifyInstanceList(what, vm_capable, result, all_hvparams)
1255
1256 if constants.NV_VGLIST in what and vm_capable:
1257 result[constants.NV_VGLIST] = utils.ListVolumeGroups()
1258
1259 if constants.NV_PVLIST in what and vm_capable:
1260 check_exclusive_pvs = constants.NV_EXCLUSIVEPVS in what
1261 val = bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
1262 filter_allocatable=False,
1263 include_lvs=check_exclusive_pvs)
1264 if check_exclusive_pvs:
1265 result[constants.NV_EXCLUSIVEPVS] = _CheckExclusivePvs(val)
1266 for pvi in val:
1267 # Avoid sending useless data on the wire
1268 pvi.lv_list = []
1269 result[constants.NV_PVLIST] = map(objects.LvmPvInfo.ToDict, val)
1270
1271 if constants.NV_VERSION in what:
1272 result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
1273 constants.RELEASE_VERSION)
1274
1275 _VerifyNodeInfo(what, vm_capable, result, all_hvparams)
1276
1277 if constants.NV_DRBDVERSION in what and vm_capable:
1278 try:
1279 drbd_version = DRBD8.GetProcInfo().GetVersionString()
1280 except errors.BlockDeviceError, err:
1281 logging.warning("Can't get DRBD version", exc_info=True)
1282 drbd_version = str(err)
1283 result[constants.NV_DRBDVERSION] = drbd_version
1284
1285 if constants.NV_DRBDLIST in what and vm_capable:
1286 try:
1287 used_minors = drbd.DRBD8.GetUsedDevs()
1288 except errors.BlockDeviceError, err:
1289 logging.warning("Can't get used minors list", exc_info=True)
1290 used_minors = str(err)
1291 result[constants.NV_DRBDLIST] = used_minors
1292
1293 if constants.NV_DRBDHELPER in what and vm_capable:
1294 status = True
1295 try:
1296 payload = drbd.DRBD8.GetUsermodeHelper()
1297 except errors.BlockDeviceError, err:
1298 logging.error("Can't get DRBD usermode helper: %s", str(err))
1299 status = False
1300 payload = str(err)
1301 result[constants.NV_DRBDHELPER] = (status, payload)
1302
1303 if constants.NV_NODESETUP in what:
1304 result[constants.NV_NODESETUP] = tmpr = []
1305 if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
1306 tmpr.append("The sysfs filesytem doesn't seem to be mounted"
1307 " under /sys, missing required directories /sys/block"
1308 " and /sys/class/net")
1309 if (not os.path.isdir("/proc/sys") or
1310 not os.path.isfile("/proc/sysrq-trigger")):
1311 tmpr.append("The procfs filesystem doesn't seem to be mounted"
1312 " under /proc, missing required directory /proc/sys and"
1313 " the file /proc/sysrq-trigger")
1314
1315 if constants.NV_TIME in what:
1316 result[constants.NV_TIME] = utils.SplitTime(time.time())
1317
1318 if constants.NV_OSLIST in what and vm_capable:
1319 result[constants.NV_OSLIST] = DiagnoseOS()
1320
1321 if constants.NV_BRIDGES in what and vm_capable:
1322 result[constants.NV_BRIDGES] = [bridge
1323 for bridge in what[constants.NV_BRIDGES]
1324 if not utils.BridgeExists(bridge)]
1325
1326 if what.get(constants.NV_ACCEPTED_STORAGE_PATHS) == my_name:
1327 result[constants.NV_ACCEPTED_STORAGE_PATHS] = \
1328 filestorage.ComputeWrongFileStoragePaths()
1329
1330 if what.get(constants.NV_FILE_STORAGE_PATH):
1331 pathresult = filestorage.CheckFileStoragePath(
1332 what[constants.NV_FILE_STORAGE_PATH])
1333 if pathresult:
1334 result[constants.NV_FILE_STORAGE_PATH] = pathresult
1335
1336 if what.get(constants.NV_SHARED_FILE_STORAGE_PATH):
1337 pathresult = filestorage.CheckFileStoragePath(
1338 what[constants.NV_SHARED_FILE_STORAGE_PATH])
1339 if pathresult:
1340 result[constants.NV_SHARED_FILE_STORAGE_PATH] = pathresult
1341
1342 return result
1343
1344
1345 def GetCryptoTokens(token_requests):
1346 """Perform actions on the node's cryptographic tokens.
1347
1348 Token types can be 'ssl' or 'ssh'. So far only some actions are implemented
1349 for 'ssl'. Action 'get' returns the digest of the public client ssl
1350 certificate. Action 'create' creates a new client certificate and private key
1351 and also returns the digest of the certificate. The third parameter of a
1352 token request are optional parameters for the actions, so far only the
1353 filename is supported.
1354
1355 @type token_requests: list of tuples of (string, string, dict), where the
1356 first string is in constants.CRYPTO_TYPES, the second in
1357 constants.CRYPTO_ACTIONS. The third parameter is a dictionary of string
1358 to string.
1359 @param token_requests: list of requests of cryptographic tokens and actions
1360 to perform on them. The actions come with a dictionary of options.
1361 @rtype: list of tuples (string, string)
1362 @return: list of tuples of the token type and the public crypto token
1363
1364 """
1365 tokens = []
1366 for (token_type, action, _) in token_requests:
1367 if token_type not in constants.CRYPTO_TYPES:
1368 raise errors.ProgrammerError("Token type '%s' not supported." %
1369 token_type)
1370 if action not in constants.CRYPTO_ACTIONS:
1371 raise errors.ProgrammerError("Action '%s' is not supported." %
1372 action)
1373 if token_type == constants.CRYPTO_TYPE_SSL_DIGEST:
1374 tokens.append((token_type,
1375 utils.GetCertificateDigest()))
1376 return tokens
1377
1378
1379 def EnsureDaemon(daemon_name, run):
1380 """Ensures the given daemon is running or stopped.
1381
1382 @type daemon_name: string
1383 @param daemon_name: name of the daemon (e.g., constants.KVMD)
1384
1385 @type run: bool
1386 @param run: whether to start or stop the daemon
1387
1388 @rtype: bool
1389 @return: 'True' if daemon successfully started/stopped,
1390 'False' otherwise
1391
1392 """
1393 allowed_daemons = [constants.KVMD]
1394
1395 if daemon_name not in allowed_daemons:
1396 fn = lambda _: False
1397 elif run:
1398 fn = utils.EnsureDaemon
1399 else:
1400 fn = utils.StopDaemon
1401
1402 return fn(daemon_name)
1403
1404
1405 def _InitSshUpdateData(data, noded_cert_file, ssconf_store):
1406 (_, noded_cert) = \
1407 utils.ExtractX509Certificate(utils.ReadFile(noded_cert_file))
1408 data[constants.SSHS_NODE_DAEMON_CERTIFICATE] = noded_cert
1409
1410 cluster_name = ssconf_store.GetClusterName()
1411 data[constants.SSHS_CLUSTER_NAME] = cluster_name
1412
1413
1414 def AddNodeSshKey(node_uuid, node_name,
1415 potential_master_candidates,
1416 to_authorized_keys=False,
1417 to_public_keys=False,
1418 get_public_keys=False,
1419 pub_key_file=pathutils.SSH_PUB_KEYS,
1420 ssconf_store=None,
1421 noded_cert_file=pathutils.NODED_CERT_FILE,
1422 run_cmd_fn=ssh.RunSshCmdWithStdin,
1423 ssh_update_debug=False,
1424 ssh_update_verbose=False):
1425 """Distributes a node's public SSH key across the cluster.
1426
1427 Note that this function should only be executed on the master node, which
1428 then will copy the new node's key to all nodes in the cluster via SSH.
1429
1430 Also note: at least one of the flags C{to_authorized_keys},
1431 C{to_public_keys}, and C{get_public_keys} has to be set to C{True} for
1432 the function to actually perform any actions.
1433
1434 @type node_uuid: str
1435 @param node_uuid: the UUID of the node whose key is added
1436 @type node_name: str
1437 @param node_name: the name of the node whose key is added
1438 @type potential_master_candidates: list of str
1439 @param potential_master_candidates: list of node names of potential master
1440 candidates; this should match the list of uuids in the public key file
1441 @type to_authorized_keys: boolean
1442 @param to_authorized_keys: whether the key should be added to the
1443 C{authorized_keys} file of all nodes
1444 @type to_public_keys: boolean
1445 @param to_public_keys: whether the keys should be added to the public key file
1446 @type get_public_keys: boolean
1447 @param get_public_keys: whether the node should add the clusters' public keys
1448 to its {ganeti_pub_keys} file
1449
1450 """
1451 node_list = [SshAddNodeInfo(name=node_name, uuid=node_uuid,
1452 to_authorized_keys=to_authorized_keys,
1453 to_public_keys=to_public_keys,
1454 get_public_keys=get_public_keys)]
1455 return AddNodeSshKeyBulk(node_list,
1456 potential_master_candidates,
1457 pub_key_file=pub_key_file,
1458 ssconf_store=ssconf_store,
1459 noded_cert_file=noded_cert_file,
1460 run_cmd_fn=run_cmd_fn,
1461 ssh_update_debug=ssh_update_debug,
1462 ssh_update_verbose=ssh_update_verbose)
1463
1464
1465 # Node info named tuple specifically for the use with AddNodeSshKeyBulk
1466 SshAddNodeInfo = collections.namedtuple(
1467 "SshAddNodeInfo",
1468 ["uuid",
1469 "name",
1470 "to_authorized_keys",
1471 "to_public_keys",
1472 "get_public_keys"])
1473
1474
1475 def AddNodeSshKeyBulk(node_list,
1476 potential_master_candidates,
1477 pub_key_file=pathutils.SSH_PUB_KEYS,
1478 ssconf_store=None,
1479 noded_cert_file=pathutils.NODED_CERT_FILE,
1480 run_cmd_fn=ssh.RunSshCmdWithStdin,
1481 ssh_update_debug=False,
1482 ssh_update_verbose=False):
1483 """Distributes a node's public SSH key across the cluster.
1484
1485 Note that this function should only be executed on the master node, which
1486 then will copy the new node's key to all nodes in the cluster via SSH.
1487
1488 Also note: at least one of the flags C{to_authorized_keys},
1489 C{to_public_keys}, and C{get_public_keys} has to be set to C{True} for
1490 the function to actually perform any actions.
1491
1492 @type node_list: list of SshAddNodeInfo tuples
1493 @param node_list: list of tuples containing the necessary node information for
1494 adding their keys
1495 @type potential_master_candidates: list of str
1496 @param potential_master_candidates: list of node names of potential master
1497 candidates; this should match the list of uuids in the public key file
1498
1499 """
1500 # whether there are any keys to be added or retrieved at all
1501 to_authorized_keys = any([node_info.to_authorized_keys for node_info in
1502 node_list])
1503 to_public_keys = any([node_info.to_public_keys for node_info in
1504 node_list])
1505
1506 if not ssconf_store:
1507 ssconf_store = ssconf.SimpleStore()
1508
1509 for node_info in node_list:
1510 # replacement not necessary for keys that are not supposed to be in the
1511 # list of public keys
1512 if not node_info.to_public_keys:
1513 continue
1514 # Check and fix sanity of key file
1515 keys_by_name = ssh.QueryPubKeyFile([node_info.name], key_file=pub_key_file)
1516 keys_by_uuid = ssh.QueryPubKeyFile([node_info.uuid], key_file=pub_key_file)
1517
1518 if (not keys_by_name or node_info.name not in keys_by_name) \
1519 and (not keys_by_uuid or node_info.uuid not in keys_by_uuid):
1520 raise errors.SshUpdateError(
1521 "No keys found for the new node '%s' (UUID %s) in the list of public"
1522 " SSH keys, neither for the name or the UUID" %
1523 (node_info.name, node_info.uuid))
1524 else:
1525 if node_info.name in keys_by_name:
1526 # Replace the name by UUID in the file as the name should only be used
1527 # temporarily
1528 ssh.ReplaceNameByUuid(node_info.uuid, node_info.name,
1529 error_fn=errors.SshUpdateError,
1530 key_file=pub_key_file)
1531
1532 # Retrieve updated map of UUIDs to keys
1533 keys_by_uuid = ssh.QueryPubKeyFile(
1534 [node_info.uuid for node_info in node_list], key_file=pub_key_file)
1535
1536 # Update the master node's key files
1537 (auth_key_file, _) = \
1538 ssh.GetAllUserFiles(constants.SSH_LOGIN_USER, mkdir=False, dircheck=False)
1539 for node_info in node_list:
1540 if node_info.to_authorized_keys:
1541 ssh.AddAuthorizedKeys(auth_key_file, keys_by_uuid[node_info.uuid])
1542
1543 base_data = {}
1544 _InitSshUpdateData(base_data, noded_cert_file, ssconf_store)
1545 cluster_name = base_data[constants.SSHS_CLUSTER_NAME]
1546
1547 ssh_port_map = ssconf_store.GetSshPortMap()
1548
1549 # Update the target nodes themselves
1550 for node_info in node_list:
1551 logging.debug("Updating SSH key files of target node '%s'.", node_info.name)
1552 if node_info.get_public_keys:
1553 node_data = {}
1554 _InitSshUpdateData(node_data, noded_cert_file, ssconf_store)
1555 all_keys = ssh.QueryPubKeyFile(None, key_file=pub_key_file)
1556 node_data[constants.SSHS_SSH_PUBLIC_KEYS] = \
1557 (constants.SSHS_OVERRIDE, all_keys)
1558
1559 try:
1560 utils.RetryByNumberOfTimes(
1561 constants.SSHS_MAX_RETRIES,
1562 errors.SshUpdateError,
1563 run_cmd_fn, cluster_name, node_info.name, pathutils.SSH_UPDATE,
1564 ssh_port_map.get(node_info.name), node_data,
1565 debug=ssh_update_debug, verbose=ssh_update_verbose,
1566 use_cluster_key=False, ask_key=False, strict_host_check=False)
1567 except errors.SshUpdateError as e:
1568 # Clean up the master's public key file if adding key fails
1569 if node_info.to_public_keys:
1570 ssh.RemovePublicKey(node_info.uuid)
1571 raise e
1572
1573 # Update all nodes except master and the target nodes
1574 keys_by_uuid_auth = ssh.QueryPubKeyFile(
1575 [node_info.uuid for node_info in node_list
1576 if node_info.to_authorized_keys],
1577 key_file=pub_key_file)
1578 if to_authorized_keys:
1579 base_data[constants.SSHS_SSH_AUTHORIZED_KEYS] = \
1580 (constants.SSHS_ADD, keys_by_uuid_auth)
1581
1582 pot_mc_data = base_data.copy()
1583 keys_by_uuid_pub = ssh.QueryPubKeyFile(
1584 [node_info.uuid for node_info in node_list
1585 if node_info.to_public_keys],
1586 key_file=pub_key_file)
1587 if to_public_keys:
1588 pot_mc_data[constants.SSHS_SSH_PUBLIC_KEYS] = \
1589 (constants.SSHS_REPLACE_OR_ADD, keys_by_uuid_pub)
1590
1591 all_nodes = ssconf_store.GetNodeList()
1592 master_node = ssconf_store.GetMasterNode()
1593 online_nodes = ssconf_store.GetOnlineNodeList()
1594
1595 node_errors = []
1596 for node in all_nodes:
1597 if node == master_node:
1598 logging.debug("Skipping master node '%s'.", master_node)
1599 continue
1600 if node not in online_nodes:
1601 logging.debug("Skipping offline node '%s'.", node)
1602 continue
1603 if node in potential_master_candidates:
1604 logging.debug("Updating SSH key files of node '%s'.", node)
1605 try:
1606 utils.RetryByNumberOfTimes(
1607 constants.SSHS_MAX_RETRIES,
1608 errors.SshUpdateError,
1609 run_cmd_fn, cluster_name, node, pathutils.SSH_UPDATE,
1610 ssh_port_map.get(node), pot_mc_data,
1611 debug=ssh_update_debug, verbose=ssh_update_verbose,
1612 use_cluster_key=False, ask_key=False, strict_host_check=False)
1613 except errors.SshUpdateError as last_exception:
1614 error_msg = ("When adding the key of node '%s', updating SSH key"
1615 " files of node '%s' failed after %s retries."
1616 " Not trying again. Last error was: %s." %
1617 (node, node_info.name, constants.SSHS_MAX_RETRIES,
1618 last_exception))
1619 node_errors.append((node, error_msg))
1620 # We only log the error and don't throw an exception, because
1621 # one unreachable node shall not abort the entire procedure.
1622 logging.error(error_msg)
1623
1624 else:
1625 if to_authorized_keys:
1626 run_cmd_fn(cluster_name, node, pathutils.SSH_UPDATE,
1627 ssh_port_map.get(node), base_data,
1628 debug=ssh_update_debug, verbose=ssh_update_verbose,
1629 use_cluster_key=False, ask_key=False,
1630 strict_host_check=False)
1631
1632 return node_errors
1633
1634
1635 # TODO: will be fixed with pending patch series.
1636 # pylint: disable=R0913
1637 def RemoveNodeSshKey(node_uuid, node_name,
1638 master_candidate_uuids,
1639 potential_master_candidates,
1640 master_uuid=None,
1641 keys_to_remove=None,
1642 from_authorized_keys=False,
1643 from_public_keys=False,
1644 clear_authorized_keys=False,
1645 clear_public_keys=False,
1646 pub_key_file=pathutils.SSH_PUB_KEYS,
1647 ssconf_store=None,
1648 noded_cert_file=pathutils.NODED_CERT_FILE,
1649 readd=False,
1650 run_cmd_fn=ssh.RunSshCmdWithStdin,
1651 ssh_update_debug=False,
1652 ssh_update_verbose=False):
1653 """Removes the node's SSH keys from the key files and distributes those.
1654
1655 Note that at least one of the flags C{from_authorized_keys},
1656 C{from_public_keys}, C{clear_authorized_keys}, and C{clear_public_keys}
1657 has to be set to C{True} for the function to perform any action at all.
1658 Not doing so will trigger an assertion in the function.
1659
1660 @type node_uuid: str
1661 @param node_uuid: UUID of the node whose key is removed
1662 @type node_name: str
1663 @param node_name: name of the node whose key is remove
1664 @type master_candidate_uuids: list of str
1665 @param master_candidate_uuids: list of UUIDs of the current master candidates
1666 @type potential_master_candidates: list of str
1667 @param potential_master_candidates: list of names of potential master
1668 candidates
1669 @type keys_to_remove: dict of str to list of str
1670 @param keys_to_remove: a dictionary mapping node UUIDS to lists of SSH keys
1671 to be removed. This list is supposed to be used only if the keys are not
1672 in the public keys file. This is for example the case when removing a
1673 master node's key.
1674 @type from_authorized_keys: boolean
1675 @param from_authorized_keys: whether or not the key should be removed
1676 from the C{authorized_keys} file
1677 @type from_public_keys: boolean
1678 @param from_public_keys: whether or not the key should be remove from
1679 the C{ganeti_pub_keys} file
1680 @type clear_authorized_keys: boolean
1681 @param clear_authorized_keys: whether or not the C{authorized_keys} file
1682 should be cleared on the node whose keys are removed
1683 @type clear_public_keys: boolean
1684 @param clear_public_keys: whether to clear the node's C{ganeti_pub_key} file
1685 @type readd: boolean
1686 @param readd: whether this is called during a readd operation.
1687 @rtype: list of string
1688 @returns: list of feedback messages
1689
1690 """
1691 node_list = [SshRemoveNodeInfo(uuid=node_uuid,
1692 name=node_name,
1693 from_authorized_keys=from_authorized_keys,
1694 from_public_keys=from_public_keys,
1695 clear_authorized_keys=clear_authorized_keys,
1696 clear_public_keys=clear_public_keys)]
1697 return RemoveNodeSshKeyBulk(node_list,
1698 master_candidate_uuids,
1699 potential_master_candidates,
1700 master_uuid=master_uuid,
1701 keys_to_remove=keys_to_remove,
1702 pub_key_file=pub_key_file,
1703 ssconf_store=ssconf_store,
1704 noded_cert_file=noded_cert_file,
1705 readd=readd,
1706 run_cmd_fn=run_cmd_fn,
1707 ssh_update_debug=ssh_update_debug,
1708 ssh_update_verbose=ssh_update_verbose)
1709
1710
1711 # Node info named tuple specifically for the use with RemoveNodeSshKeyBulk
1712 SshRemoveNodeInfo = collections.namedtuple(
1713 "SshRemoveNodeInfo",
1714 ["uuid",
1715 "name",
1716 "from_authorized_keys",
1717 "from_public_keys",
1718 "clear_authorized_keys",
1719 "clear_public_keys"])
1720
1721
1722 def RemoveNodeSshKeyBulk(node_list,
1723 master_candidate_uuids,
1724 potential_master_candidates,
1725 master_uuid=None,
1726 keys_to_remove=None,
1727 pub_key_file=pathutils.SSH_PUB_KEYS,
1728 ssconf_store=None,
1729 noded_cert_file=pathutils.NODED_CERT_FILE,
1730 readd=False,
1731 run_cmd_fn=ssh.RunSshCmdWithStdin,
1732 ssh_update_debug=False,
1733 ssh_update_verbose=False):
1734 """Removes the node's SSH keys from the key files and distributes those.
1735
1736 Note that at least one of the flags C{from_authorized_keys},
1737 C{from_public_keys}, C{clear_authorized_keys}, and C{clear_public_keys}
1738 of at least one node has to be set to C{True} for the function to perform any
1739 action at all. Not doing so will trigger an assertion in the function.
1740
1741 @type node_list: list of C{SshRemoveNodeInfo}.
1742 @param node_list: list of information about nodes whose keys are being removed
1743 @type master_candidate_uuids: list of str
1744 @param master_candidate_uuids: list of UUIDs of the current master candidates
1745 @type potential_master_candidates: list of str
1746 @param potential_master_candidates: list of names of potential master
1747 candidates
1748 @type keys_to_remove: dict of str to list of str
1749 @param keys_to_remove: a dictionary mapping node UUIDS to lists of SSH keys
1750 to be removed. This list is supposed to be used only if the keys are not
1751 in the public keys file. This is for example the case when removing a
1752 master node's key.
1753 @type readd: boolean
1754 @param readd: whether this is called during a readd operation.
1755 @rtype: list of string
1756 @returns: list of feedback messages
1757
1758 """
1759 # Non-disruptive error messages, list of (node, msg) pairs
1760 result_msgs = []
1761
1762 # whether there are any keys to be added or retrieved at all
1763 from_authorized_keys = any([node_info.from_authorized_keys for node_info in
1764 node_list])
1765 from_public_keys = any([node_info.from_public_keys for node_info in
1766 node_list])
1767 clear_authorized_keys = any([node_info.clear_authorized_keys for node_info in
1768 node_list])
1769 clear_public_keys = any([node_info.clear_public_keys for node_info in
1770 node_list])
1771
1772 # Make sure at least one of these flags is true.
1773 if not (from_authorized_keys or from_public_keys or clear_authorized_keys
1774 or clear_public_keys):
1775 raise errors.SshUpdateError("No removal from any key file was requested.")
1776
1777 if not ssconf_store:
1778 ssconf_store = ssconf.SimpleStore()
1779
1780 master_node = ssconf_store.GetMasterNode()
1781 ssh_port_map = ssconf_store.GetSshPortMap()
1782
1783 all_keys_to_remove = {}
1784 if from_authorized_keys or from_public_keys:
1785 for node_info in node_list:
1786 # Skip nodes that don't actually need any keys to be removed.
1787 if not (node_info.from_authorized_keys or node_info.from_public_keys):
1788 continue
1789 if node_info.name == master_node and not keys_to_remove:
1790 raise errors.SshUpdateError("Cannot remove the master node's keys.")
1791 if keys_to_remove:
1792 keys = keys_to_remove
1793 else:
1794 keys = ssh.QueryPubKeyFile([node_info.uuid], key_file=pub_key_file)
1795 if (not keys or node_info.uuid not in keys) and not readd:
1796 raise errors.SshUpdateError("Node '%s' not found in the list of"
1797 " public SSH keys. It seems someone"
1798 " tries to remove a key from outside"
1799 " the cluster!" % node_info.uuid)
1800 # During an upgrade all nodes have the master key. In this case we
1801 # should not remove it to avoid accidentally shutting down cluster
1802 # SSH communication
1803 master_keys = None
1804 if master_uuid:
1805 master_keys = ssh.QueryPubKeyFile([master_uuid],
1806 key_file=pub_key_file)
1807 for master_key in master_keys:
1808 if master_key in keys[node_info.uuid]:
1809 keys[node_info.uuid].remove(master_key)
1810
1811 all_keys_to_remove.update(keys)
1812
1813 if all_keys_to_remove:
1814 base_data = {}
1815 _InitSshUpdateData(base_data, noded_cert_file, ssconf_store)
1816 cluster_name = base_data[constants.SSHS_CLUSTER_NAME]
1817
1818 if from_authorized_keys:
1819 # UUIDs of nodes that are supposed to be removed from the
1820 # authorized_keys files.
1821 nodes_remove_from_authorized_keys = [
1822 node_info.uuid for node_info in node_list
1823 if node_info.from_authorized_keys]
1824 keys_to_remove_from_authorized_keys = dict([
1825 (uuid, keys) for (uuid, keys) in all_keys_to_remove.items()
1826 if uuid in nodes_remove_from_authorized_keys])
1827 base_data[constants.SSHS_SSH_AUTHORIZED_KEYS] = \
1828 (constants.SSHS_REMOVE, keys_to_remove_from_authorized_keys)
1829 (auth_key_file, _) = \
1830 ssh.GetAllUserFiles(constants.SSH_LOGIN_USER, mkdir=False,
1831 dircheck=False)
1832
1833 for uuid in nodes_remove_from_authorized_keys:
1834 ssh.RemoveAuthorizedKeys(auth_key_file,
1835 keys_to_remove_from_authorized_keys[uuid])
1836
1837 pot_mc_data = base_data.copy()
1838
1839 if from_public_keys:
1840 nodes_remove_from_public_keys = [
1841 node_info.uuid for node_info in node_list
1842 if node_info.from_public_keys]
1843 keys_to_remove_from_public_keys = dict([
1844 (uuid, keys) for (uuid, keys) in all_keys_to_remove.items()
1845 if uuid in nodes_remove_from_public_keys])
1846 pot_mc_data[constants.SSHS_SSH_PUBLIC_KEYS] = \
1847 (constants.SSHS_REMOVE, keys_to_remove_from_public_keys)
1848
1849 all_nodes = ssconf_store.GetNodeList()
1850 online_nodes = ssconf_store.GetOnlineNodeList()
1851 all_nodes_to_remove = [node_info.name for node_info in node_list]
1852 logging.debug("Removing keys of nodes '%s' from all nodes but itself and"
1853 " master.", ", ".join(all_nodes_to_remove))
1854 for node in all_nodes:
1855 if node == master_node:
1856 logging.debug("Skipping master node '%s'.", master_node)
1857 continue
1858 if node not in online_nodes:
1859 logging.debug("Skipping offline node '%s'.", node)
1860 continue
1861 if node in all_nodes_to_remove:
1862 logging.debug("Skipping node whose key is removed itself '%s'.", node)
1863 continue
1864 ssh_port = ssh_port_map.get(node)
1865 if not ssh_port:
1866 raise errors.OpExecError("No SSH port information available for"
1867 " node '%s', map: %s." %
1868 (node, ssh_port_map))
1869 error_msg_final = ("When removing the key of node '%s', updating the"
1870 " SSH key files of node '%s' failed. Last error"
1871 " was: %s.")
1872 if node in potential_master_candidates:
1873 logging.debug("Updating key setup of potential master candidate node"
1874 " %s.", node)
1875 try:
1876 utils.RetryByNumberOfTimes(
1877 constants.SSHS_MAX_RETRIES,
1878 errors.SshUpdateError,
1879 run_cmd_fn, cluster_name, node, pathutils.SSH_UPDATE,
1880 ssh_port, pot_mc_data,
1881 debug=ssh_update_debug, verbose=ssh_update_verbose,
1882 use_cluster_key=False, ask_key=False, strict_host_check=False)
1883 except errors.SshUpdateError as last_exception:
1884 error_msg = error_msg_final % (
1885 node_info.name, node, last_exception)
1886 result_msgs.append((node, error_msg))
1887 logging.error(error_msg)
1888
1889 else:
1890 if from_authorized_keys:
1891 logging.debug("Updating key setup of normal node %s.", node)
1892 try:
1893 utils.RetryByNumberOfTimes(
1894 constants.SSHS_MAX_RETRIES,
1895 errors.SshUpdateError,
1896 run_cmd_fn, cluster_name, node, pathutils.SSH_UPDATE,
1897 ssh_port, base_data,
1898 debug=ssh_update_debug, verbose=ssh_update_verbose,
1899 use_cluster_key=False, ask_key=False, strict_host_check=False)
1900 except errors.SshUpdateError as last_exception:
1901 error_msg = error_msg_final % (
1902 node_info.name, node, last_exception)
1903 result_msgs.append((node, error_msg))
1904 logging.error(error_msg)
1905
1906 for node_info in node_list:
1907 if node_info.clear_authorized_keys or node_info.from_public_keys or \
1908 node_info.clear_public_keys:
1909 data = {}
1910 _InitSshUpdateData(data, noded_cert_file, ssconf_store)
1911 cluster_name = data[constants.SSHS_CLUSTER_NAME]
1912 ssh_port = ssh_port_map.get(node_info.name)
1913 if not ssh_port:
1914 raise errors.OpExecError("No SSH port information available for"
1915 " node '%s', which is leaving the cluster.")
1916
1917 if node_info.clear_authorized_keys:
1918 # The 'authorized_keys' file is not solely managed by Ganeti. Therefore,
1919 # we have to specify exactly which keys to clear to leave keys untouched
1920 # that were not added by Ganeti.
1921 other_master_candidate_uuids = [uuid for uuid in master_candidate_uuids
1922 if uuid != node_info.uuid]
1923 candidate_keys = ssh.QueryPubKeyFile(other_master_candidate_uuids,
1924 key_file=pub_key_file)
1925 data[constants.SSHS_SSH_AUTHORIZED_KEYS] = \
1926 (constants.SSHS_REMOVE, candidate_keys)
1927
1928 if node_info.clear_public_keys:
1929 data[constants.SSHS_SSH_PUBLIC_KEYS] = \
1930 (constants.SSHS_CLEAR, {})
1931 elif node_info.from_public_keys:
1932 # Since clearing the public keys subsumes removing just a single key,
1933 # we only do it if clear_public_keys is 'False'.
1934
1935 if all_keys_to_remove:
1936 data[constants.SSHS_SSH_PUBLIC_KEYS] = \
1937 (constants.SSHS_REMOVE, all_keys_to_remove)
1938
1939 # If we have no changes to any keyfile, just return
1940 if not (constants.SSHS_SSH_PUBLIC_KEYS in data or
1941 constants.SSHS_SSH_AUTHORIZED_KEYS in data):
1942 return
1943
1944 logging.debug("Updating SSH key setup of target node '%s'.",
1945 node_info.name)
1946 try:
1947 utils.RetryByNumberOfTimes(
1948 constants.SSHS_MAX_RETRIES,
1949 errors.SshUpdateError,
1950 run_cmd_fn, cluster_name, node_info.name, pathutils.SSH_UPDATE,
1951 ssh_port, data,
1952 debug=ssh_update_debug, verbose=ssh_update_verbose,
1953 use_cluster_key=False, ask_key=False, strict_host_check=False)
1954 except errors.SshUpdateError as last_exception:
1955 result_msgs.append(
1956 (node_info.name,
1957 ("Removing SSH keys from node '%s' failed."
1958 " This can happen when the node is already unreachable."
1959 " Error: %s" % (node_info.name, last_exception))))
1960
1961 if all_keys_to_remove and from_public_keys:
1962 for node_uuid in nodes_remove_from_public_keys:
1963 ssh.RemovePublicKey(node_uuid, key_file=pub_key_file)
1964
1965 return result_msgs
1966 # pylint: enable=R0913
1967
1968
1969 def _GenerateNodeSshKey(node_uuid, node_name, ssh_port_map, ssh_key_type,
1970 ssh_key_bits, pub_key_file=pathutils.SSH_PUB_KEYS,
1971 ssconf_store=None,
1972 noded_cert_file=pathutils.NODED_CERT_FILE,
1973 run_cmd_fn=ssh.RunSshCmdWithStdin,
1974 suffix="",
1975 ssh_update_debug=False,
1976 ssh_update_verbose=False):
1977 """Generates the root SSH key pair on the node.
1978
1979 @type node_uuid: str
1980 @param node_uuid: UUID of the node whose key is removed
1981 @type node_name: str
1982 @param node_name: name of the node whose key is remove
1983 @type ssh_port_map: dict of str to int
1984 @param ssh_port_map: mapping of node names to their SSH port
1985 @type ssh_key_type: One of L{constants.SSHK_ALL}
1986 @param ssh_key_type: the type of SSH key to be generated
1987 @type ssh_key_bits: int
1988 @param ssh_key_bits: the length of the key to be generated
1989
1990 """
1991 if not ssconf_store:
1992 ssconf_store = ssconf.SimpleStore()
1993
1994 keys_by_uuid = ssh.QueryPubKeyFile([node_uuid], key_file=pub_key_file)
1995 if not keys_by_uuid or node_uuid not in keys_by_uuid:
1996 raise errors.SshUpdateError("Node %s (UUID: %s) whose key is requested to"
1997 " be regenerated is not registered in the"
1998 " public keys file." % (node_name, node_uuid))
1999
2000 data = {}
2001 _InitSshUpdateData(data, noded_cert_file, ssconf_store)
2002 cluster_name = data[constants.SSHS_CLUSTER_NAME]
2003 data[constants.SSHS_GENERATE] = (ssh_key_type, ssh_key_bits, suffix)
2004
2005 run_cmd_fn(cluster_name, node_name, pathutils.SSH_UPDATE,
2006 ssh_port_map.get(node_name), data,
2007 debug=ssh_update_debug, verbose=ssh_update_verbose,
2008 use_cluster_key=False, ask_key=False, strict_host_check=False)
2009
2010
2011 def _GetMasterNodeUUID(node_uuid_name_map, master_node_name):
2012 master_node_uuids = [node_uuid for (node_uuid, node_name)
2013 in node_uuid_name_map
2014 if node_name == master_node_name]
2015 if len(master_node_uuids) != 1:
2016 raise errors.SshUpdateError("No (unique) master UUID found. Master node"
2017 " name: '%s', Master UUID: '%s'" %
2018 (master_node_name, master_node_uuids))
2019 return master_node_uuids[0]
2020
2021
2022 def _GetOldMasterKeys(master_node_uuid, pub_key_file):
2023 old_master_keys_by_uuid = ssh.QueryPubKeyFile([master_node_uuid],
2024 key_file=pub_key_file)
2025 if not old_master_keys_by_uuid:
2026 raise errors.SshUpdateError("No public key of the master node (UUID '%s')"
2027 " found, not generating a new key."
2028 % master_node_uuid)
2029 return old_master_keys_by_uuid
2030
2031
2032 def _GetNewMasterKey(root_keyfiles, master_node_uuid):
2033 new_master_keys = []
2034 for (_, (_, public_key_file)) in root_keyfiles.items():
2035 public_key_dir = os.path.dirname(public_key_file)
2036 public_key_file_tmp_filename = \
2037 os.path.splitext(os.path.basename(public_key_file))[0] \
2038 + constants.SSHS_MASTER_SUFFIX + ".pub"
2039 public_key_path_tmp = os.path.join(public_key_dir,
2040 public_key_file_tmp_filename)
2041 if os.path.exists(public_key_path_tmp):
2042 # for some key types, there might not be any keys
2043 key = utils.ReadFile(public_key_path_tmp)
2044 new_master_keys.append(key)
2045 if not new_master_keys:
2046 raise errors.SshUpdateError("Cannot find any type of temporary SSH key.")
2047 return {master_node_uuid: new_master_keys}
2048
2049
2050 def _ReplaceMasterKeyOnMaster(root_keyfiles):
2051 number_of_moves = 0
2052 for (_, (private_key_file, public_key_file)) in root_keyfiles.items():
2053 key_dir = os.path.dirname(public_key_file)
2054 private_key_file_tmp = \
2055 os.path.basename(private_key_file) + constants.SSHS_MASTER_SUFFIX
2056 public_key_file_tmp = private_key_file_tmp + ".pub"
2057 private_key_path_tmp = os.path.join(key_dir,
2058 private_key_file_tmp)
2059 public_key_path_tmp = os.path.join(key_dir,
2060 public_key_file_tmp)
2061 if os.path.exists(public_key_file):
2062 utils.CreateBackup(public_key_file)
2063 utils.RemoveFile(public_key_file)
2064 if os.path.exists(private_key_file):
2065 utils.CreateBackup(private_key_file)
2066 utils.RemoveFile(private_key_file)
2067 if os.path.exists(public_key_path_tmp) and \
2068 os.path.exists(private_key_path_tmp):
2069 # for some key types, there might not be any keys
2070 shutil.move(public_key_path_tmp, public_key_file)
2071 shutil.move(private_key_path_tmp, private_key_file)
2072 number_of_moves += 1
2073 if not number_of_moves:
2074 raise errors.SshUpdateError("Could not move at least one master SSH key.")
2075
2076
2077 def RenewSshKeys(node_uuids, node_names, master_candidate_uuids,
2078 potential_master_candidates, old_key_type, new_key_type,
2079 new_key_bits,
2080 ganeti_pub_keys_file=pathutils.SSH_PUB_KEYS,
2081 ssconf_store=None,
2082 noded_cert_file=pathutils.NODED_CERT_FILE,
2083 run_cmd_fn=ssh.RunSshCmdWithStdin,
2084 ssh_update_debug=False,
2085 ssh_update_verbose=False):
2086 """Renews all SSH keys and updates authorized_keys and ganeti_pub_keys.
2087
2088 @type node_uuids: list of str
2089 @param node_uuids: list of node UUIDs whose keys should be renewed
2090 @type node_names: list of str
2091 @param node_names: list of node names whose keys should be removed. This list
2092 should match the C{node_uuids} parameter
2093 @type master_candidate_uuids: list of str
2094 @param master_candidate_uuids: list of UUIDs of master candidates or
2095 master node
2096 @type old_key_type: One of L{constants.SSHK_ALL}
2097 @param old_key_type: the type of SSH key already present on nodes
2098 @type new_key_type: One of L{constants.SSHK_ALL}
2099 @param new_key_type: the type of SSH key to be generated
2100 @type new_key_bits: int
2101 @param new_key_bits: the length of the key to be generated
2102 @type ganeti_pub_keys_file: str
2103 @param ganeti_pub_keys_file: file path of the the public key file
2104 @type noded_cert_file: str
2105 @param noded_cert_file: path of the noded SSL certificate file
2106 @type run_cmd_fn: function
2107 @param run_cmd_fn: function to run commands on remote nodes via SSH
2108 @raises ProgrammerError: if node_uuids and node_names don't match;
2109 SshUpdateError if a node's key is missing from the public key file,
2110 if a node's new SSH key could not be fetched from it, if there is
2111 none or more than one entry in the public key list for the master
2112 node.
2113
2114 """
2115 if not ssconf_store:
2116 ssconf_store = ssconf.SimpleStore()
2117 cluster_name = ssconf_store.GetClusterName()
2118
2119 if not len(node_uuids) == len(node_names):
2120 raise errors.ProgrammerError("List of nodes UUIDs and node names"
2121 " does not match in length.")
2122
2123 (_, root_keyfiles) = \
2124 ssh.GetAllUserFiles(constants.SSH_LOGIN_USER, mkdir=False, dircheck=False)
2125 (_, old_pub_keyfile) = root_keyfiles[old_key_type]
2126 (_, new_pub_keyfile) = root_keyfiles[new_key_type]
2127 old_master_key = utils.ReadFile(old_pub_keyfile)
2128
2129 node_uuid_name_map = zip(node_uuids, node_names)
2130
2131 master_node_name = ssconf_store.GetMasterNode()
2132 master_node_uuid = _GetMasterNodeUUID(node_uuid_name_map, master_node_name)
2133 ssh_port_map = ssconf_store.GetSshPortMap()
2134 # List of all node errors that happened, but which did not abort the
2135 # procedure as a whole. It is important that this is a list to have a
2136 # somewhat chronological history of events.
2137 all_node_errors = []
2138
2139 # process non-master nodes
2140
2141 # keys to add in bulk at the end
2142 node_keys_to_add = []
2143
2144 # list of all nodes
2145 node_list = []
2146
2147 # list of keys to be removed before generating new keys
2148 node_info_to_remove = []
2149
2150 for node_uuid, node_name in node_uuid_name_map:
2151 if node_name == master_node_name:
2152 continue
2153 master_candidate = node_uuid in master_candidate_uuids
2154 potential_master_candidate = node_name in potential_master_candidates
2155 node_list.append((node_uuid, node_name, master_candidate,
2156 potential_master_candidate))
2157
2158 keys_by_uuid = ssh.QueryPubKeyFile([node_uuid],
2159 key_file=ganeti_pub_keys_file)
2160 if not keys_by_uuid:
2161 raise errors.SshUpdateError("No public key of node %s (UUID %s) found,"
2162 " not generating a new key."
2163 % (node_name, node_uuid))
2164
2165 if master_candidate:
2166 logging.debug("Fetching old SSH key from node '%s'.", node_name)
2167 old_pub_key = ssh.ReadRemoteSshPubKeys(old_pub_keyfile,
2168 node_name, cluster_name,
2169 ssh_port_map[node_name],
2170 False, # ask_key
2171 False) # key_check
2172 if old_pub_key != old_master_key:
2173 # If we are already in a multi-key setup (that is past Ganeti 2.12),
2174 # we can safely remove the old key of the node. Otherwise, we cannot
2175 # remove that node's key, because it is also the master node's key
2176 # and that would terminate all communication from the master to the
2177 # node.
2178 node_info_to_remove.append(SshRemoveNodeInfo(
2179 uuid=node_uuid,
2180 name=node_name,
2181 from_authorized_keys=master_candidate,
2182 from_public_keys=False,
2183 clear_authorized_keys=False,
2184 clear_public_keys=False))
2185 else:
2186 logging.debug("Old key of node '%s' is the same as the current master"
2187 " key. Not deleting that key on the node.", node_name)
2188
2189 logging.debug("Removing old SSH keys of all master candidates.")
2190 if node_info_to_remove:
2191 node_errors = RemoveNodeSshKeyBulk(
2192 node_info_to_remove,
2193 master_candidate_uuids,
2194 potential_master_candidates,
2195 master_uuid=master_node_uuid,
2196 ssh_update_debug=ssh_update_debug,
2197 ssh_update_verbose=ssh_update_verbose)
2198 if node_errors:
2199 all_node_errors = all_node_errors + node_errors
2200
2201 for (node_uuid, node_name, master_candidate, potential_master_candidate) \
2202 in node_list:
2203
2204 logging.debug("Generating new SSH key for node '%s'.", node_name)
2205 _GenerateNodeSshKey(node_uuid, node_name, ssh_port_map, new_key_type,
2206 new_key_bits, pub_key_file=ganeti_pub_keys_file,
2207 ssconf_store=ssconf_store,
2208 noded_cert_file=noded_cert_file,
2209 run_cmd_fn=run_cmd_fn,
2210 ssh_update_verbose=ssh_update_verbose,
2211 ssh_update_debug=ssh_update_debug)
2212
2213 try:
2214 logging.debug("Fetching newly created SSH key from node '%s'.", node_name)
2215 pub_key = ssh.ReadRemoteSshPubKeys(new_pub_keyfile,
2216 node_name, cluster_name,
2217 ssh_port_map[node_name],
2218 False, # ask_key
2219 False) # key_check
2220 except:
2221 raise errors.SshUpdateError("Could not fetch key of node %s"
2222 " (UUID %s)" % (node_name, node_uuid))
2223
2224 if potential_master_candidate:
2225 ssh.RemovePublicKey(node_uuid, key_file=ganeti_pub_keys_file)
2226 ssh.AddPublicKey(node_uuid, pub_key, key_file=ganeti_pub_keys_file)
2227
2228 node_info = SshAddNodeInfo(name=node_name,
2229 uuid=node_uuid,
2230 to_authorized_keys=master_candidate,
2231 to_public_keys=potential_master_candidate,
2232 get_public_keys=True)
2233 node_keys_to_add.append(node_info)
2234
2235 node_errors = AddNodeSshKeyBulk(
2236 node_keys_to_add, potential_master_candidates,
2237 pub_key_file=ganeti_pub_keys_file, ssconf_store=ssconf_store,
2238 noded_cert_file=noded_cert_file,
2239 run_cmd_fn=run_cmd_fn,
2240 ssh_update_debug=ssh_update_debug,
2241 ssh_update_verbose=ssh_update_verbose)
2242 if node_errors:
2243 all_node_errors = all_node_errors + node_errors
2244
2245 # Renewing the master node's key
2246
2247 # Preserve the old keys for now
2248 old_master_keys_by_uuid = _GetOldMasterKeys(master_node_uuid,
2249 ganeti_pub_keys_file)
2250
2251 # Generate a new master key with a suffix, don't touch the old one for now
2252 logging.debug("Generate new ssh key of master.")
2253 _GenerateNodeSshKey(master_node_uuid, master_node_name, ssh_port_map,
2254 new_key_type, new_key_bits,
2255 pub_key_file=ganeti_pub_keys_file,
2256 ssconf_store=ssconf_store,
2257 noded_cert_file=noded_cert_file,
2258 run_cmd_fn=run_cmd_fn,
2259 suffix=constants.SSHS_MASTER_SUFFIX,
2260 ssh_update_debug=ssh_update_debug,
2261 ssh_update_verbose=ssh_update_verbose)
2262 # Read newly created master key
2263 new_master_key_dict = _GetNewMasterKey(root_keyfiles, master_node_uuid)
2264
2265 # Replace master key in the master nodes' public key file
2266 ssh.RemovePublicKey(master_node_uuid, key_file=ganeti_pub_keys_file)
2267 for pub_key in new_master_key_dict[master_node_uuid]:
2268 ssh.AddPublicKey(master_node_uuid, pub_key, key_file=ganeti_pub_keys_file)
2269
2270 # Add new master key to all node's public and authorized keys
2271 logging.debug("Add new master key to all nodes.")
2272 node_errors = AddNodeSshKey(
2273 master_node_uuid, master_node_name, potential_master_candidates,
2274 to_authorized_keys=True, to_public_keys=True,
2275 get_public_keys=False, pub_key_file=ganeti_pub_keys_file,
2276 ssconf_store=ssconf_store, noded_cert_file=noded_cert_file,
2277 run_cmd_fn=run_cmd_fn,
2278 ssh_update_debug=ssh_update_debug,
2279 ssh_update_verbose=ssh_update_verbose)
2280 if node_errors:
2281 all_node_errors = all_node_errors + node_errors
2282
2283 # Remove the old key file and rename the new key to the non-temporary filename
2284 _ReplaceMasterKeyOnMaster(root_keyfiles)
2285
2286 # Remove old key from authorized keys
2287 (auth_key_file, _) = \
2288 ssh.GetAllUserFiles(constants.SSH_LOGIN_USER, mkdir=False, dircheck=False)
2289 ssh.RemoveAuthorizedKeys(auth_key_file,
2290 old_master_keys_by_uuid[master_node_uuid])
2291
2292 # Remove the old key from all node's authorized keys file
2293 logging.debug("Remove the old master key from all nodes.")
2294 node_errors = RemoveNodeSshKey(
2295 master_node_uuid, master_node_name, master_candidate_uuids,
2296 potential_master_candidates,
2297 keys_to_remove=old_master_keys_by_uuid, from_authorized_keys=True,
2298 from_public_keys=False, clear_authorized_keys=False,
2299 clear_public_keys=False,
2300 ssh_update_debug=ssh_update_debug,
2301 ssh_update_verbose=ssh_update_verbose)
2302 if node_errors:
2303 all_node_errors = all_node_errors + node_errors
2304
2305 return all_node_errors
2306
2307
2308 def GetBlockDevSizes(devices):
2309 """Return the size of the given block devices
2310
2311 @type devices: list
2312 @param devices: list of block device nodes to query
2313 @rtype: dict
2314 @return:
2315 dictionary of all block devices under /dev (key). The value is their
2316 size in MiB.
2317
2318 {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
2319
2320 """
2321 DEV_PREFIX = "/dev/"
2322 blockdevs = {}
2323
2324 for devpath in devices:
2325 if not utils.IsBelowDir(DEV_PREFIX, devpath):
2326 continue
2327
2328 try:
2329 st = os.stat(devpath)
2330 except EnvironmentError, err:
2331 logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
2332 continue
2333
2334 if stat.S_ISBLK(st.st_mode):
2335 result = utils.RunCmd(["blockdev", "--getsize64", devpath])
2336 if result.failed:
2337 # We don't want to fail, just do not list this device as available
2338 logging.warning("Cannot get size for block device %s", devpath)
2339 continue
2340
2341 size = int(result.stdout) / (1024 * 1024)
2342 blockdevs[devpath] = size
2343 return blockdevs
2344
2345
2346 def GetVolumeList(vg_names):
2347 """Compute list of logical volumes and their size.
2348
2349 @type vg_names: list
2350 @param vg_names: the volume groups whose LVs we should list, or
2351 empty for all volume groups
2352 @rtype: dict
2353 @return:
2354 dictionary of all partions (key) with value being a tuple of
2355 their size (in MiB), inactive and online status::
2356
2357 {'xenvg/test1': ('20.06', True, True)}
2358
2359 in case of errors, a string is returned with the error
2360 details.
2361
2362 """
2363 lvs = {}
2364 sep = "|"
2365 if not vg_names:
2366 vg_names = []
2367 result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
2368 "--separator=%s" % sep,
2369 "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
2370 if result.failed:
2371 _Fail("Failed to list logical volumes, lvs output: %s", result.output)
2372
2373 for line in result.stdout.splitlines():
2374 line = line.strip()
2375 match = _LVSLINE_REGEX.match(line)
2376 if not match:
2377 logging.error("Invalid line returned from lvs output: '%s'", line)
2378 continue
2379 vg_name, name, size, attr = match.groups()
2380 inactive = attr[4] == "-"
2381 online = attr[5] == "o"
2382 virtual = attr[0] == "v"
2383 if virtual:
2384 # we don't want to report such volumes as existing, since they
2385 # don't really hold data
2386 continue
2387 lvs[vg_name + "/" + name] = (size, inactive, online)
2388
2389 return lvs
2390
2391
2392 def ListVolumeGroups():
2393 """List the volume groups and their size.
2394
2395 @rtype: dict
2396 @return: dictionary with keys volume name and values the
2397 size of the volume
2398
2399 """
2400 return utils.ListVolumeGroups()
2401
2402
2403 def NodeVolumes():
2404 """List all volumes on this node.
2405
2406 @rtype: list
2407 @return:
2408 A list of dictionaries, each having four keys:
2409 - name: the logical volume name,
2410 - size: the size of the logical volume
2411 - dev: the physical device on which the LV lives
2412 - vg: the volume group to which it belongs
2413
2414 In case of errors, we return an empty list and log the
2415 error.
2416
2417 Note that since a logical volume can live on multiple physical
2418 volumes, the resulting list might include a logical volume
2419 multiple times.
2420
2421 """
2422 result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
2423 "--separator=|",
2424 "--options=lv_name,lv_size,devices,vg_name"])
2425 if result.failed:
2426 _Fail("Failed to list logical volumes, lvs output: %s",
2427 result.output)
2428
2429 def parse_dev(dev):
2430 return dev.split("(")[0]
2431
2432 def handle_dev(dev):
2433 return [parse_dev(x) for x in dev.split(",")]
2434
2435 def map_line(line):
2436 line = [v.strip() for v in line]
2437 return [{"name": line[0], "size": line[1],
2438 "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
2439
2440 all_devs = []
2441 for line in result.stdout.splitlines():
2442 if line.count("|") >= 3:
2443 all_devs.extend(map_line(line.split("|")))
2444 else:
2445 logging.warning("Strange line in the output from lvs: '%s'", line)
2446 return all_devs
2447
2448
2449 def BridgesExist(bridges_list):
2450 """Check if a list of bridges exist on the current node.
2451
2452 @rtype: boolean
2453 @return: C{True} if all of them exist, C{False} otherwise
2454
2455 """
2456 missing = []
2457 for bridge in bridges_list:
2458 if not utils.BridgeExists(bridge):
2459 missing.append(bridge)
2460
2461 if missing:
2462 _Fail("Missing bridges %s", utils.CommaJoin(missing))
2463
2464
2465 def GetInstanceListForHypervisor(hname, hvparams=None,
2466 get_hv_fn=hypervisor.GetHypervisor):
2467 """Provides a list of instances of the given hypervisor.
2468
2469 @type hname: string
2470 @param hname: name of the hypervisor
2471 @type hvparams: dict of strings
2472 @param hvparams: hypervisor parameters for the given hypervisor
2473 @type get_hv_fn: function
2474 @param get_hv_fn: function that returns a hypervisor for the given hypervisor
2475 name; optional parameter to increase testability
2476
2477 @rtype: list
2478 @return: a list of all running instances on the current node
2479 - instance1.example.com
2480 - instance2.example.com
2481
2482 """
2483 try:
2484 return get_hv_fn(hname).ListInstances(hvparams=hvparams)
2485 except errors.HypervisorError, err:
2486 _Fail("Error enumerating instances (hypervisor %s): %s",
2487 hname, err, exc=True)
2488
2489
2490 def GetInstanceList(hypervisor_list, all_hvparams=None,
2491 get_hv_fn=hypervisor.GetHypervisor):
2492 """Provides a list of instances.
2493
2494 @type hypervisor_list: list
2495 @param hypervisor_list: the list of hypervisors to query information
2496 @type all_hvparams: dict of dict of strings
2497 @param all_hvparams: a dictionary mapping hypervisor types to respective
2498 cluster-wide hypervisor parameters
2499 @type get_hv_fn: function
2500 @param get_hv_fn: function that returns a hypervisor for the given hypervisor
2501 name; optional parameter to increase testability
2502
2503 @rtype: list
2504 @return: a list of all running instances on the current node
2505 - instance1.example.com
2506 - instance2.example.com
2507
2508 """
2509 results = []
2510 for hname in hypervisor_list:
2511 hvparams = all_hvparams[hname]
2512 results.extend(GetInstanceListForHypervisor(hname, hvparams=hvparams,
2513 get_hv_fn=get_hv_fn))
2514 return results
2515
2516
2517 def GetInstanceInfo(instance, hname, hvparams=None):
2518 """Gives back the information about an instance as a dictionary.
2519
2520 @type instance: string
2521 @param instance: the instance name
2522 @type hname: string
2523 @param hname: the hypervisor type of the instance
2524 @type hvparams: dict of strings
2525 @param hvparams: the instance's hvparams
2526
2527 @rtype: dict
2528 @return: dictionary with the following keys:
2529 - memory: memory size of instance (int)
2530 - state: state of instance (HvInstanceState)
2531 - time: cpu time of instance (float)
2532 - vcpus: the number of vcpus (int)
2533
2534 """
2535 output = {}
2536
2537 iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance,
2538 hvparams=hvparams)
2539 if iinfo is not None:
2540 output["memory"] = iinfo[2]
2541 output["vcpus"] = iinfo[3]
2542 output["state"] = iinfo[4]
2543 output["time"] = iinfo[5]
2544
2545 return output
2546
2547
2548 def GetInstanceMigratable(instance):
2549 """Computes whether an instance can be migrated.
2550
2551 @type instance: L{objects.Instance}
2552 @param instance: object representing the instance to be checked.
2553
2554 @rtype: tuple
2555 @return: tuple of (result, description) where:
2556 - result: whether the instance can be migrated or not
2557 - description: a description of the issue, if relevant
2558
2559 """
2560 hyper = hypervisor.GetHypervisor(instance.hypervisor)
2561 iname = instance.name
2562 if iname not in hyper.ListInstances(hvparams=instance.hvparams):
2563 _Fail("Instance %s is not running", iname)
2564
2565 for idx in range(len(instance.disks_info)):
2566 link_name = _GetBlockDevSymlinkPath(iname, idx)
2567 if not os.path.islink(link_name):
2568 logging.warning("Instance %s is missing symlink %s for disk %d",
2569 iname, link_name, idx)
2570
2571
2572 def GetAllInstancesInfo(hypervisor_list, all_hvparams):
2573 """Gather data about all instances.
2574
2575 This is the equivalent of L{GetInstanceInfo}, except that it
2576 computes data for all instances at once, thus being faster if one
2577 needs data about more than one instance.
2578
2579 @type hypervisor_list: list
2580 @param hypervisor_list: list of hypervisors to query for instance data
2581 @type all_hvparams: dict of dict of strings
2582 @param all_hvparams: mapping of hypervisor names to hvparams
2583
2584 @rtype: dict
2585 @return: dictionary of instance: data, with data having the following keys:
2586 - memory: memory size of instance (int)
2587 - state: xen state of instance (string)
2588 - time: cpu time of instance (float)
2589 - vcpus: the number of vcpus
2590
2591 """
2592 output = {}
2593 for hname in hypervisor_list:
2594 hvparams = all_hvparams[hname]
2595 iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo(hvparams)
2596 if iinfo:
2597 for name, _, memory, vcpus, state, times in iinfo:
2598 value = {
2599 "memory": memory,
2600 "vcpus": vcpus,
2601 "state": state,
2602 "time": times,
2603 }
2604 if name in output:
2605 # we only check static parameters, like memory and vcpus,
2606 # and not state and time which can change between the
2607 # invocations of the different hypervisors
2608 for key in "memory", "vcpus":
2609 if value[key] != output[name][key]:
2610 _Fail("Instance %s is running twice"
2611 " with different parameters", name)
2612 output[name] = value
2613
2614 return output
2615
2616
2617 def GetInstanceConsoleInfo(instance_param_dict,
2618 get_hv_fn=hypervisor.GetHypervisor):
2619 """Gather data about the console access of a set of instances of this node.
2620
2621 This function assumes that the caller already knows which instances are on
2622 this node, by calling a function such as L{GetAllInstancesInfo} or
2623 L{GetInstanceList}.
2624
2625 For every instance, a large amount of configuration data needs to be
2626 provided to the hypervisor interface in order to receive the console
2627 information. Whether this could or should be cut down can be discussed.
2628 The information is provided in a dictionary indexed by instance name,
2629 allowing any number of instance queries to be done.
2630
2631 @type instance_param_dict: dict of string to tuple of dictionaries, where the
2632 dictionaries represent: L{objects.Instance}, L{objects.Node},
2633 L{objects.NodeGroup}, HvParams, BeParams
2634 @param instance_param_dict: mapping of instance name to parameters necessary
2635 for console information retrieval
2636
2637 @rtype: dict
2638 @return: dictionary of instance: data, with data having the following keys:
2639 - instance: instance name
2640 - kind: console kind
2641 - message: used with kind == CONS_MESSAGE, indicates console to be
2642 unavailable, supplies error message
2643 - host: host to connect to
2644 - port: port to use
2645 - user: user for login
2646 - command: the command, broken into parts as an array
2647 - display: unknown, potentially unused?
2648
2649 """
2650
2651 output = {}
2652 for inst_name in instance_param_dict:
2653 instance = instance_param_dict[inst_name]["instance"]
2654 pnode = instance_param_dict[inst_name]["node"]
2655 group = instance_param_dict[inst_name]["group"]
2656 hvparams = instance_param_dict[inst_name]["hvParams"]
2657 beparams = instance_param_dict[inst_name]["beParams"]
2658
2659 instance = objects.Instance.FromDict(instance)
2660 pnode = objects.Node.FromDict(pnode)
2661 group = objects.NodeGroup.FromDict(group)
2662
2663 h = get_hv_fn(instance.hypervisor)
2664 output[inst_name] = h.GetInstanceConsole(instance, pnode, group,
2665 hvparams, beparams).ToDict()
2666
2667 return output
2668
2669
2670 def _InstanceLogName(kind, os_name, instance, component):
2671 """Compute the OS log filename for a given instance and operation.
2672
2673 The instance name and os name are passed in as strings since not all
2674 operations have these as part of an instance object.
2675
2676 @type kind: string
2677 @param kind: the operation type (e.g. add, import, etc.)
2678 @type os_name: string
2679 @param os_name: the os name
2680 @type instance: string
2681 @param instance: the name of the instance being imported/added/etc.
2682 @type component: string or None
2683 @param component: the name of the component of the instance being
2684 transferred
2685
2686 """
2687 # TODO: Use tempfile.mkstemp to create unique filename
2688 if component:
2689 assert "/" not in component
2690 c_msg = "-%s" % component
2691 else:
2692 c_msg = ""
2693 base = ("%s-%s-%s%s-%s.log" %
2694 (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
2695 return utils.PathJoin(pathutils.LOG_OS_DIR, base)
2696
2697
2698 def InstanceOsAdd(instance, reinstall, debug):
2699 """Add an OS to an instance.
2700
2701 @type instance: L{objects.Instance}
2702 @param instance: Instance whose OS is to be installed
2703 @type reinstall: boolean
2704 @param reinstall: whether this is an instance reinstall
2705 @type debug: integer
2706 @param debug: debug level, passed to the OS scripts
2707 @rtype: None
2708
2709 """
2710 inst_os = OSFromDisk(instance.os)
2711
2712 create_env = OSEnvironment(instance, inst_os, debug)
2713 if reinstall:
2714 create_env["INSTANCE_REINSTALL"] = "1"
2715
2716 logfile = _InstanceLogName("add", instance.os, instance.name, None)
2717
2718 result = utils.RunCmd([inst_os.create_script], env=create_env,
2719 cwd=inst_os.path, output=logfile, reset_env=True)
2720 if result.failed:
2721 logging.error("os create command '%s' returned error: %s, logfile: %s,"
2722 " output: %s", result.cmd, result.fail_reason, logfile,
2723 result.output)
2724 lines = [utils.SafeEncode(val)
2725 for val in utils.TailFile(logfile, lines=20)]
2726 _Fail("OS create script failed (%s), last lines in the"
2727 " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
2728
2729
2730 def RunRenameInstance(instance, old_name, debug):
2731 """Run the OS rename script for an instance.
2732
2733 @type instance: L{objects.Instance}
2734 @param instance: Instance whose OS is to be installed
2735 @type old_name: string
2736 @param old_name: previous instance name
2737 @type debug: integer
2738 @param debug: debug level, passed to the OS scripts
2739 @rtype: boolean
2740 @return: the success of the operation
2741
2742 """
2743 inst_os = OSFromDisk(instance.os)
2744
2745 rename_env = OSEnvironment(instance, inst_os, debug)
2746 rename_env["OLD_INSTANCE_NAME"] = old_name
2747
2748 logfile = _InstanceLogName("rename", instance.os,
2749 "%s-%s" % (old_name, instance.name), None)
2750
2751 result = utils.RunCmd([inst_os.rename_script], env=rename_env,
2752 cwd=inst_os.path, output=logfile, reset_env=True)
2753
2754 if result.failed:
2755 logging.error("os create command '%s' returned error: %s output: %s",
2756 result.cmd, result.fail_reason, result.output)
2757 lines = [utils.SafeEncode(val)
2758 for val in utils.TailFile(logfile, lines=20)]
2759 _Fail("OS rename script failed (%s), last lines in the"
2760 " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
2761
2762
2763 def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
2764 """Returns symlink path for block device.
2765
2766 """
2767 if _dir is None:
2768 _dir = pathutils.DISK_LINKS_DIR
2769
2770 return utils.PathJoin(_dir,
2771 ("%s%s%s" %
2772 (instance_name, constants.DISK_SEPARATOR, idx)))
2773
2774
2775 def _SymlinkBlockDev(instance_name, device_path, idx):
2776 """Set up symlinks to a instance's block device.
2777
2778 This is an auxiliary function run when an instance is start (on the primary
2779 node) or when an instance is migrated (on the target node).
2780
2781
2782 @param instance_name: the name of the target instance
2783 @param device_path: path of the physical block device, on the node
2784 @param idx: the disk index
2785 @return: absolute path to the disk's symlink
2786
2787 """
2788 # In case we have only a userspace access URI, device_path is None
2789 if not device_path:
2790 return None
2791
2792 link_name = _GetBlockDevSymlinkPath(instance_name, idx)
2793 try:
2794 os.symlink(device_path, link_name)
2795 except OSError, err:
2796 if err.errno == errno.EEXIST:
2797 if (not os.path.islink(link_name) or
2798 os.readlink(link_name) != device_path):
2799 os.remove(link_name)
2800 os.symlink(device_path, link_name)
2801 else:
2802 raise
2803
2804 return link_name
2805
2806
2807 def _RemoveBlockDevLinks(instance_name, disks):
2808 """Remove the block device symlinks belonging to the given instance.
2809
2810 """
2811 for idx, _ in enumerate(disks):
2812 link_name = _GetBlockDevSymlinkPath(instance_name, idx)
2813 if os.path.islink(link_name):
2814 try:
2815 os.remove(link_name)
2816 except OSError:
2817 logging.exception("Can't remove symlink '%s'", link_name)
2818
2819
2820 def _CalculateDeviceURI(instance, disk, device):
2821 """Get the URI for the device.
2822
2823 @type instance: L{objects.Instance}
2824 @param instance: the instance which disk belongs to
2825 @type disk: L{objects.Disk}
2826 @param disk: the target disk object
2827 @type device: L{bdev.BlockDev}
2828 @param device: the corresponding BlockDevice
2829 @rtype: string
2830 @return: the device uri if any else None
2831
2832 """
2833 access_mode = disk.params.get(constants.LDP_ACCESS,
2834 constants.DISK_KERNELSPACE)
2835 if access_mode == constants.DISK_USERSPACE:
2836 # This can raise errors.BlockDeviceError
2837 return device.GetUserspaceAccessUri(instance.hypervisor)
2838 else:
2839 return None
2840
2841
2842 def _GatherAndLinkBlockDevs(instance):
2843 """Set up an instance's block device(s).
2844
2845 This is run on the primary node at instance startup. The block
2846 devices must be already assembled.
2847
2848 @type instance: L{objects.Instance}
2849 @param instance: the instance whose disks we should assemble
2850 @rtype: list
2851 @return: list of (disk_object, link_name, drive_uri)
2852
2853 """
2854 block_devices = []
2855 for idx, disk in enumerate(instance.disks_info):
2856 device = _RecursiveFindBD(disk)
2857 if device is None:
2858 raise errors.BlockDeviceError("Block device '%s' is not set up." %
2859 str(disk))
2860 device.Open()
2861 try:
2862 link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
2863 except OSError, e:
2864 raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
2865 e.strerror)
2866 uri = _CalculateDeviceURI(instance, disk, device)
2867
2868 block_devices.append((disk, link_name, uri))
2869
2870 return block_devices
2871
2872
2873 def _IsInstanceUserDown(instance_info):
2874 return instance_info and \
2875 "state" in instance_info and \
2876 hv_base.HvInstanceState.IsShutdown(instance_info["state"])
2877
2878
2879 def _GetInstanceInfo(instance):
2880 """Helper function L{GetInstanceInfo}"""
2881 return GetInstanceInfo(instance.name, instance.hypervisor,
2882 hvparams=instance.hvparams)
2883
2884
2885 def StartInstance(instance, startup_paused, reason, store_reason=True):
2886 """Start an instance.
2887
2888 @type instance: L{objects.Instance}
2889 @param instance: the instance object
2890 @type startup_paused: bool
2891 @param instance: pause instance at startup?
2892 @type reason: list of reasons
2893 @param reason: the reason trail for this startup
2894 @type store_reason: boolean
2895 @param store_reason: whether to store the shutdown reason trail on file
2896 @rtype: None
2897
2898 """
2899 instance_info = _GetInstanceInfo(instance)
2900
2901 if instance_info and not _IsInstanceUserDown(instance_info):
2902 logging.info("Instance '%s' already running, not starting", instance.name)
2903 return
2904
2905 try:
2906 block_devices = _GatherAndLinkBlockDevs(instance)
2907 hyper = hypervisor.GetHypervisor(instance.hypervisor)
2908 hyper.StartInstance(instance, block_devices, startup_paused)
2909 if store_reason:
2910 _StoreInstReasonTrail(instance.name, reason)
2911 except errors.BlockDeviceError, err:
2912 _Fail("Block device error: %s", err, exc=True)
2913 except errors.HypervisorError, err:
2914 _RemoveBlockDevLinks(instance.name, instance.disks_info)
2915 _Fail("Hypervisor error: %s", err, exc=True)
2916
2917
2918 def InstanceShutdown(instance, timeout, reason, store_reason=True):
2919 """Shut an instance down.
2920
2921 @note: this functions uses polling with a hardcoded timeout.
2922
2923 @type instance: L{objects.Instance}
2924 @param instance: the instance object
2925 @type timeout: integer
2926 @param timeout: maximum timeout for soft shutdown
2927 @type reason: list of reasons
2928 @param reason: the reason trail for this shutdown
2929 @type store_reason: boolean
2930 @param store_reason: whether to store the shutdown reason trail on file
2931 @rtype: None
2932
2933 """
2934 hyper = hypervisor.GetHypervisor(instance.hypervisor)
2935
2936 if not _GetInstanceInfo(instance):
2937 logging.info("Instance '%s' not running, doing nothing", instance.name)
2938 return
2939
2940 class _TryShutdown(object):
2941 def __init__(self):
2942 self.tried_once = False
2943
2944 def __call__(self):
2945 if not _GetInstanceInfo(instance):
2946 return
2947
2948 try:
2949 hyper.StopInstance(instance, retry=self.tried_once, timeout=timeout)
2950 if store_reason:
2951 _StoreInstReasonTrail(instance.name, reason)
2952 except errors.HypervisorError, err:
2953 # if the instance is no longer existing, consider this a
2954 # success and go to cleanup
2955 if not _GetInstanceInfo(instance):
2956 return
2957
2958 _Fail("Failed to stop instance '%s': %s", instance.name, err)
2959
2960 self.tried_once = True
2961
2962 raise utils.RetryAgain()
2963
2964 try:
2965 utils.Retry(_TryShutdown(), 5, timeout)
2966 except utils.RetryTimeout:
2967 # the shutdown did not succeed
2968 logging.error("Shutdown of '%s' unsuccessful, forcing", instance.name)
2969
2970 try:
2971 hyper.StopInstance(instance, force=True)
2972 except errors.HypervisorError, err:
2973 # only raise an error if the instance still exists, otherwise
2974 # the error could simply be "instance ... unknown"!
2975 if _GetInstanceInfo(instance):
2976 _Fail("Failed to force stop instance '%s': %s", instance.name, err)
2977
2978 time.sleep(1)
2979
2980 if _GetInstanceInfo(instance):
2981 _Fail("Could not shutdown instance '%s' even by destroy", instance.name)
2982
2983 try:
2984 hyper.CleanupInstance(instance.name)
2985 except errors.HypervisorError, err:
2986 logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
2987
2988 _RemoveBlockDevLinks(instance.name, instance.disks_info)
2989
2990
2991 def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
2992 """Reboot an instance.
2993
2994 @type instance: L{objects.Instance}
2995 @param instance: the instance object to reboot
2996 @type reboot_type: str
2997 @param reboot_type: the type of reboot, one the following
2998 constants:
2999 - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
3000 instance OS, do not recreate the VM
3001 - L{constants.INSTANCE_REBOOT_HARD}: tear down and
3002 restart the VM (at the hypervisor level)
3003 - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
3004 not accepted here, since that mode is handled differently, in
3005 cmdlib, and translates into full stop and start of the
3006 instance (instead of a call_instance_reboot RPC)
3007 @type shutdown_timeout: integer
3008 @param shutdown_timeout: maximum timeout for soft shutdown
3009 @type reason: list of reasons
3010 @param reason: the reason trail for this reboot
3011 @rtype: None
3012
3013 """
3014 # TODO: this is inconsistent with 'StartInstance' and 'InstanceShutdown'
3015 # because those functions simply 'return' on error whereas this one
3016 # raises an exception with '_Fail'
3017 if not _GetInstanceInfo(instance):
3018 _Fail("Cannot reboot instance '%s' that is not running", instance.name)
3019
3020 hyper = hypervisor.GetHypervisor(instance.hypervisor)
3021 if reboot_type == constants.INSTANCE_REBOOT_SOFT:
3022 try:
3023 hyper.RebootInstance(instance)
3024 except errors.HypervisorError, err:
3025 _Fail("Failed to soft reboot instance '%s': %s", instance.name, err)
3026 elif reboot_type == constants.INSTANCE_REBOOT_HARD:
3027 try:
3028 InstanceShutdown(instance, shutdown_timeout, reason, store_reason=False)
3029 result = StartInstance(instance, False, reason, store_reason=False)
3030 _StoreInstReasonTrail(instance.name, reason)
3031 return result
3032 except errors.HypervisorError, err:
3033 _Fail("Failed to hard reboot instance '%s': %s", instance.name, err)
3034 else:
3035 _Fail("Invalid reboot_type received: '%s'", reboot_type)
3036
3037
3038 def InstanceBalloonMemory(instance, memory):
3039 """Resize an instance's memory.
3040
3041 @type instance: L{objects.Instance}
3042 @param instance: the instance object
3043 @type memory: int
3044 @param memory: new memory amount in MB
3045 @rtype: None
3046
3047 """
3048 hyper = hypervisor.GetHypervisor(instance.hypervisor)
3049 running = hyper.ListInstances(hvparams=instance.hvparams)
3050 if instance.name not in running:
3051 logging.info("Instance %s is not running, cannot balloon", instance.name)
3052 return
3053 try:
3054 hyper.BalloonInstanceMemory(instance, memory)
3055 except errors.HypervisorError, err:
3056 _Fail("Failed to balloon instance memory: %s", err, exc=True)
3057
3058
3059 def MigrationInfo(instance):
3060 """Gather information about an instance to be migrated.
3061
3062 @type instance: L{objects.Instance}
3063 @param instance: the instance definition
3064
3065 """
3066 hyper = hypervisor.GetHypervisor(instance.hypervisor)
3067 try:
3068 info = hyper.MigrationInfo(instance)
3069 except errors.HypervisorError, err:
3070 _Fail("Failed to fetch migration information: %s", err, exc=True)
3071 return info
3072
3073
3074 def AcceptInstance(instance, info, target):
3075 """Prepare the node to accept an instance.
3076
3077 @type instance: L{objects.Instance}
3078 @param instance: the instance definition
3079 @type info: string/data (opaque)
3080 @param info: migration information, from the source node
3081 @type target: string
3082 @param target: target host (usually ip), on this node
3083
3084 """
3085 hyper = hypervisor.GetHypervisor(instance.hypervisor)
3086 try:
3087 hyper.AcceptInstance(instance, info, target)
3088 except errors.HypervisorError, err:
3089 _Fail("Failed to accept instance: %s", err, exc=True)
3090
3091
3092 def FinalizeMigrationDst(instance, info, success):
3093 """Finalize any preparation to accept an instance.
3094
3095 @type instance: L{objects.Instance}
3096 @param instance: the instance definition
3097 @type info: string/data (opaque)
3098 @param info: migration information, from the source node
3099 @type success: boolean
3100 @param success: whether the migration was a success or a failure
3101
3102 """
3103 hyper = hypervisor.GetHypervisor(instance.hypervisor)
3104 try:
3105 hyper.FinalizeMigrationDst(instance, info, success)
3106 except errors.HypervisorError, err:
3107 _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
3108
3109
3110 def MigrateInstance(cluster_name, instance, target, live):
3111 """Migrates an instance to another node.
3112
3113 @type cluster_name: string
3114 @param cluster_name: name of the cluster
3115 @type instance: L{objects.Instance}
3116 @param instance: the instance definition
3117 @type target: string
3118 @param target: the target node name
3119 @type live: boolean
3120 @param live: whether the migration should be done live or not (the
3121 interpretation of this parameter is left to the hypervisor)
3122 @raise RPCFail: if migration fails for some reason
3123
3124 """
3125 hyper = hypervisor.GetHypervisor(instance.hypervisor)
3126
3127 try:
3128 hyper.MigrateInstance(cluster_name, instance, target, live)
3129 except errors.HypervisorError, err:
3130 _Fail("Failed to migrate instance: %s", err, exc=True)
3131
3132
3133 def FinalizeMigrationSource(instance, success, live):
3134 """Finalize the instance migration on the source node.
3135
3136 @type instance: L{objects.Instance}
3137 @param instance: the instance definition of the migrated instance
3138 @type success: bool
3139 @param success: whether the migration succeeded or not
3140 @type live: bool
3141 @param live: whether the user requested a live migration or not
3142 @raise RPCFail: If the execution fails for some reason
3143
3144 """
3145 hyper = hypervisor.GetHypervisor(instance.hypervisor)
3146
3147 try:
3148 hyper.FinalizeMigrationSource(instance, success, live)
3149 except Exception, err: # pylint: disable=W0703
3150 _Fail("Failed to finalize the migration on the source node: %s", err,
3151 exc=True)
3152
3153
3154 def GetMigrationStatus(instance):
3155 """Get the migration status
3156
3157 @type instance: L{objects.Instance}
3158 @param instance: the instance that is being migrated
3159 @rtype: L{objects.MigrationStatus}
3160 @return: the status of the current migration (one of
3161 L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
3162 progress info that can be retrieved from the hypervisor
3163 @raise RPCFail: If the migration status cannot be retrieved
3164
3165 """
3166 hyper = hypervisor.GetHypervisor(instance.hypervisor)
3167 try:
3168 return hyper.GetMigrationStatus(instance)
3169 except Exception, err: # pylint: disable=W0703
3170 _Fail("Failed to get migration status: %s", err, exc=True)
3171
3172
3173 def HotplugDevice(instance, action, dev_type, device, extra, seq):
3174 """Hotplug a device
3175
3176 Hotplug is currently supported only for KVM Hypervisor.
3177 @type instance: L{objects.Instance}
3178 @param instance: the instance to which we hotplug a device
3179 @type action: string
3180 @param action: the hotplug action to perform
3181 @type dev_type: string
3182 @param dev_type: the device type to hotplug
3183 @type device: either L{objects.NIC} or L{objects.Disk}
3184 @param device: the device object to hotplug
3185 @type extra: tuple
3186 @param extra: extra info used for disk hotplug (disk link, drive uri)
3187 @type seq: int
3188 @param seq: the index of the device from master perspective
3189 @raise RPCFail: in case instance does not have KVM hypervisor
3190
3191 """
3192 hyper = hypervisor.GetHypervisor(instance.hypervisor)
3193 try:
3194 hyper.VerifyHotplugSupport(instance, action, dev_type)
3195 except errors.HotplugError, err:
3196 _Fail("Hotplug is not supported: %s", err)
3197
3198 if action == constants.HOTPLUG_ACTION_ADD:
3199 fn = hyper.HotAddDevice
3200 elif action == constants.HOTPLUG_ACTION_REMOVE:
3201 fn = hyper.HotDelDevice
3202 elif action == constants.HOTPLUG_ACTION_MODIFY:
3203 fn = hyper.HotModDevice
3204 else:
3205 assert action in constants.HOTPLUG_ALL_ACTIONS
3206
3207 return fn(instance, dev_type, device, extra, seq)
3208
3209
3210 def HotplugSupported(instance):
3211 """Checks if hotplug is generally supported.
3212
3213 """
3214 hyper = hypervisor.GetHypervisor(instance.hypervisor)
3215 try:
3216 hyper.HotplugSupported(instance)
3217 except errors.HotplugError, err:
3218 _Fail("Hotplug is not supported: %s", err)
3219
3220
3221 def ModifyInstanceMetadata(metadata):
3222 """Sends instance data to the metadata daemon.
3223
3224 Uses the Luxi transport layer to communicate with the metadata
3225 daemon configuration server. It starts the metadata daemon if it is
3226 not running.
3227 The daemon must be enabled during at configuration time.
3228
3229 @type metadata: dict
3230 @param metadata: instance metadata obtained by calling
3231 L{objects.Instance.ToDict} on an instance object
3232
3233 """
3234 if not constants.ENABLE_METAD:
3235 raise errors.ProgrammerError("The metadata deamon is disabled, yet"
3236 " ModifyInstanceMetadata has been called")
3237
3238 if not utils.IsDaemonAlive(constants.METAD):
3239 result = utils.RunCmd([pathutils.DAEMON_UTIL, "start", constants.METAD])
3240 if result.failed:
3241 raise errors.HypervisorError("Failed to start metadata daemon")
3242
3243 with contextlib.closing(metad.Client()) as client:
3244 client.UpdateConfig(metadata)
3245
3246
3247 def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
3248 """Creates a block device for an instance.
3249
3250 @type disk: L{objects.Disk}
3251 @param disk: the object describing the disk we should create
3252 @type size: int
3253 @param size: the size of the physical underlying device, in MiB
3254 @type owner: str
3255 @param owner: the name of the instance for which disk is created,
3256 used for device cache data
3257 @type on_primary: boolean
3258 @param on_primary: indicates if it is the primary node or not
3259 @type info: string
3260 @param info: string that will be sent to the physical device
3261 creation, used for example to set (LVM) tags on LVs
3262 @type excl_stor: boolean
3263 @param excl_stor: Whether exclusive_storage is active
3264
3265 @return: the new unique_id of the device (this can sometime be
3266 computed only after creation), or None. On secondary nodes,
3267 it's not required to return anything.
3268
3269 """
3270 # TODO: remove the obsolete "size" argument
3271 # pylint: disable=W0613
3272 clist = []
3273 if disk.children:
3274 for child in disk.children:
3275 try:
3276 crdev = _RecursiveAssembleBD(child, owner, on_primary)
3277 except errors.BlockDeviceError, err:
3278 _Fail("Can't assemble device %s: %s", child, err)
3279 if on_primary or disk.AssembleOnSecondary():
3280 # we need the children open in case the device itself has to
3281 # be assembled
3282 try:
3283 # pylint: disable=E1103
3284 crdev.Open()
3285 except errors.BlockDeviceError, err:
3286 _Fail("Can't make child '%s' read-write: %s", child, err)
3287 clist.append(crdev)
3288
3289 try:
3290 device = bdev.Create(disk, clist, excl_stor)
3291 except errors.BlockDeviceError, err:
3292 _Fail("Can't create block device: %s", err)
3293
3294 if on_primary or disk.AssembleOnSecondary():
3295 try:
3296 device.Assemble()
3297 except errors.BlockDeviceError, err:
3298 _Fail("Can't assemble device after creation, unusual event: %s", err)
3299 if on_primary or disk.OpenOnSecondary():
3300 try:
3301 device.Open(force=True)
3302 except errors.BlockDeviceError, err:
3303 _Fail("Can't make device r/w after creation, unusual event: %s", err)
3304 DevCacheManager.UpdateCache(device.dev_path, owner,
3305 on_primary, disk.iv_name)
3306
3307 device.SetInfo(info)
3308
3309 return device.unique_id
3310
3311
3312 def _DumpDevice(source_path, target_path, offset, size, truncate):
3313 """This function images/wipes the device using a local file.
3314
3315 @type source_path: string
3316 @param source_path: path of the image or data source (e.g., "/dev/zero")
3317
3318 @type target_path: string
3319 @param target_path: path of the device to image/wipe
3320
3321 @type offset: int
3322 @param offset: offset in MiB in the output file
3323
3324 @type size: int
3325 @param size: maximum size in MiB to write (data source might be smaller)
3326
3327 @type truncate: bool
3328 @param truncate: whether the file should be truncated
3329
3330 @return: None
3331 @raise RPCFail: in case of failure
3332
3333 """
3334 # Internal sizes are always in Mebibytes; if the following "dd" command
3335 # should use a different block size the offset and size given to this
3336 # function must be adjusted accordingly before being passed to "dd".
3337 block_size = constants.DD_BLOCK_SIZE
3338
3339 cmd = [constants.DD_CMD, "if=%s" % source_path, "seek=%d" % offset,
3340 "bs=%s" % block_size, "oflag=direct", "of=%s" % target_path,
3341 "count=%d" % size]
3342
3343 if not truncate:
3344 cmd.append("conv=notrunc")
3345
3346 result = utils.RunCmd(cmd)
3347
3348 if result.failed:
3349 _Fail("Dump command '%s' exited with error: %s; output: %s", result.cmd,
3350 result.fail_reason, result.output)
3351
3352
3353 def _DownloadAndDumpDevice(source_url, target_path, size):
3354 """This function images a device using a downloaded image file.
3355
3356 @type source_url: string
3357 @param source_url: URL of image to dump to disk
3358
3359 @type target_path: string
3360 @param target_path: path of the device to image
3361
3362 @type size: int
3363 @param size: maximum size in MiB to write (data source might be smaller)
3364
3365 @rtype: NoneType
3366 @return: None
3367 @raise RPCFail: in case of download or write failures
3368
3369 """
3370 class DDParams(object):
3371 def __init__(self, current_size, total_size):
3372 self.current_size = current_size
3373 self.total_size = total_size
3374 self.image_size_error = False
3375
3376 def dd_write(ddparams, out):
3377 if ddparams.current_size < ddparams.total_size:
3378 ddparams.current_size += len(out)
3379 target_file.write(out)
3380 else:
3381 ddparams.image_size_error = True
3382 return -1
3383
3384 target_file = open(target_path, "r+")
3385 ddparams = DDParams(0, 1024 * 1024 * size)
3386
3387 curl = pycurl.Curl()
3388 curl.setopt(pycurl.VERBOSE, True)
3389 curl.setopt(pycurl.NOSIGNAL, True)
3390 curl.setopt(pycurl.USERAGENT, http.HTTP_GANETI_VERSION)
3391 curl.setopt(pycurl.URL, source_url)
3392 curl.setopt(pycurl.WRITEFUNCTION, lambda out: dd_write(ddparams, out))
3393
3394 try:
3395 curl.perform()
3396 except pycurl.error:
3397 if ddparams.image_size_error:
3398 _Fail("Disk image larger than the disk")
3399 else:
3400 raise
3401
3402 target_file.close()
3403
3404
3405 def BlockdevConvert(src_disk, target_disk):
3406 """Copies data from source block device to target.
3407
3408 This function gets the export and import commands from the source and
3409 target devices respectively, and then concatenates them to a single
3410 command using a pipe ("|"). Finally, executes the unified command that
3411 will transfer the data between the devices during the disk template
3412 conversion operation.
3413
3414 @type src_disk: L{objects.Disk}
3415 @param src_disk: the disk object we want to copy from
3416 @type target_disk: L{objects.Disk}
3417 @param target_disk: the disk object we want to copy to
3418
3419 @rtype: NoneType
3420 @return: None
3421 @raise RPCFail: in case of failure
3422
3423 """
3424 src_dev = _RecursiveFindBD(src_disk)
3425 if src_dev is None:
3426 _Fail("Cannot copy from device '%s': device not found", src_disk.uuid)
3427
3428 dest_dev = _RecursiveFindBD(target_disk)
3429 if dest_dev is None:
3430 _Fail("Cannot copy to device '%s': device not found", target_disk.uuid)
3431
3432 src_cmd = src_dev.Export()
3433 dest_cmd = dest_dev.Import()
3434 command = "%s | %s" % (utils.ShellQuoteArgs(src_cmd),
3435 utils.ShellQuoteArgs(dest_cmd))
3436
3437 result = utils.RunCmd(command)
3438 if result.failed:
3439 _Fail("Disk conversion command '%s' exited with error: %s; output: %s",
3440 result.cmd, result.fail_reason, result.output)
3441
3442
3443 def BlockdevWipe(disk, offset, size):
3444 """Wipes a block device.
3445
3446 @type disk: L{objects.Disk}
3447 @param disk: the disk object we want to wipe
3448 @type offset: int
3449 @param offset: The offset in MiB in the file
3450 @type size: int
3451 @param size: The size in MiB to write
3452
3453 """
3454 try:
3455 rdev = _RecursiveFindBD(disk)
3456 except errors.BlockDeviceError:
3457 rdev = None
3458
3459 if not rdev:
3460 _Fail("Cannot wipe device %s: device not found", disk.iv_name)
3461 if offset < 0:
3462 _Fail("Negative offset")
3463 if size < 0:
3464 _Fail("Negative size")
3465 if offset > rdev.size:
3466 _Fail("Wipe offset is bigger than device size")
3467 if (offset + size) > rdev.size:
3468 _Fail("Wipe offset and size are bigger than device size")
3469
3470 _DumpDevice("/dev/zero", rdev.dev_path, offset, size, True)
3471
3472
3473 def BlockdevImage(disk, image, size):
3474 """Images a block device either by dumping a local file or
3475 downloading a URL.
3476
3477 @type disk: L{objects.Disk}
3478 @param disk: the disk object we want to image
3479
3480 @type image: string
3481 @param image: file path to the disk image be dumped
3482
3483 @type size: int
3484 @param size: The size in MiB to write
3485
3486 @rtype: NoneType
3487 @return: None
3488 @raise RPCFail: in case of failure
3489
3490 """
3491 if not (utils.IsUrl(image) or os.path.exists(image)):
3492 _Fail("Image '%s' not found", image)
3493
3494 try:
3495 rdev = _RecursiveFindBD(disk)
3496 except errors.BlockDeviceError:
3497 rdev = None
3498
3499 if not rdev:
3500 _Fail("Cannot image device %s: device not found", disk.iv_name)
3501 if size < 0:
3502 _Fail("Negative size")
3503 if size > rdev.size:
3504 _Fail("Image size is bigger than device size")
3505
3506 if utils.IsUrl(image):
3507 _DownloadAndDumpDevice(image, rdev.dev_path, size)
3508 else:
3509 _DumpDevice(image, rdev.dev_path, 0, size, False)
3510
3511
3512 def BlockdevPauseResumeSync(disks, pause):
3513 """Pause or resume the sync of the block device.
3514
3515 @type disks: list of L{objects.Disk}
3516 @param disks: the disks object we want to pause/resume
3517 @type pause: bool
3518 @param pause: Wheater to pause or resume
3519
3520 """
3521 success = []
3522 for disk in disks:
3523 try:
3524 rdev = _RecursiveFindBD(disk)
3525 except errors.BlockDeviceError:
3526 rdev = None
3527
3528 if not rdev:
3529 success.append((False, ("Cannot change sync for device %s:"
3530 " device not found" % disk.iv_name)))
3531 continue
3532
3533 result = rdev.PauseResumeSync(pause)
3534
3535 if result:
3536 success.append((result, None))
3537 else:
3538 if pause:
3539 msg = "Pause"
3540 else:
3541 msg = "Resume"
3542 success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
3543
3544 return success
3545
3546
3547 def BlockdevRemove(disk):
3548 """Remove a block device.
3549
3550 @note: This is intended to be called recursively.
3551
3552 @type disk: L{objects.Disk}
3553 @param disk: the disk object we should remove
3554 @rtype: boolean
3555 @return: the success of the operation
3556
3557 """
3558 msgs = []
3559 try:
3560 rdev = _RecursiveFindBD(disk)
3561 except errors.BlockDeviceError, err:
3562 # probably can't attach
3563 logging.info("Can't attach to device %s in remove", disk)
3564 rdev = None
3565 if rdev is not None:
3566 r_path = rdev.dev_path
3567
3568 def _TryRemove():
3569 try:
3570 rdev.Remove()
3571 return []
3572 except errors.BlockDeviceError, err:
3573 return [str(err)]
3574
3575 msgs.extend(utils.SimpleRetry([], _TryRemove,
3576 constants.DISK_REMOVE_RETRY_INTERVAL,
3577 constants.DISK_REMOVE_RETRY_TIMEOUT))
3578
3579 if not msgs:
3580 DevCacheManager.RemoveCache(r_path)
3581
3582 if disk.children:
3583 for child in disk.children:
3584 try:
3585 BlockdevRemove(child)
3586 except RPCFail, err:
3587 msgs.append(str(err))
3588
3589 if msgs:
3590 _Fail("; ".join(msgs))
3591
3592
3593 def _RecursiveAssembleBD(disk, owner, as_primary):
3594 """Activate a block device for an instance.
3595
3596 This is run on the primary and secondary nodes for an instance.
3597
3598 @note: this function is called recursively.
3599
3600 @type disk: L{objects.Disk}
3601 @param disk: the disk we try to assemble
3602 @type owner: str
3603 @param owner: the name of the instance which owns the disk
3604 @type as_primary: boolean
3605 @param as_primary: if we should make the block device
3606 read/write
3607
3608 @return: the assembled device or None (in case no device
3609 was assembled)
3610 @raise errors.BlockDeviceError: in case there is an error
3611 during the activation of the children or the device
3612 itself
3613
3614 """
3615 children = []
3616 if disk.children:
3617 mcn = disk.ChildrenNeeded()
3618 if mcn == -1:
3619 mcn = 0 # max number of Nones allowed
3620 else:
3621 mcn = len(disk.children) - mcn # max number of Nones
3622 for chld_disk in disk.children:
3623 try:
3624 cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
3625 except errors.BlockDeviceError, err:
3626 if children.count(None) >= mcn:
3627 raise
3628 cdev = None
3629 logging.error("Error in child activation (but continuing): %s",
3630 str(err))
3631 children.append(cdev)
3632
3633 if as_primary or disk.AssembleOnSecondary():
3634 r_dev = bdev.Assemble(disk, children)
3635 result = r_dev
3636 if as_primary or disk.OpenOnSecondary():
3637 r_dev.Open()
3638 DevCacheManager.UpdateCache(r_dev.dev_path, owner,
3639 as_primary, disk.iv_name)
3640
3641 else:
3642 result = True
3643 return result
3644
3645
3646 def BlockdevAssemble(disk, instance, as_primary, idx):
3647 """Activate a block device for an instance.
3648
3649 This is a wrapper over _RecursiveAssembleBD.
3650
3651 @rtype: str or boolean
3652 @return: a tuple with the C{/dev/...} path and the created symlink
3653 for primary nodes, and (C{True}, C{True}) for secondary nodes
3654
3655 """
3656 try:
3657 result = _RecursiveAssembleBD(disk, instance.name, as_primary)
3658 if isinstance(result, BlockDev):
3659 # pylint: disable=E1103
3660 dev_path = result.dev_path
3661 link_name = None
3662 uri = None
3663 if as_primary:
3664 link_name = _SymlinkBlockDev(instance.name, dev_path, idx)
3665 uri = _CalculateDeviceURI(instance, disk, result)
3666 elif result:
3667 return result, result
3668 else:
3669 _Fail("Unexpected result from _RecursiveAssembleBD")
3670 except errors.BlockDeviceError, err:
3671 _Fail("Error while assembling disk: %s", err, exc=True)
3672 except OSError, err:
3673 _Fail("Error while symlinking disk: %s", err, exc=True)
3674
3675 return dev_path, link_name, uri
3676
3677
3678 def BlockdevShutdown(disk):
3679 """Shut down a block device.
3680
3681 First, if the device is assembled (Attach() is successful), then
3682 the device is shutdown. Then the children of the device are
3683 shutdown.
3684
3685 This function is called recursively. Note that we don't cache the
3686 children or such, as oppossed to assemble, shutdown of different
3687 devices doesn't require that the upper device was active.
3688
3689 @type disk: L{objects.Disk}
3690 @param disk: the description of the disk we should
3691 shutdown
3692 @rtype: None
3693
3694 """
3695 msgs = []
3696 r_dev = _RecursiveFindBD(disk)
3697 if r_dev is not None:
3698 r_path = r_dev.dev_path
3699 try:
3700 r_dev.Shutdown()
3701 DevCacheManager.RemoveCache(r_path)
3702 except errors.BlockDeviceError, err:
3703 msgs.append(str(err))
3704
3705 if disk.children:
3706 for child in disk.children:
3707 try:
3708 BlockdevShutdown(child)
3709 except RPCFail, err:
3710 msgs.append(str(err))
3711
3712 if msgs:
3713 _Fail("; ".join(msgs))
3714
3715
3716 def BlockdevAddchildren(parent_cdev, new_cdevs):
3717 """Extend a mirrored block device.
3718
3719 @type parent_cdev: L{objects.Disk}
3720 @param parent_cdev: the disk to which we should add children
3721 @type new_cdevs: list of L{objects.Disk}
3722 @param new_cdevs: the list of children which we should add
3723 @rtype: None
3724
3725 """
3726 parent_bdev = _RecursiveFindBD(parent_cdev)
3727 if parent_bdev is None:
3728 _Fail("Can't find parent device '%s' in add children", parent_cdev)
3729 new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
3730 if new_bdevs.count(None) > 0:
3731 _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
3732 parent_bdev.AddChildren(new_bdevs)
3733
3734
3735 def BlockdevRemovechildren(parent_cdev, new_cdevs):
3736 """Shrink a mirrored block device.
3737
3738 @type parent_cdev: L{objects.Disk}
3739 @param parent_cdev: the disk from which we should remove children
3740 @type new_cdevs: list of L{objects.Disk}
3741 @param new_cdevs: the list of children which we should remove
3742 @rtype: None
3743
3744 """
3745 parent_bdev = _RecursiveFindBD(parent_cdev)
3746 if parent_bdev is None:
3747 _Fail("Can't find parent device '%s' in remove children", parent_cdev)
3748 devs = []
3749 for disk in new_cdevs:
3750 rpath = disk.StaticDevPath()
3751 if rpath is None:
3752 bd = _RecursiveFindBD(disk)
3753 if bd is None:
3754 _Fail("Can't find device %s while removing children", disk)
3755 else:
3756 devs.append(bd.dev_path)
3757 else:
3758 if not utils.IsNormAbsPath(rpath):
3759 _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
3760 devs.append(rpath)
3761 parent_bdev.RemoveChildren(devs)
3762
3763
3764 def BlockdevGetmirrorstatus(disks):
3765 """Get the mirroring status of a list of devices.
3766
3767 @type disks: list of L{objects.Disk}
3768 @param disks: the list of disks which we should query
3769 @rtype: disk
3770 @return: List of L{objects.BlockDevStatus}, one for each disk
3771 @raise errors.BlockDeviceError: if any of the disks cannot be
3772 found
3773
3774 """
3775 stats = []
3776 for dsk in disks:
3777 rbd = _RecursiveFindBD(dsk)
3778 if rbd is None:
3779 _Fail("Can't find device %s", dsk)
3780
3781 stats.append(rbd.CombinedSyncStatus())
3782
3783 return stats
3784
3785
3786 def BlockdevGetmirrorstatusMulti(disks):
3787 """Get the mirroring status of a list of devices.
3788
3789 @type disks: list of L{objects.Disk}
3790 @param disks: the list of disks which we should query
3791 @rtype: disk
3792 @return: List of tuples, (bool, status), one for each disk; bool denotes
3793 success/failure, status is L{objects.BlockDevStatus} on success, string
3794 otherwise
3795
3796 """
3797 result = []
3798 for disk in disks:
3799 try:
3800 rbd = _RecursiveFindBD(disk)
3801 if rbd is None:
3802 result.append((False, "Can't find device %s" % disk))
3803 continue
3804
3805 status = rbd.CombinedSyncStatus()
3806 except errors.BlockDeviceError, err:
3807 logging.exception("Error while getting disk status")
3808 result.append((False, str(err)))
3809 else:
3810 result.append((True, status))
3811
3812 assert len(disks) == len(result)
3813
3814 return result
3815
3816
3817 def _RecursiveFindBD(disk):
3818 """Check if a device is activated.
3819
3820 If so, return information about the real device.
3821
3822 @type disk: L{objects.Disk}
3823 @param disk: the disk object we need to find
3824
3825 @return: None if the device can't be found,
3826 otherwise the device instance
3827
3828 """
3829 children = []
3830 if disk.children:
3831 for chdisk in disk.children:
3832 children.append(_RecursiveFindBD(chdisk))
3833
3834 return bdev.FindDevice(disk, children)
3835
3836
3837 def _OpenRealBD(disk):
3838 """Opens the underlying block device of a disk.
3839
3840 @type disk: L{objects.Disk}
3841 @param disk: the disk object we want to open
3842
3843 """
3844 real_disk = _RecursiveFindBD(disk)
3845 if real_disk is None:
3846 _Fail("Block device '%s' is not set up", disk)
3847
3848 real_disk.Open()
3849
3850 return real_disk
3851
3852
3853 def BlockdevFind(disk):
3854 """Check if a device is activated.
3855
3856 If it is, return information about the real device.
3857
3858 @type disk: L{objects.Disk}
3859 @param disk: the disk to find
3860 @rtype: None or objects.BlockDevStatus
3861 @return: None if the disk cannot be found, otherwise a the current
3862 information
3863
3864 """
3865 try:
3866 rbd = _RecursiveFindBD(disk)
3867 except errors.BlockDeviceError, err:
3868 _Fail("Failed to find device: %s", err, exc=True)
3869
3870 if rbd is None:
3871 return None
3872
3873 return rbd.GetSyncStatus()
3874
3875
3876 def BlockdevGetdimensions(disks):
3877 """Computes the size of the given disks.
3878
3879 If a disk is not found, returns None instead.
3880
3881 @type disks: list of L{objects.Disk}
3882 @param disks: the list of disk to compute the size for
3883 @rtype: list
3884 @return: list with elements None if the disk cannot be found,
3885 otherwise the pair (size, spindles), where spindles is None if the
3886 device doesn't support that
3887
3888 """
3889 result = []
3890 for cf in disks:
3891 try:
3892 rbd = _RecursiveFindBD(cf)
3893 except errors.BlockDeviceError:
3894 result.append(None)
3895 continue
3896 if rbd is None:
3897 result.append(None)
3898 else:
3899 result.append(rbd.GetActualDimensions())
3900 return result
3901
3902
3903 def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
3904 """Write a file to the filesystem.
3905
3906 This allows the master to overwrite(!) a file. It will only perform
3907 the operation if the file belongs to a list of configuration files.
3908
3909 @type file_name: str
3910 @param file_name: the target file name
3911 @type data: str
3912 @param data: the new contents of the file
3913 @type mode: int
3914 @param mode: the mode to give the file (can be None)
3915 @type uid: string
3916 @param uid: the owner of the file
3917 @type gid: string
3918 @param gid: the group of the file
3919 @type atime: float
3920 @param atime: the atime to set on the file (can be None)
3921 @type mtime: float
3922 @param mtime: the mtime to set on the file (can be None)
3923 @rtype: None
3924
3925 """
3926 file_name = vcluster.LocalizeVirtualPath(file_name)
3927
3928 if not os.path.isabs