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