Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 75bf3149

History | View | Annotate | Download (131.2 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Google Inc.
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful, but
12
# WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
# General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19
# 02110-1301, USA.
20

    
21

    
22
"""Functions used by the node daemon
23

24
@var _ALLOWED_UPLOAD_FILES: denotes which files are accepted in
25
     the L{UploadFile} function
26
@var _ALLOWED_CLEAN_DIRS: denotes which directories are accepted
27
     in the L{_CleanDirectory} function
28

29
"""
30

    
31
# pylint: disable=E1103
32

    
33
# E1103: %s %r has no %r member (but some types could not be
34
# inferred), because the _TryOSFromDisk returns either (True, os_obj)
35
# or (False, "string") which confuses pylint
36

    
37

    
38
import os
39
import os.path
40
import shutil
41
import time
42
import stat
43
import errno
44
import re
45
import random
46
import logging
47
import tempfile
48
import zlib
49
import base64
50
import signal
51

    
52
from ganeti import errors
53
from ganeti import utils
54
from ganeti import ssh
55
from ganeti import hypervisor
56
from ganeti import constants
57
from ganeti.storage import bdev
58
from ganeti.storage import drbd
59
from ganeti import objects
60
from ganeti import ssconf
61
from ganeti import serializer
62
from ganeti import netutils
63
from ganeti import runtime
64
from ganeti import compat
65
from ganeti import pathutils
66
from ganeti import vcluster
67
from ganeti import ht
68
from ganeti.storage.base import BlockDev
69
from ganeti.storage.drbd import DRBD8
70
from ganeti import hooksmaster
71

    
72

    
73
_BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id"
74
_ALLOWED_CLEAN_DIRS = compat.UniqueFrozenset([
75
  pathutils.DATA_DIR,
76
  pathutils.JOB_QUEUE_ARCHIVE_DIR,
77
  pathutils.QUEUE_DIR,
78
  pathutils.CRYPTO_KEYS_DIR,
79
  ])
80
_MAX_SSL_CERT_VALIDITY = 7 * 24 * 60 * 60
81
_X509_KEY_FILE = "key"
82
_X509_CERT_FILE = "cert"
83
_IES_STATUS_FILE = "status"
84
_IES_PID_FILE = "pid"
85
_IES_CA_FILE = "ca"
86

    
87
#: Valid LVS output line regex
88
_LVSLINE_REGEX = re.compile("^ *([^|]+)\|([^|]+)\|([0-9.]+)\|([^|]{6,})\|?$")
89

    
90
# Actions for the master setup script
91
_MASTER_START = "start"
92
_MASTER_STOP = "stop"
93

    
94
#: Maximum file permissions for restricted command directory and executables
95
_RCMD_MAX_MODE = (stat.S_IRWXU |
96
                  stat.S_IRGRP | stat.S_IXGRP |
97
                  stat.S_IROTH | stat.S_IXOTH)
98

    
99
#: Delay before returning an error for restricted commands
100
_RCMD_INVALID_DELAY = 10
101

    
102
#: How long to wait to acquire lock for restricted commands (shorter than
103
#: L{_RCMD_INVALID_DELAY}) to reduce blockage of noded forks when many
104
#: command requests arrive
105
_RCMD_LOCK_TIMEOUT = _RCMD_INVALID_DELAY * 0.8
106

    
107

    
108
class RPCFail(Exception):
109
  """Class denoting RPC failure.
110

111
  Its argument is the error message.
112

113
  """
114

    
115

    
116
def _GetInstReasonFilename(instance_name):
117
  """Path of the file containing the reason of the instance status change.
118

119
  @type instance_name: string
120
  @param instance_name: The name of the instance
121
  @rtype: string
122
  @return: The path of the file
123

124
  """
125
  return utils.PathJoin(pathutils.INSTANCE_REASON_DIR, instance_name)
126

    
127

    
128
def _StoreInstReasonTrail(instance_name, trail):
129
  """Serialize a reason trail related to an instance change of state to file.
130

131
  The exact location of the file depends on the name of the instance and on
132
  the configuration of the Ganeti cluster defined at deploy time.
133

134
  @type instance_name: string
135
  @param instance_name: The name of the instance
136
  @rtype: None
137

138
  """
139
  json = serializer.DumpJson(trail)
140
  filename = _GetInstReasonFilename(instance_name)
141
  utils.WriteFile(filename, data=json)
142

    
143

    
144
def _Fail(msg, *args, **kwargs):
145
  """Log an error and the raise an RPCFail exception.
146

147
  This exception is then handled specially in the ganeti daemon and
148
  turned into a 'failed' return type. As such, this function is a
149
  useful shortcut for logging the error and returning it to the master
150
  daemon.
151

152
  @type msg: string
153
  @param msg: the text of the exception
154
  @raise RPCFail
155

156
  """
157
  if args:
158
    msg = msg % args
159
  if "log" not in kwargs or kwargs["log"]: # if we should log this error
160
    if "exc" in kwargs and kwargs["exc"]:
161
      logging.exception(msg)
162
    else:
163
      logging.error(msg)
164
  raise RPCFail(msg)
165

    
166

    
167
def _GetConfig():
168
  """Simple wrapper to return a SimpleStore.
169

170
  @rtype: L{ssconf.SimpleStore}
171
  @return: a SimpleStore instance
172

173
  """
174
  return ssconf.SimpleStore()
175

    
176

    
177
def _GetSshRunner(cluster_name):
178
  """Simple wrapper to return an SshRunner.
179

180
  @type cluster_name: str
181
  @param cluster_name: the cluster name, which is needed
182
      by the SshRunner constructor
183
  @rtype: L{ssh.SshRunner}
184
  @return: an SshRunner instance
185

186
  """
187
  return ssh.SshRunner(cluster_name)
188

    
189

    
190
def _Decompress(data):
191
  """Unpacks data compressed by the RPC client.
192

193
  @type data: list or tuple
194
  @param data: Data sent by RPC client
195
  @rtype: str
196
  @return: Decompressed data
197

198
  """
199
  assert isinstance(data, (list, tuple))
200
  assert len(data) == 2
201
  (encoding, content) = data
202
  if encoding == constants.RPC_ENCODING_NONE:
203
    return content
204
  elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
205
    return zlib.decompress(base64.b64decode(content))
206
  else:
207
    raise AssertionError("Unknown data encoding")
208

    
209

    
210
def _CleanDirectory(path, exclude=None):
211
  """Removes all regular files in a directory.
212

213
  @type path: str
214
  @param path: the directory to clean
215
  @type exclude: list
216
  @param exclude: list of files to be excluded, defaults
217
      to the empty list
218

219
  """
220
  if path not in _ALLOWED_CLEAN_DIRS:
221
    _Fail("Path passed to _CleanDirectory not in allowed clean targets: '%s'",
222
          path)
223

    
224
  if not os.path.isdir(path):
225
    return
226
  if exclude is None:
227
    exclude = []
228
  else:
229
    # Normalize excluded paths
230
    exclude = [os.path.normpath(i) for i in exclude]
231

    
232
  for rel_name in utils.ListVisibleFiles(path):
233
    full_name = utils.PathJoin(path, rel_name)
234
    if full_name in exclude:
235
      continue
236
    if os.path.isfile(full_name) and not os.path.islink(full_name):
237
      utils.RemoveFile(full_name)
238

    
239

    
240
def _BuildUploadFileList():
241
  """Build the list of allowed upload files.
242

243
  This is abstracted so that it's built only once at module import time.
244

245
  """
246
  allowed_files = set([
247
    pathutils.CLUSTER_CONF_FILE,
248
    pathutils.ETC_HOSTS,
249
    pathutils.SSH_KNOWN_HOSTS_FILE,
250
    pathutils.VNC_PASSWORD_FILE,
251
    pathutils.RAPI_CERT_FILE,
252
    pathutils.SPICE_CERT_FILE,
253
    pathutils.SPICE_CACERT_FILE,
254
    pathutils.RAPI_USERS_FILE,
255
    pathutils.CONFD_HMAC_KEY,
256
    pathutils.CLUSTER_DOMAIN_SECRET_FILE,
257
    ])
258

    
259
  for hv_name in constants.HYPER_TYPES:
260
    hv_class = hypervisor.GetHypervisorClass(hv_name)
261
    allowed_files.update(hv_class.GetAncillaryFiles()[0])
262

    
263
  assert pathutils.FILE_STORAGE_PATHS_FILE not in allowed_files, \
264
    "Allowed file storage paths should never be uploaded via RPC"
265

    
266
  return frozenset(allowed_files)
267

    
268

    
269
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
270

    
271

    
272
def JobQueuePurge():
273
  """Removes job queue files and archived jobs.
274

275
  @rtype: tuple
276
  @return: True, None
277

278
  """
279
  _CleanDirectory(pathutils.QUEUE_DIR, exclude=[pathutils.JOB_QUEUE_LOCK_FILE])
280
  _CleanDirectory(pathutils.JOB_QUEUE_ARCHIVE_DIR)
281

    
282

    
283
def GetMasterInfo():
284
  """Returns master information.
285

286
  This is an utility function to compute master information, either
287
  for consumption here or from the node daemon.
288

289
  @rtype: tuple
290
  @return: master_netdev, master_ip, master_name, primary_ip_family,
291
    master_netmask
292
  @raise RPCFail: in case of errors
293

294
  """
295
  try:
296
    cfg = _GetConfig()
297
    master_netdev = cfg.GetMasterNetdev()
298
    master_ip = cfg.GetMasterIP()
299
    master_netmask = cfg.GetMasterNetmask()
300
    master_node = cfg.GetMasterNode()
301
    primary_ip_family = cfg.GetPrimaryIPFamily()
302
  except errors.ConfigurationError, err:
303
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
304
  return (master_netdev, master_ip, master_node, primary_ip_family,
305
          master_netmask)
306

    
307

    
308
def RunLocalHooks(hook_opcode, hooks_path, env_builder_fn):
309
  """Decorator that runs hooks before and after the decorated function.
310

311
  @type hook_opcode: string
312
  @param hook_opcode: opcode of the hook
313
  @type hooks_path: string
314
  @param hooks_path: path of the hooks
315
  @type env_builder_fn: function
316
  @param env_builder_fn: function that returns a dictionary containing the
317
    environment variables for the hooks. Will get all the parameters of the
318
    decorated function.
319
  @raise RPCFail: in case of pre-hook failure
320

321
  """
322
  def decorator(fn):
323
    def wrapper(*args, **kwargs):
324
      _, myself = ssconf.GetMasterAndMyself()
325
      nodes = ([myself], [myself])  # these hooks run locally
326

    
327
      env_fn = compat.partial(env_builder_fn, *args, **kwargs)
328

    
329
      cfg = _GetConfig()
330
      hr = HooksRunner()
331
      hm = hooksmaster.HooksMaster(hook_opcode, hooks_path, nodes,
332
                                   hr.RunLocalHooks, None, env_fn,
333
                                   logging.warning, cfg.GetClusterName(),
334
                                   cfg.GetMasterNode())
335
      hm.RunPhase(constants.HOOKS_PHASE_PRE)
336
      result = fn(*args, **kwargs)
337
      hm.RunPhase(constants.HOOKS_PHASE_POST)
338

    
339
      return result
340
    return wrapper
341
  return decorator
342

    
343

    
344
def _BuildMasterIpEnv(master_params, use_external_mip_script=None):
345
  """Builds environment variables for master IP hooks.
346

347
  @type master_params: L{objects.MasterNetworkParameters}
348
  @param master_params: network parameters of the master
349
  @type use_external_mip_script: boolean
350
  @param use_external_mip_script: whether to use an external master IP
351
    address setup script (unused, but necessary per the implementation of the
352
    _RunLocalHooks decorator)
353

354
  """
355
  # pylint: disable=W0613
356
  ver = netutils.IPAddress.GetVersionFromAddressFamily(master_params.ip_family)
357
  env = {
358
    "MASTER_NETDEV": master_params.netdev,
359
    "MASTER_IP": master_params.ip,
360
    "MASTER_NETMASK": str(master_params.netmask),
361
    "CLUSTER_IP_VERSION": str(ver),
362
  }
363

    
364
  return env
365

    
366

    
367
def _RunMasterSetupScript(master_params, action, use_external_mip_script):
368
  """Execute the master IP address setup script.
369

370
  @type master_params: L{objects.MasterNetworkParameters}
371
  @param master_params: network parameters of the master
372
  @type action: string
373
  @param action: action to pass to the script. Must be one of
374
    L{backend._MASTER_START} or L{backend._MASTER_STOP}
375
  @type use_external_mip_script: boolean
376
  @param use_external_mip_script: whether to use an external master IP
377
    address setup script
378
  @raise backend.RPCFail: if there are errors during the execution of the
379
    script
380

381
  """
382
  env = _BuildMasterIpEnv(master_params)
383

    
384
  if use_external_mip_script:
385
    setup_script = pathutils.EXTERNAL_MASTER_SETUP_SCRIPT
386
  else:
387
    setup_script = pathutils.DEFAULT_MASTER_SETUP_SCRIPT
388

    
389
  result = utils.RunCmd([setup_script, action], env=env, reset_env=True)
390

    
391
  if result.failed:
392
    _Fail("Failed to %s the master IP. Script return value: %s, output: '%s'" %
393
          (action, result.exit_code, result.output), log=True)
394

    
395

    
396
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNUP, "master-ip-turnup",
397
               _BuildMasterIpEnv)
398
def ActivateMasterIp(master_params, use_external_mip_script):
399
  """Activate the IP address of the master daemon.
400

401
  @type master_params: L{objects.MasterNetworkParameters}
402
  @param master_params: network parameters of the master
403
  @type use_external_mip_script: boolean
404
  @param use_external_mip_script: whether to use an external master IP
405
    address setup script
406
  @raise RPCFail: in case of errors during the IP startup
407

408
  """
409
  _RunMasterSetupScript(master_params, _MASTER_START,
410
                        use_external_mip_script)
411

    
412

    
413
def StartMasterDaemons(no_voting):
414
  """Activate local node as master node.
415

416
  The function will start the master daemons (ganeti-masterd and ganeti-rapi).
417

418
  @type no_voting: boolean
419
  @param no_voting: whether to start ganeti-masterd without a node vote
420
      but still non-interactively
421
  @rtype: None
422

423
  """
424

    
425
  if no_voting:
426
    masterd_args = "--no-voting --yes-do-it"
427
  else:
428
    masterd_args = ""
429

    
430
  env = {
431
    "EXTRA_MASTERD_ARGS": masterd_args,
432
    }
433

    
434
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "start-master"], env=env)
435
  if result.failed:
436
    msg = "Can't start Ganeti master: %s" % result.output
437
    logging.error(msg)
438
    _Fail(msg)
439

    
440

    
441
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNDOWN, "master-ip-turndown",
442
               _BuildMasterIpEnv)
443
def DeactivateMasterIp(master_params, use_external_mip_script):
444
  """Deactivate the master IP on this node.
445

446
  @type master_params: L{objects.MasterNetworkParameters}
447
  @param master_params: network parameters of the master
448
  @type use_external_mip_script: boolean
449
  @param use_external_mip_script: whether to use an external master IP
450
    address setup script
451
  @raise RPCFail: in case of errors during the IP turndown
452

453
  """
454
  _RunMasterSetupScript(master_params, _MASTER_STOP,
455
                        use_external_mip_script)
456

    
457

    
458
def StopMasterDaemons():
459
  """Stop the master daemons on this node.
460

461
  Stop the master daemons (ganeti-masterd and ganeti-rapi) on this node.
462

463
  @rtype: None
464

465
  """
466
  # TODO: log and report back to the caller the error failures; we
467
  # need to decide in which case we fail the RPC for this
468

    
469
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop-master"])
470
  if result.failed:
471
    logging.error("Could not stop Ganeti master, command %s had exitcode %s"
472
                  " and error %s",
473
                  result.cmd, result.exit_code, result.output)
474

    
475

    
476
def ChangeMasterNetmask(old_netmask, netmask, master_ip, master_netdev):
477
  """Change the netmask of the master IP.
478

479
  @param old_netmask: the old value of the netmask
480
  @param netmask: the new value of the netmask
481
  @param master_ip: the master IP
482
  @param master_netdev: the master network device
483

484
  """
485
  if old_netmask == netmask:
486
    return
487

    
488
  if not netutils.IPAddress.Own(master_ip):
489
    _Fail("The master IP address is not up, not attempting to change its"
490
          " netmask")
491

    
492
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
493
                         "%s/%s" % (master_ip, netmask),
494
                         "dev", master_netdev, "label",
495
                         "%s:0" % master_netdev])
496
  if result.failed:
497
    _Fail("Could not set the new netmask on the master IP address")
498

    
499
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
500
                         "%s/%s" % (master_ip, old_netmask),
501
                         "dev", master_netdev, "label",
502
                         "%s:0" % master_netdev])
503
  if result.failed:
504
    _Fail("Could not bring down the master IP address with the old netmask")
505

    
506

    
507
def EtcHostsModify(mode, host, ip):
508
  """Modify a host entry in /etc/hosts.
509

510
  @param mode: The mode to operate. Either add or remove entry
511
  @param host: The host to operate on
512
  @param ip: The ip associated with the entry
513

514
  """
515
  if mode == constants.ETC_HOSTS_ADD:
516
    if not ip:
517
      RPCFail("Mode 'add' needs 'ip' parameter, but parameter not"
518
              " present")
519
    utils.AddHostToEtcHosts(host, ip)
520
  elif mode == constants.ETC_HOSTS_REMOVE:
521
    if ip:
522
      RPCFail("Mode 'remove' does not allow 'ip' parameter, but"
523
              " parameter is present")
524
    utils.RemoveHostFromEtcHosts(host)
525
  else:
526
    RPCFail("Mode not supported")
527

    
528

    
529
def LeaveCluster(modify_ssh_setup):
530
  """Cleans up and remove the current node.
531

532
  This function cleans up and prepares the current node to be removed
533
  from the cluster.
534

535
  If processing is successful, then it raises an
536
  L{errors.QuitGanetiException} which is used as a special case to
537
  shutdown the node daemon.
538

539
  @param modify_ssh_setup: boolean
540

541
  """
542
  _CleanDirectory(pathutils.DATA_DIR)
543
  _CleanDirectory(pathutils.CRYPTO_KEYS_DIR)
544
  JobQueuePurge()
545

    
546
  if modify_ssh_setup:
547
    try:
548
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.SSH_LOGIN_USER)
549

    
550
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
551

    
552
      utils.RemoveFile(priv_key)
553
      utils.RemoveFile(pub_key)
554
    except errors.OpExecError:
555
      logging.exception("Error while processing ssh files")
556

    
557
  try:
558
    utils.RemoveFile(pathutils.CONFD_HMAC_KEY)
559
    utils.RemoveFile(pathutils.RAPI_CERT_FILE)
560
    utils.RemoveFile(pathutils.SPICE_CERT_FILE)
561
    utils.RemoveFile(pathutils.SPICE_CACERT_FILE)
562
    utils.RemoveFile(pathutils.NODED_CERT_FILE)
563
  except: # pylint: disable=W0702
564
    logging.exception("Error while removing cluster secrets")
565

    
566
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop", constants.CONFD])
567
  if result.failed:
568
    logging.error("Command %s failed with exitcode %s and error %s",
569
                  result.cmd, result.exit_code, result.output)
570

    
571
  # Raise a custom exception (handled in ganeti-noded)
572
  raise errors.QuitGanetiException(True, "Shutdown scheduled")
573

    
574

    
575
def _GetVgInfo(name, excl_stor):
576
  """Retrieves information about a LVM volume group.
577

578
  """
579
  # TODO: GetVGInfo supports returning information for multiple VGs at once
580
  vginfo = bdev.LogicalVolume.GetVGInfo([name], excl_stor)
581
  if vginfo:
582
    vg_free = int(round(vginfo[0][0], 0))
583
    vg_size = int(round(vginfo[0][1], 0))
584
  else:
585
    vg_free = None
586
    vg_size = None
587

    
588
  return {
589
    "name": name,
590
    "vg_free": vg_free,
591
    "vg_size": vg_size,
592
    }
593

    
594

    
595
def _GetVgSpindlesInfo(name, excl_stor):
596
  """Retrieves information about spindles in an LVM volume group.
597

598
  @type name: string
599
  @param name: VG name
600
  @type excl_stor: bool
601
  @param excl_stor: exclusive storage
602
  @rtype: dict
603
  @return: dictionary whose keys are "name", "vg_free", "vg_size" for VG name,
604
      free spindles, total spindles respectively
605

606
  """
607
  if excl_stor:
608
    (vg_free, vg_size) = bdev.LogicalVolume.GetVgSpindlesInfo(name)
609
  else:
610
    vg_free = 0
611
    vg_size = 0
612
  return {
613
    "name": name,
614
    "vg_free": vg_free,
615
    "vg_size": vg_size,
616
    }
617

    
618

    
619
def _GetHvInfo(name):
620
  """Retrieves node information from a hypervisor.
621

622
  The information returned depends on the hypervisor. Common items:
623

624
    - vg_size is the size of the configured volume group in MiB
625
    - vg_free is the free size of the volume group in MiB
626
    - memory_dom0 is the memory allocated for domain0 in MiB
627
    - memory_free is the currently available (free) ram in MiB
628
    - memory_total is the total number of ram in MiB
629
    - hv_version: the hypervisor version, if available
630

631
  """
632
  return hypervisor.GetHypervisor(name).GetNodeInfo()
633

    
634

    
635
def _GetNamedNodeInfo(names, fn):
636
  """Calls C{fn} for all names in C{names} and returns a dictionary.
637

638
  @rtype: None or dict
639

640
  """
641
  if names is None:
642
    return None
643
  else:
644
    return map(fn, names)
645

    
646

    
647
def GetNodeInfo(storage_units, hv_names, excl_stor):
648
  """Gives back a hash with different information about the node.
649

650
  @type storage_units: list of pairs (string, string)
651
  @param storage_units: List of pairs (storage unit, identifier) to ask for disk
652
                        space information. In case of lvm-vg, the identifier is
653
                        the VG name.
654
  @type hv_names: list of string
655
  @param hv_names: Names of the hypervisors to ask for node information
656
  @type excl_stor: boolean
657
  @param excl_stor: Whether exclusive_storage is active
658
  @rtype: tuple; (string, None/dict, None/dict)
659
  @return: Tuple containing boot ID, volume group information and hypervisor
660
    information
661

662
  """
663
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
664
  storage_info = _GetNamedNodeInfo(
665
    storage_units,
666
    (lambda storage_unit: _ApplyStorageInfoFunction(storage_unit[0],
667
                                                    storage_unit[1],
668
                                                    excl_stor)))
669
  hv_info = _GetNamedNodeInfo(hv_names, _GetHvInfo)
670

    
671
  return (bootid, storage_info, hv_info)
672

    
673

    
674
# FIXME: implement storage reporting for all missing storage types.
675
_STORAGE_TYPE_INFO_FN = {
676
  constants.ST_BLOCK: None,
677
  constants.ST_DISKLESS: None,
678
  constants.ST_EXT: None,
679
  constants.ST_FILE: None,
680
  constants.ST_LVM_PV: _GetVgSpindlesInfo,
681
  constants.ST_LVM_VG: _GetVgInfo,
682
  constants.ST_RADOS: None,
683
}
684

    
685

    
686
def _ApplyStorageInfoFunction(storage_type, storage_key, *args):
687
  """Looks up and applies the correct function to calculate free and total
688
  storage for the given storage type.
689

690
  @type storage_type: string
691
  @param storage_type: the storage type for which the storage shall be reported.
692
  @type storage_key: string
693
  @param storage_key: identifier of a storage unit, e.g. the volume group name
694
    of an LVM storage unit
695
  @type args: any
696
  @param args: various parameters that can be used for storage reporting. These
697
    parameters and their semantics vary from storage type to storage type and
698
    are just propagated in this function.
699
  @return: the results of the application of the storage space function (see
700
    _STORAGE_TYPE_INFO_FN) if storage space reporting is implemented for that
701
    storage type
702
  @raises NotImplementedError: for storage types who don't support space
703
    reporting yet
704
  """
705
  fn = _STORAGE_TYPE_INFO_FN[storage_type]
706
  if fn is not None:
707
    return fn(storage_key, *args)
708
  else:
709
    raise NotImplementedError
710

    
711

    
712
def _CheckExclusivePvs(pvi_list):
713
  """Check that PVs are not shared among LVs
714

715
  @type pvi_list: list of L{objects.LvmPvInfo} objects
716
  @param pvi_list: information about the PVs
717

718
  @rtype: list of tuples (string, list of strings)
719
  @return: offending volumes, as tuples: (pv_name, [lv1_name, lv2_name...])
720

721
  """
722
  res = []
723
  for pvi in pvi_list:
724
    if len(pvi.lv_list) > 1:
725
      res.append((pvi.name, pvi.lv_list))
726
  return res
727

    
728

    
729
def _VerifyHypervisors(what, vm_capable, result, all_hvparams,
730
                       get_hv_fn=hypervisor.GetHypervisor):
731
  """Verifies the hypervisor. Appends the results to the 'results' list.
732

733
  @type what: C{dict}
734
  @param what: a dictionary of things to check
735
  @type vm_capable: boolean
736
  @param vm_capable: whether or not this not is vm capable
737
  @type result: dict
738
  @param result: dictionary of verification results; results of the
739
    verifications in this function will be added here
740
  @type all_hvparams: dict of dict of string
741
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
742
  @type get_hv_fn: function
743
  @param get_hv_fn: function to retrieve the hypervisor, to improve testability
744

745
  """
746
  if not vm_capable:
747
    return
748

    
749
  if constants.NV_HYPERVISOR in what:
750
    result[constants.NV_HYPERVISOR] = {}
751
    for hv_name in what[constants.NV_HYPERVISOR]:
752
      hvparams = all_hvparams[hv_name]
753
      try:
754
        val = get_hv_fn(hv_name).Verify(hvparams=hvparams)
755
      except errors.HypervisorError, err:
756
        val = "Error while checking hypervisor: %s" % str(err)
757
      result[constants.NV_HYPERVISOR][hv_name] = val
758

    
759

    
760
def _VerifyHvparams(what, vm_capable, result,
761
                    get_hv_fn=hypervisor.GetHypervisor):
762
  """Verifies the hvparams. Appends the results to the 'results' list.
763

764
  @type what: C{dict}
765
  @param what: a dictionary of things to check
766
  @type vm_capable: boolean
767
  @param vm_capable: whether or not this not is vm capable
768
  @type result: dict
769
  @param result: dictionary of verification results; results of the
770
    verifications in this function will be added here
771
  @type get_hv_fn: function
772
  @param get_hv_fn: function to retrieve the hypervisor, to improve testability
773

774
  """
775
  if not vm_capable:
776
    return
777

    
778
  if constants.NV_HVPARAMS in what:
779
    result[constants.NV_HVPARAMS] = []
780
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
781
      try:
782
        logging.info("Validating hv %s, %s", hv_name, hvparms)
783
        get_hv_fn(hv_name).ValidateParameters(hvparms)
784
      except errors.HypervisorError, err:
785
        result[constants.NV_HVPARAMS].append((source, hv_name, str(err)))
786

    
787

    
788
def VerifyNode(what, cluster_name):
789
  """Verify the status of the local node.
790

791
  Based on the input L{what} parameter, various checks are done on the
792
  local node.
793

794
  If the I{filelist} key is present, this list of
795
  files is checksummed and the file/checksum pairs are returned.
796

797
  If the I{nodelist} key is present, we check that we have
798
  connectivity via ssh with the target nodes (and check the hostname
799
  report).
800

801
  If the I{node-net-test} key is present, we check that we have
802
  connectivity to the given nodes via both primary IP and, if
803
  applicable, secondary IPs.
804

805
  @type what: C{dict}
806
  @param what: a dictionary of things to check:
807
      - filelist: list of files for which to compute checksums
808
      - nodelist: list of nodes we should check ssh communication with
809
      - node-net-test: list of nodes we should check node daemon port
810
        connectivity with
811
      - hypervisor: list with hypervisors to run the verify for
812

813
  @rtype: dict
814
  @return: a dictionary with the same keys as the input dict, and
815
      values representing the result of the checks
816

817
  """
818
  result = {}
819
  my_name = netutils.Hostname.GetSysName()
820
  port = netutils.GetDaemonPort(constants.NODED)
821
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
822

    
823
  _VerifyHypervisors(what, vm_capable, result, all_hvparams)
824
  _VerifyHvparams(what, vm_capable, result)
825

    
826
  if constants.NV_FILELIST in what:
827
    fingerprints = utils.FingerprintFiles(map(vcluster.LocalizeVirtualPath,
828
                                              what[constants.NV_FILELIST]))
829
    result[constants.NV_FILELIST] = \
830
      dict((vcluster.MakeVirtualPath(key), value)
831
           for (key, value) in fingerprints.items())
832

    
833
  if constants.NV_NODELIST in what:
834
    (nodes, bynode) = what[constants.NV_NODELIST]
835

    
836
    # Add nodes from other groups (different for each node)
837
    try:
838
      nodes.extend(bynode[my_name])
839
    except KeyError:
840
      pass
841

    
842
    # Use a random order
843
    random.shuffle(nodes)
844

    
845
    # Try to contact all nodes
846
    val = {}
847
    for node in nodes:
848
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
849
      if not success:
850
        val[node] = message
851

    
852
    result[constants.NV_NODELIST] = val
853

    
854
  if constants.NV_NODENETTEST in what:
855
    result[constants.NV_NODENETTEST] = tmp = {}
856
    my_pip = my_sip = None
857
    for name, pip, sip in what[constants.NV_NODENETTEST]:
858
      if name == my_name:
859
        my_pip = pip
860
        my_sip = sip
861
        break
862
    if not my_pip:
863
      tmp[my_name] = ("Can't find my own primary/secondary IP"
864
                      " in the node list")
865
    else:
866
      for name, pip, sip in what[constants.NV_NODENETTEST]:
867
        fail = []
868
        if not netutils.TcpPing(pip, port, source=my_pip):
869
          fail.append("primary")
870
        if sip != pip:
871
          if not netutils.TcpPing(sip, port, source=my_sip):
872
            fail.append("secondary")
873
        if fail:
874
          tmp[name] = ("failure using the %s interface(s)" %
875
                       " and ".join(fail))
876

    
877
  if constants.NV_MASTERIP in what:
878
    # FIXME: add checks on incoming data structures (here and in the
879
    # rest of the function)
880
    master_name, master_ip = what[constants.NV_MASTERIP]
881
    if master_name == my_name:
882
      source = constants.IP4_ADDRESS_LOCALHOST
883
    else:
884
      source = None
885
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
886
                                                     source=source)
887

    
888
  if constants.NV_USERSCRIPTS in what:
889
    result[constants.NV_USERSCRIPTS] = \
890
      [script for script in what[constants.NV_USERSCRIPTS]
891
       if not utils.IsExecutable(script)]
892

    
893
  if constants.NV_OOB_PATHS in what:
894
    result[constants.NV_OOB_PATHS] = tmp = []
895
    for path in what[constants.NV_OOB_PATHS]:
896
      try:
897
        st = os.stat(path)
898
      except OSError, err:
899
        tmp.append("error stating out of band helper: %s" % err)
900
      else:
901
        if stat.S_ISREG(st.st_mode):
902
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
903
            tmp.append(None)
904
          else:
905
            tmp.append("out of band helper %s is not executable" % path)
906
        else:
907
          tmp.append("out of band helper %s is not a file" % path)
908

    
909
  if constants.NV_LVLIST in what and vm_capable:
910
    try:
911
      val = GetVolumeList(utils.ListVolumeGroups().keys())
912
    except RPCFail, err:
913
      val = str(err)
914
    result[constants.NV_LVLIST] = val
915

    
916
  if constants.NV_INSTANCELIST in what and vm_capable:
917
    # GetInstanceList can fail
918
    try:
919
      val = GetInstanceList(what[constants.NV_INSTANCELIST])
920
    except RPCFail, err:
921
      val = str(err)
922
    result[constants.NV_INSTANCELIST] = val
923

    
924
  if constants.NV_VGLIST in what and vm_capable:
925
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
926

    
927
  if constants.NV_PVLIST in what and vm_capable:
928
    check_exclusive_pvs = constants.NV_EXCLUSIVEPVS in what
929
    val = bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
930
                                       filter_allocatable=False,
931
                                       include_lvs=check_exclusive_pvs)
932
    if check_exclusive_pvs:
933
      result[constants.NV_EXCLUSIVEPVS] = _CheckExclusivePvs(val)
934
      for pvi in val:
935
        # Avoid sending useless data on the wire
936
        pvi.lv_list = []
937
    result[constants.NV_PVLIST] = map(objects.LvmPvInfo.ToDict, val)
938

    
939
  if constants.NV_VERSION in what:
940
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
941
                                    constants.RELEASE_VERSION)
942

    
943
  if constants.NV_HVINFO in what and vm_capable:
944
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
945
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
946

    
947
  if constants.NV_DRBDVERSION in what and vm_capable:
948
    try:
949
      drbd_version = DRBD8.GetProcInfo().GetVersionString()
950
    except errors.BlockDeviceError, err:
951
      logging.warning("Can't get DRBD version", exc_info=True)
952
      drbd_version = str(err)
953
    result[constants.NV_DRBDVERSION] = drbd_version
954

    
955
  if constants.NV_DRBDLIST in what and vm_capable:
956
    try:
957
      used_minors = drbd.DRBD8.GetUsedDevs()
958
    except errors.BlockDeviceError, err:
959
      logging.warning("Can't get used minors list", exc_info=True)
960
      used_minors = str(err)
961
    result[constants.NV_DRBDLIST] = used_minors
962

    
963
  if constants.NV_DRBDHELPER in what and vm_capable:
964
    status = True
965
    try:
966
      payload = drbd.DRBD8.GetUsermodeHelper()
967
    except errors.BlockDeviceError, err:
968
      logging.error("Can't get DRBD usermode helper: %s", str(err))
969
      status = False
970
      payload = str(err)
971
    result[constants.NV_DRBDHELPER] = (status, payload)
972

    
973
  if constants.NV_NODESETUP in what:
974
    result[constants.NV_NODESETUP] = tmpr = []
975
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
976
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
977
                  " under /sys, missing required directories /sys/block"
978
                  " and /sys/class/net")
979
    if (not os.path.isdir("/proc/sys") or
980
        not os.path.isfile("/proc/sysrq-trigger")):
981
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
982
                  " under /proc, missing required directory /proc/sys and"
983
                  " the file /proc/sysrq-trigger")
984

    
985
  if constants.NV_TIME in what:
986
    result[constants.NV_TIME] = utils.SplitTime(time.time())
987

    
988
  if constants.NV_OSLIST in what and vm_capable:
989
    result[constants.NV_OSLIST] = DiagnoseOS()
990

    
991
  if constants.NV_BRIDGES in what and vm_capable:
992
    result[constants.NV_BRIDGES] = [bridge
993
                                    for bridge in what[constants.NV_BRIDGES]
994
                                    if not utils.BridgeExists(bridge)]
995

    
996
  if what.get(constants.NV_FILE_STORAGE_PATHS) == my_name:
997
    result[constants.NV_FILE_STORAGE_PATHS] = \
998
      bdev.ComputeWrongFileStoragePaths()
999

    
1000
  return result
1001

    
1002

    
1003
def GetBlockDevSizes(devices):
1004
  """Return the size of the given block devices
1005

1006
  @type devices: list
1007
  @param devices: list of block device nodes to query
1008
  @rtype: dict
1009
  @return:
1010
    dictionary of all block devices under /dev (key). The value is their
1011
    size in MiB.
1012

1013
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
1014

1015
  """
1016
  DEV_PREFIX = "/dev/"
1017
  blockdevs = {}
1018

    
1019
  for devpath in devices:
1020
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
1021
      continue
1022

    
1023
    try:
1024
      st = os.stat(devpath)
1025
    except EnvironmentError, err:
1026
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
1027
      continue
1028

    
1029
    if stat.S_ISBLK(st.st_mode):
1030
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
1031
      if result.failed:
1032
        # We don't want to fail, just do not list this device as available
1033
        logging.warning("Cannot get size for block device %s", devpath)
1034
        continue
1035

    
1036
      size = int(result.stdout) / (1024 * 1024)
1037
      blockdevs[devpath] = size
1038
  return blockdevs
1039

    
1040

    
1041
def GetVolumeList(vg_names):
1042
  """Compute list of logical volumes and their size.
1043

1044
  @type vg_names: list
1045
  @param vg_names: the volume groups whose LVs we should list, or
1046
      empty for all volume groups
1047
  @rtype: dict
1048
  @return:
1049
      dictionary of all partions (key) with value being a tuple of
1050
      their size (in MiB), inactive and online status::
1051

1052
        {'xenvg/test1': ('20.06', True, True)}
1053

1054
      in case of errors, a string is returned with the error
1055
      details.
1056

1057
  """
1058
  lvs = {}
1059
  sep = "|"
1060
  if not vg_names:
1061
    vg_names = []
1062
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1063
                         "--separator=%s" % sep,
1064
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
1065
  if result.failed:
1066
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
1067

    
1068
  for line in result.stdout.splitlines():
1069
    line = line.strip()
1070
    match = _LVSLINE_REGEX.match(line)
1071
    if not match:
1072
      logging.error("Invalid line returned from lvs output: '%s'", line)
1073
      continue
1074
    vg_name, name, size, attr = match.groups()
1075
    inactive = attr[4] == "-"
1076
    online = attr[5] == "o"
1077
    virtual = attr[0] == "v"
1078
    if virtual:
1079
      # we don't want to report such volumes as existing, since they
1080
      # don't really hold data
1081
      continue
1082
    lvs[vg_name + "/" + name] = (size, inactive, online)
1083

    
1084
  return lvs
1085

    
1086

    
1087
def ListVolumeGroups():
1088
  """List the volume groups and their size.
1089

1090
  @rtype: dict
1091
  @return: dictionary with keys volume name and values the
1092
      size of the volume
1093

1094
  """
1095
  return utils.ListVolumeGroups()
1096

    
1097

    
1098
def NodeVolumes():
1099
  """List all volumes on this node.
1100

1101
  @rtype: list
1102
  @return:
1103
    A list of dictionaries, each having four keys:
1104
      - name: the logical volume name,
1105
      - size: the size of the logical volume
1106
      - dev: the physical device on which the LV lives
1107
      - vg: the volume group to which it belongs
1108

1109
    In case of errors, we return an empty list and log the
1110
    error.
1111

1112
    Note that since a logical volume can live on multiple physical
1113
    volumes, the resulting list might include a logical volume
1114
    multiple times.
1115

1116
  """
1117
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1118
                         "--separator=|",
1119
                         "--options=lv_name,lv_size,devices,vg_name"])
1120
  if result.failed:
1121
    _Fail("Failed to list logical volumes, lvs output: %s",
1122
          result.output)
1123

    
1124
  def parse_dev(dev):
1125
    return dev.split("(")[0]
1126

    
1127
  def handle_dev(dev):
1128
    return [parse_dev(x) for x in dev.split(",")]
1129

    
1130
  def map_line(line):
1131
    line = [v.strip() for v in line]
1132
    return [{"name": line[0], "size": line[1],
1133
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
1134

    
1135
  all_devs = []
1136
  for line in result.stdout.splitlines():
1137
    if line.count("|") >= 3:
1138
      all_devs.extend(map_line(line.split("|")))
1139
    else:
1140
      logging.warning("Strange line in the output from lvs: '%s'", line)
1141
  return all_devs
1142

    
1143

    
1144
def BridgesExist(bridges_list):
1145
  """Check if a list of bridges exist on the current node.
1146

1147
  @rtype: boolean
1148
  @return: C{True} if all of them exist, C{False} otherwise
1149

1150
  """
1151
  missing = []
1152
  for bridge in bridges_list:
1153
    if not utils.BridgeExists(bridge):
1154
      missing.append(bridge)
1155

    
1156
  if missing:
1157
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
1158

    
1159

    
1160
def GetInstanceListForHypervisor(hname, hvparams=None,
1161
                                 get_hv_fn=hypervisor.GetHypervisor):
1162
  """Provides a list of instances of the given hypervisor.
1163

1164
  @type hname: string
1165
  @param hname: name of the hypervisor
1166
  @type hvparams: dict of strings
1167
  @param hvparams: hypervisor parameters for the given hypervisor
1168
  @type get_hv_fn: function
1169
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1170
    name; optional parameter to increase testability
1171

1172
  @rtype: list
1173
  @return: a list of all running instances on the current node
1174
    - instance1.example.com
1175
    - instance2.example.com
1176

1177
  """
1178
  results = []
1179
  try:
1180
    hv = get_hv_fn(hname)
1181
    names = hv.ListInstances(hvparams)
1182
    results.extend(names)
1183
  except errors.HypervisorError, err:
1184
    _Fail("Error enumerating instances (hypervisor %s): %s",
1185
          hname, err, exc=True)
1186
  return results
1187

    
1188

    
1189
def GetInstanceList(hypervisor_list, all_hvparams=None,
1190
                    get_hv_fn=hypervisor.GetHypervisor):
1191
  """Provides a list of instances.
1192

1193
  @type hypervisor_list: list
1194
  @param hypervisor_list: the list of hypervisors to query information
1195
  @type all_hvparams: dict of dict of strings
1196
  @param all_hvparams: a dictionary mapping hypervisor types to respective
1197
    cluster-wide hypervisor parameters
1198
  @type get_hv_fn: function
1199
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1200
    name; optional parameter to increase testability
1201

1202
  @rtype: list
1203
  @return: a list of all running instances on the current node
1204
    - instance1.example.com
1205
    - instance2.example.com
1206

1207
  """
1208
  results = []
1209
  for hname in hypervisor_list:
1210
    hvparams = None
1211
    if all_hvparams is not None:
1212
      hvparams = all_hvparams[hname]
1213
    results.extend(GetInstanceListForHypervisor(hname, hvparams,
1214
                                                get_hv_fn=get_hv_fn))
1215
  return results
1216

    
1217

    
1218
def GetInstanceInfo(instance, hname):
1219
  """Gives back the information about an instance as a dictionary.
1220

1221
  @type instance: string
1222
  @param instance: the instance name
1223
  @type hname: string
1224
  @param hname: the hypervisor type of the instance
1225

1226
  @rtype: dict
1227
  @return: dictionary with the following keys:
1228
      - memory: memory size of instance (int)
1229
      - state: xen state of instance (string)
1230
      - time: cpu time of instance (float)
1231
      - vcpus: the number of vcpus (int)
1232

1233
  """
1234
  output = {}
1235

    
1236
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
1237
  if iinfo is not None:
1238
    output["memory"] = iinfo[2]
1239
    output["vcpus"] = iinfo[3]
1240
    output["state"] = iinfo[4]
1241
    output["time"] = iinfo[5]
1242

    
1243
  return output
1244

    
1245

    
1246
def GetInstanceMigratable(instance):
1247
  """Computes whether an instance can be migrated.
1248

1249
  @type instance: L{objects.Instance}
1250
  @param instance: object representing the instance to be checked.
1251

1252
  @rtype: tuple
1253
  @return: tuple of (result, description) where:
1254
      - result: whether the instance can be migrated or not
1255
      - description: a description of the issue, if relevant
1256

1257
  """
1258
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1259
  iname = instance.name
1260
  if iname not in hyper.ListInstances(instance.hvparams):
1261
    _Fail("Instance %s is not running", iname)
1262

    
1263
  for idx in range(len(instance.disks)):
1264
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1265
    if not os.path.islink(link_name):
1266
      logging.warning("Instance %s is missing symlink %s for disk %d",
1267
                      iname, link_name, idx)
1268

    
1269

    
1270
def GetAllInstancesInfo(hypervisor_list):
1271
  """Gather data about all instances.
1272

1273
  This is the equivalent of L{GetInstanceInfo}, except that it
1274
  computes data for all instances at once, thus being faster if one
1275
  needs data about more than one instance.
1276

1277
  @type hypervisor_list: list
1278
  @param hypervisor_list: list of hypervisors to query for instance data
1279

1280
  @rtype: dict
1281
  @return: dictionary of instance: data, with data having the following keys:
1282
      - memory: memory size of instance (int)
1283
      - state: xen state of instance (string)
1284
      - time: cpu time of instance (float)
1285
      - vcpus: the number of vcpus
1286

1287
  """
1288
  output = {}
1289

    
1290
  for hname in hypervisor_list:
1291
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
1292
    if iinfo:
1293
      for name, _, memory, vcpus, state, times in iinfo:
1294
        value = {
1295
          "memory": memory,
1296
          "vcpus": vcpus,
1297
          "state": state,
1298
          "time": times,
1299
          }
1300
        if name in output:
1301
          # we only check static parameters, like memory and vcpus,
1302
          # and not state and time which can change between the
1303
          # invocations of the different hypervisors
1304
          for key in "memory", "vcpus":
1305
            if value[key] != output[name][key]:
1306
              _Fail("Instance %s is running twice"
1307
                    " with different parameters", name)
1308
        output[name] = value
1309

    
1310
  return output
1311

    
1312

    
1313
def _InstanceLogName(kind, os_name, instance, component):
1314
  """Compute the OS log filename for a given instance and operation.
1315

1316
  The instance name and os name are passed in as strings since not all
1317
  operations have these as part of an instance object.
1318

1319
  @type kind: string
1320
  @param kind: the operation type (e.g. add, import, etc.)
1321
  @type os_name: string
1322
  @param os_name: the os name
1323
  @type instance: string
1324
  @param instance: the name of the instance being imported/added/etc.
1325
  @type component: string or None
1326
  @param component: the name of the component of the instance being
1327
      transferred
1328

1329
  """
1330
  # TODO: Use tempfile.mkstemp to create unique filename
1331
  if component:
1332
    assert "/" not in component
1333
    c_msg = "-%s" % component
1334
  else:
1335
    c_msg = ""
1336
  base = ("%s-%s-%s%s-%s.log" %
1337
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1338
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1339

    
1340

    
1341
def InstanceOsAdd(instance, reinstall, debug):
1342
  """Add an OS to an instance.
1343

1344
  @type instance: L{objects.Instance}
1345
  @param instance: Instance whose OS is to be installed
1346
  @type reinstall: boolean
1347
  @param reinstall: whether this is an instance reinstall
1348
  @type debug: integer
1349
  @param debug: debug level, passed to the OS scripts
1350
  @rtype: None
1351

1352
  """
1353
  inst_os = OSFromDisk(instance.os)
1354

    
1355
  create_env = OSEnvironment(instance, inst_os, debug)
1356
  if reinstall:
1357
    create_env["INSTANCE_REINSTALL"] = "1"
1358

    
1359
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1360

    
1361
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1362
                        cwd=inst_os.path, output=logfile, reset_env=True)
1363
  if result.failed:
1364
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1365
                  " output: %s", result.cmd, result.fail_reason, logfile,
1366
                  result.output)
1367
    lines = [utils.SafeEncode(val)
1368
             for val in utils.TailFile(logfile, lines=20)]
1369
    _Fail("OS create script failed (%s), last lines in the"
1370
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1371

    
1372

    
1373
def RunRenameInstance(instance, old_name, debug):
1374
  """Run the OS rename script for an instance.
1375

1376
  @type instance: L{objects.Instance}
1377
  @param instance: Instance whose OS is to be installed
1378
  @type old_name: string
1379
  @param old_name: previous instance name
1380
  @type debug: integer
1381
  @param debug: debug level, passed to the OS scripts
1382
  @rtype: boolean
1383
  @return: the success of the operation
1384

1385
  """
1386
  inst_os = OSFromDisk(instance.os)
1387

    
1388
  rename_env = OSEnvironment(instance, inst_os, debug)
1389
  rename_env["OLD_INSTANCE_NAME"] = old_name
1390

    
1391
  logfile = _InstanceLogName("rename", instance.os,
1392
                             "%s-%s" % (old_name, instance.name), None)
1393

    
1394
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1395
                        cwd=inst_os.path, output=logfile, reset_env=True)
1396

    
1397
  if result.failed:
1398
    logging.error("os create command '%s' returned error: %s output: %s",
1399
                  result.cmd, result.fail_reason, result.output)
1400
    lines = [utils.SafeEncode(val)
1401
             for val in utils.TailFile(logfile, lines=20)]
1402
    _Fail("OS rename script failed (%s), last lines in the"
1403
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1404

    
1405

    
1406
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1407
  """Returns symlink path for block device.
1408

1409
  """
1410
  if _dir is None:
1411
    _dir = pathutils.DISK_LINKS_DIR
1412

    
1413
  return utils.PathJoin(_dir,
1414
                        ("%s%s%s" %
1415
                         (instance_name, constants.DISK_SEPARATOR, idx)))
1416

    
1417

    
1418
def _SymlinkBlockDev(instance_name, device_path, idx):
1419
  """Set up symlinks to a instance's block device.
1420

1421
  This is an auxiliary function run when an instance is start (on the primary
1422
  node) or when an instance is migrated (on the target node).
1423

1424

1425
  @param instance_name: the name of the target instance
1426
  @param device_path: path of the physical block device, on the node
1427
  @param idx: the disk index
1428
  @return: absolute path to the disk's symlink
1429

1430
  """
1431
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1432
  try:
1433
    os.symlink(device_path, link_name)
1434
  except OSError, err:
1435
    if err.errno == errno.EEXIST:
1436
      if (not os.path.islink(link_name) or
1437
          os.readlink(link_name) != device_path):
1438
        os.remove(link_name)
1439
        os.symlink(device_path, link_name)
1440
    else:
1441
      raise
1442

    
1443
  return link_name
1444

    
1445

    
1446
def _RemoveBlockDevLinks(instance_name, disks):
1447
  """Remove the block device symlinks belonging to the given instance.
1448

1449
  """
1450
  for idx, _ in enumerate(disks):
1451
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1452
    if os.path.islink(link_name):
1453
      try:
1454
        os.remove(link_name)
1455
      except OSError:
1456
        logging.exception("Can't remove symlink '%s'", link_name)
1457

    
1458

    
1459
def _GatherAndLinkBlockDevs(instance):
1460
  """Set up an instance's block device(s).
1461

1462
  This is run on the primary node at instance startup. The block
1463
  devices must be already assembled.
1464

1465
  @type instance: L{objects.Instance}
1466
  @param instance: the instance whose disks we shoul assemble
1467
  @rtype: list
1468
  @return: list of (disk_object, device_path)
1469

1470
  """
1471
  block_devices = []
1472
  for idx, disk in enumerate(instance.disks):
1473
    device = _RecursiveFindBD(disk)
1474
    if device is None:
1475
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1476
                                    str(disk))
1477
    device.Open()
1478
    try:
1479
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1480
    except OSError, e:
1481
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1482
                                    e.strerror)
1483

    
1484
    block_devices.append((disk, link_name))
1485

    
1486
  return block_devices
1487

    
1488

    
1489
def StartInstance(instance, startup_paused, reason, store_reason=True):
1490
  """Start an instance.
1491

1492
  @type instance: L{objects.Instance}
1493
  @param instance: the instance object
1494
  @type startup_paused: bool
1495
  @param instance: pause instance at startup?
1496
  @type reason: list of reasons
1497
  @param reason: the reason trail for this startup
1498
  @type store_reason: boolean
1499
  @param store_reason: whether to store the shutdown reason trail on file
1500
  @rtype: None
1501

1502
  """
1503
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1504
                                                   instance.hvparams)
1505

    
1506
  if instance.name in running_instances:
1507
    logging.info("Instance %s already running, not starting", instance.name)
1508
    return
1509

    
1510
  try:
1511
    block_devices = _GatherAndLinkBlockDevs(instance)
1512
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1513
    hyper.StartInstance(instance, block_devices, startup_paused)
1514
    if store_reason:
1515
      _StoreInstReasonTrail(instance.name, reason)
1516
  except errors.BlockDeviceError, err:
1517
    _Fail("Block device error: %s", err, exc=True)
1518
  except errors.HypervisorError, err:
1519
    _RemoveBlockDevLinks(instance.name, instance.disks)
1520
    _Fail("Hypervisor error: %s", err, exc=True)
1521

    
1522

    
1523
def InstanceShutdown(instance, timeout, reason, store_reason=True):
1524
  """Shut an instance down.
1525

1526
  @note: this functions uses polling with a hardcoded timeout.
1527

1528
  @type instance: L{objects.Instance}
1529
  @param instance: the instance object
1530
  @type timeout: integer
1531
  @param timeout: maximum timeout for soft shutdown
1532
  @type reason: list of reasons
1533
  @param reason: the reason trail for this shutdown
1534
  @type store_reason: boolean
1535
  @param store_reason: whether to store the shutdown reason trail on file
1536
  @rtype: None
1537

1538
  """
1539
  hv_name = instance.hypervisor
1540
  hyper = hypervisor.GetHypervisor(hv_name)
1541
  iname = instance.name
1542

    
1543
  if instance.name not in hyper.ListInstances(instance.hvparams):
1544
    logging.info("Instance %s not running, doing nothing", iname)
1545
    return
1546

    
1547
  class _TryShutdown:
1548
    def __init__(self):
1549
      self.tried_once = False
1550

    
1551
    def __call__(self):
1552
      if iname not in hyper.ListInstances(instance.hvparams):
1553
        return
1554

    
1555
      try:
1556
        hyper.StopInstance(instance, retry=self.tried_once)
1557
        if store_reason:
1558
          _StoreInstReasonTrail(instance.name, reason)
1559
      except errors.HypervisorError, err:
1560
        if iname not in hyper.ListInstances(instance.hvparams):
1561
          # if the instance is no longer existing, consider this a
1562
          # success and go to cleanup
1563
          return
1564

    
1565
        _Fail("Failed to stop instance %s: %s", iname, err)
1566

    
1567
      self.tried_once = True
1568

    
1569
      raise utils.RetryAgain()
1570

    
1571
  try:
1572
    utils.Retry(_TryShutdown(), 5, timeout)
1573
  except utils.RetryTimeout:
1574
    # the shutdown did not succeed
1575
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1576

    
1577
    try:
1578
      hyper.StopInstance(instance, force=True)
1579
    except errors.HypervisorError, err:
1580
      if iname in hyper.ListInstances(instance.hvparams):
1581
        # only raise an error if the instance still exists, otherwise
1582
        # the error could simply be "instance ... unknown"!
1583
        _Fail("Failed to force stop instance %s: %s", iname, err)
1584

    
1585
    time.sleep(1)
1586

    
1587
    if iname in hyper.ListInstances(instance.hvparams):
1588
      _Fail("Could not shutdown instance %s even by destroy", iname)
1589

    
1590
  try:
1591
    hyper.CleanupInstance(instance.name)
1592
  except errors.HypervisorError, err:
1593
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1594

    
1595
  _RemoveBlockDevLinks(iname, instance.disks)
1596

    
1597

    
1598
def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1599
  """Reboot an instance.
1600

1601
  @type instance: L{objects.Instance}
1602
  @param instance: the instance object to reboot
1603
  @type reboot_type: str
1604
  @param reboot_type: the type of reboot, one the following
1605
    constants:
1606
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1607
        instance OS, do not recreate the VM
1608
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1609
        restart the VM (at the hypervisor level)
1610
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1611
        not accepted here, since that mode is handled differently, in
1612
        cmdlib, and translates into full stop and start of the
1613
        instance (instead of a call_instance_reboot RPC)
1614
  @type shutdown_timeout: integer
1615
  @param shutdown_timeout: maximum timeout for soft shutdown
1616
  @type reason: list of reasons
1617
  @param reason: the reason trail for this reboot
1618
  @rtype: None
1619

1620
  """
1621
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1622
                                                   instance.hvparams)
1623

    
1624
  if instance.name not in running_instances:
1625
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1626

    
1627
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1628
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1629
    try:
1630
      hyper.RebootInstance(instance)
1631
    except errors.HypervisorError, err:
1632
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1633
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1634
    try:
1635
      InstanceShutdown(instance, shutdown_timeout, reason, store_reason=False)
1636
      result = StartInstance(instance, False, reason, store_reason=False)
1637
      _StoreInstReasonTrail(instance.name, reason)
1638
      return result
1639
    except errors.HypervisorError, err:
1640
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1641
  else:
1642
    _Fail("Invalid reboot_type received: %s", reboot_type)
1643

    
1644

    
1645
def InstanceBalloonMemory(instance, memory):
1646
  """Resize an instance's memory.
1647

1648
  @type instance: L{objects.Instance}
1649
  @param instance: the instance object
1650
  @type memory: int
1651
  @param memory: new memory amount in MB
1652
  @rtype: None
1653

1654
  """
1655
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1656
  running = hyper.ListInstances(instance.hvparams)
1657
  if instance.name not in running:
1658
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1659
    return
1660
  try:
1661
    hyper.BalloonInstanceMemory(instance, memory)
1662
  except errors.HypervisorError, err:
1663
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1664

    
1665

    
1666
def MigrationInfo(instance):
1667
  """Gather information about an instance to be migrated.
1668

1669
  @type instance: L{objects.Instance}
1670
  @param instance: the instance definition
1671

1672
  """
1673
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1674
  try:
1675
    info = hyper.MigrationInfo(instance)
1676
  except errors.HypervisorError, err:
1677
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1678
  return info
1679

    
1680

    
1681
def AcceptInstance(instance, info, target):
1682
  """Prepare the node to accept an instance.
1683

1684
  @type instance: L{objects.Instance}
1685
  @param instance: the instance definition
1686
  @type info: string/data (opaque)
1687
  @param info: migration information, from the source node
1688
  @type target: string
1689
  @param target: target host (usually ip), on this node
1690

1691
  """
1692
  # TODO: why is this required only for DTS_EXT_MIRROR?
1693
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1694
    # Create the symlinks, as the disks are not active
1695
    # in any way
1696
    try:
1697
      _GatherAndLinkBlockDevs(instance)
1698
    except errors.BlockDeviceError, err:
1699
      _Fail("Block device error: %s", err, exc=True)
1700

    
1701
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1702
  try:
1703
    hyper.AcceptInstance(instance, info, target)
1704
  except errors.HypervisorError, err:
1705
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1706
      _RemoveBlockDevLinks(instance.name, instance.disks)
1707
    _Fail("Failed to accept instance: %s", err, exc=True)
1708

    
1709

    
1710
def FinalizeMigrationDst(instance, info, success):
1711
  """Finalize any preparation to accept an instance.
1712

1713
  @type instance: L{objects.Instance}
1714
  @param instance: the instance definition
1715
  @type info: string/data (opaque)
1716
  @param info: migration information, from the source node
1717
  @type success: boolean
1718
  @param success: whether the migration was a success or a failure
1719

1720
  """
1721
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1722
  try:
1723
    hyper.FinalizeMigrationDst(instance, info, success)
1724
  except errors.HypervisorError, err:
1725
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1726

    
1727

    
1728
def MigrateInstance(instance, target, live):
1729
  """Migrates an instance to another node.
1730

1731
  @type instance: L{objects.Instance}
1732
  @param instance: the instance definition
1733
  @type target: string
1734
  @param target: the target node name
1735
  @type live: boolean
1736
  @param live: whether the migration should be done live or not (the
1737
      interpretation of this parameter is left to the hypervisor)
1738
  @raise RPCFail: if migration fails for some reason
1739

1740
  """
1741
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1742

    
1743
  try:
1744
    hyper.MigrateInstance(instance, target, live)
1745
  except errors.HypervisorError, err:
1746
    _Fail("Failed to migrate instance: %s", err, exc=True)
1747

    
1748

    
1749
def FinalizeMigrationSource(instance, success, live):
1750
  """Finalize the instance migration on the source node.
1751

1752
  @type instance: L{objects.Instance}
1753
  @param instance: the instance definition of the migrated instance
1754
  @type success: bool
1755
  @param success: whether the migration succeeded or not
1756
  @type live: bool
1757
  @param live: whether the user requested a live migration or not
1758
  @raise RPCFail: If the execution fails for some reason
1759

1760
  """
1761
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1762

    
1763
  try:
1764
    hyper.FinalizeMigrationSource(instance, success, live)
1765
  except Exception, err:  # pylint: disable=W0703
1766
    _Fail("Failed to finalize the migration on the source node: %s", err,
1767
          exc=True)
1768

    
1769

    
1770
def GetMigrationStatus(instance):
1771
  """Get the migration status
1772

1773
  @type instance: L{objects.Instance}
1774
  @param instance: the instance that is being migrated
1775
  @rtype: L{objects.MigrationStatus}
1776
  @return: the status of the current migration (one of
1777
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1778
           progress info that can be retrieved from the hypervisor
1779
  @raise RPCFail: If the migration status cannot be retrieved
1780

1781
  """
1782
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1783
  try:
1784
    return hyper.GetMigrationStatus(instance)
1785
  except Exception, err:  # pylint: disable=W0703
1786
    _Fail("Failed to get migration status: %s", err, exc=True)
1787

    
1788

    
1789
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
1790
  """Creates a block device for an instance.
1791

1792
  @type disk: L{objects.Disk}
1793
  @param disk: the object describing the disk we should create
1794
  @type size: int
1795
  @param size: the size of the physical underlying device, in MiB
1796
  @type owner: str
1797
  @param owner: the name of the instance for which disk is created,
1798
      used for device cache data
1799
  @type on_primary: boolean
1800
  @param on_primary:  indicates if it is the primary node or not
1801
  @type info: string
1802
  @param info: string that will be sent to the physical device
1803
      creation, used for example to set (LVM) tags on LVs
1804
  @type excl_stor: boolean
1805
  @param excl_stor: Whether exclusive_storage is active
1806

1807
  @return: the new unique_id of the device (this can sometime be
1808
      computed only after creation), or None. On secondary nodes,
1809
      it's not required to return anything.
1810

1811
  """
1812
  # TODO: remove the obsolete "size" argument
1813
  # pylint: disable=W0613
1814
  clist = []
1815
  if disk.children:
1816
    for child in disk.children:
1817
      try:
1818
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1819
      except errors.BlockDeviceError, err:
1820
        _Fail("Can't assemble device %s: %s", child, err)
1821
      if on_primary or disk.AssembleOnSecondary():
1822
        # we need the children open in case the device itself has to
1823
        # be assembled
1824
        try:
1825
          # pylint: disable=E1103
1826
          crdev.Open()
1827
        except errors.BlockDeviceError, err:
1828
          _Fail("Can't make child '%s' read-write: %s", child, err)
1829
      clist.append(crdev)
1830

    
1831
  try:
1832
    device = bdev.Create(disk, clist, excl_stor)
1833
  except errors.BlockDeviceError, err:
1834
    _Fail("Can't create block device: %s", err)
1835

    
1836
  if on_primary or disk.AssembleOnSecondary():
1837
    try:
1838
      device.Assemble()
1839
    except errors.BlockDeviceError, err:
1840
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1841
    if on_primary or disk.OpenOnSecondary():
1842
      try:
1843
        device.Open(force=True)
1844
      except errors.BlockDeviceError, err:
1845
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1846
    DevCacheManager.UpdateCache(device.dev_path, owner,
1847
                                on_primary, disk.iv_name)
1848

    
1849
  device.SetInfo(info)
1850

    
1851
  return device.unique_id
1852

    
1853

    
1854
def _WipeDevice(path, offset, size):
1855
  """This function actually wipes the device.
1856

1857
  @param path: The path to the device to wipe
1858
  @param offset: The offset in MiB in the file
1859
  @param size: The size in MiB to write
1860

1861
  """
1862
  # Internal sizes are always in Mebibytes; if the following "dd" command
1863
  # should use a different block size the offset and size given to this
1864
  # function must be adjusted accordingly before being passed to "dd".
1865
  block_size = 1024 * 1024
1866

    
1867
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1868
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
1869
         "count=%d" % size]
1870
  result = utils.RunCmd(cmd)
1871

    
1872
  if result.failed:
1873
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1874
          result.fail_reason, result.output)
1875

    
1876

    
1877
def BlockdevWipe(disk, offset, size):
1878
  """Wipes a block device.
1879

1880
  @type disk: L{objects.Disk}
1881
  @param disk: the disk object we want to wipe
1882
  @type offset: int
1883
  @param offset: The offset in MiB in the file
1884
  @type size: int
1885
  @param size: The size in MiB to write
1886

1887
  """
1888
  try:
1889
    rdev = _RecursiveFindBD(disk)
1890
  except errors.BlockDeviceError:
1891
    rdev = None
1892

    
1893
  if not rdev:
1894
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1895

    
1896
  # Do cross verify some of the parameters
1897
  if offset < 0:
1898
    _Fail("Negative offset")
1899
  if size < 0:
1900
    _Fail("Negative size")
1901
  if offset > rdev.size:
1902
    _Fail("Offset is bigger than device size")
1903
  if (offset + size) > rdev.size:
1904
    _Fail("The provided offset and size to wipe is bigger than device size")
1905

    
1906
  _WipeDevice(rdev.dev_path, offset, size)
1907

    
1908

    
1909
def BlockdevPauseResumeSync(disks, pause):
1910
  """Pause or resume the sync of the block device.
1911

1912
  @type disks: list of L{objects.Disk}
1913
  @param disks: the disks object we want to pause/resume
1914
  @type pause: bool
1915
  @param pause: Wheater to pause or resume
1916

1917
  """
1918
  success = []
1919
  for disk in disks:
1920
    try:
1921
      rdev = _RecursiveFindBD(disk)
1922
    except errors.BlockDeviceError:
1923
      rdev = None
1924

    
1925
    if not rdev:
1926
      success.append((False, ("Cannot change sync for device %s:"
1927
                              " device not found" % disk.iv_name)))
1928
      continue
1929

    
1930
    result = rdev.PauseResumeSync(pause)
1931

    
1932
    if result:
1933
      success.append((result, None))
1934
    else:
1935
      if pause:
1936
        msg = "Pause"
1937
      else:
1938
        msg = "Resume"
1939
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1940

    
1941
  return success
1942

    
1943

    
1944
def BlockdevRemove(disk):
1945
  """Remove a block device.
1946

1947
  @note: This is intended to be called recursively.
1948

1949
  @type disk: L{objects.Disk}
1950
  @param disk: the disk object we should remove
1951
  @rtype: boolean
1952
  @return: the success of the operation
1953

1954
  """
1955
  msgs = []
1956
  try:
1957
    rdev = _RecursiveFindBD(disk)
1958
  except errors.BlockDeviceError, err:
1959
    # probably can't attach
1960
    logging.info("Can't attach to device %s in remove", disk)
1961
    rdev = None
1962
  if rdev is not None:
1963
    r_path = rdev.dev_path
1964
    try:
1965
      rdev.Remove()
1966
    except errors.BlockDeviceError, err:
1967
      msgs.append(str(err))
1968
    if not msgs:
1969
      DevCacheManager.RemoveCache(r_path)
1970

    
1971
  if disk.children:
1972
    for child in disk.children:
1973
      try:
1974
        BlockdevRemove(child)
1975
      except RPCFail, err:
1976
        msgs.append(str(err))
1977

    
1978
  if msgs:
1979
    _Fail("; ".join(msgs))
1980

    
1981

    
1982
def _RecursiveAssembleBD(disk, owner, as_primary):
1983
  """Activate a block device for an instance.
1984

1985
  This is run on the primary and secondary nodes for an instance.
1986

1987
  @note: this function is called recursively.
1988

1989
  @type disk: L{objects.Disk}
1990
  @param disk: the disk we try to assemble
1991
  @type owner: str
1992
  @param owner: the name of the instance which owns the disk
1993
  @type as_primary: boolean
1994
  @param as_primary: if we should make the block device
1995
      read/write
1996

1997
  @return: the assembled device or None (in case no device
1998
      was assembled)
1999
  @raise errors.BlockDeviceError: in case there is an error
2000
      during the activation of the children or the device
2001
      itself
2002

2003
  """
2004
  children = []
2005
  if disk.children:
2006
    mcn = disk.ChildrenNeeded()
2007
    if mcn == -1:
2008
      mcn = 0 # max number of Nones allowed
2009
    else:
2010
      mcn = len(disk.children) - mcn # max number of Nones
2011
    for chld_disk in disk.children:
2012
      try:
2013
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
2014
      except errors.BlockDeviceError, err:
2015
        if children.count(None) >= mcn:
2016
          raise
2017
        cdev = None
2018
        logging.error("Error in child activation (but continuing): %s",
2019
                      str(err))
2020
      children.append(cdev)
2021

    
2022
  if as_primary or disk.AssembleOnSecondary():
2023
    r_dev = bdev.Assemble(disk, children)
2024
    result = r_dev
2025
    if as_primary or disk.OpenOnSecondary():
2026
      r_dev.Open()
2027
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
2028
                                as_primary, disk.iv_name)
2029

    
2030
  else:
2031
    result = True
2032
  return result
2033

    
2034

    
2035
def BlockdevAssemble(disk, owner, as_primary, idx):
2036
  """Activate a block device for an instance.
2037

2038
  This is a wrapper over _RecursiveAssembleBD.
2039

2040
  @rtype: str or boolean
2041
  @return: a C{/dev/...} path for primary nodes, and
2042
      C{True} for secondary nodes
2043

2044
  """
2045
  try:
2046
    result = _RecursiveAssembleBD(disk, owner, as_primary)
2047
    if isinstance(result, BlockDev):
2048
      # pylint: disable=E1103
2049
      result = result.dev_path
2050
      if as_primary:
2051
        _SymlinkBlockDev(owner, result, idx)
2052
  except errors.BlockDeviceError, err:
2053
    _Fail("Error while assembling disk: %s", err, exc=True)
2054
  except OSError, err:
2055
    _Fail("Error while symlinking disk: %s", err, exc=True)
2056

    
2057
  return result
2058

    
2059

    
2060
def BlockdevShutdown(disk):
2061
  """Shut down a block device.
2062

2063
  First, if the device is assembled (Attach() is successful), then
2064
  the device is shutdown. Then the children of the device are
2065
  shutdown.
2066

2067
  This function is called recursively. Note that we don't cache the
2068
  children or such, as oppossed to assemble, shutdown of different
2069
  devices doesn't require that the upper device was active.
2070

2071
  @type disk: L{objects.Disk}
2072
  @param disk: the description of the disk we should
2073
      shutdown
2074
  @rtype: None
2075

2076
  """
2077
  msgs = []
2078
  r_dev = _RecursiveFindBD(disk)
2079
  if r_dev is not None:
2080
    r_path = r_dev.dev_path
2081
    try:
2082
      r_dev.Shutdown()
2083
      DevCacheManager.RemoveCache(r_path)
2084
    except errors.BlockDeviceError, err:
2085
      msgs.append(str(err))
2086

    
2087
  if disk.children:
2088
    for child in disk.children:
2089
      try:
2090
        BlockdevShutdown(child)
2091
      except RPCFail, err:
2092
        msgs.append(str(err))
2093

    
2094
  if msgs:
2095
    _Fail("; ".join(msgs))
2096

    
2097

    
2098
def BlockdevAddchildren(parent_cdev, new_cdevs):
2099
  """Extend a mirrored block device.
2100

2101
  @type parent_cdev: L{objects.Disk}
2102
  @param parent_cdev: the disk to which we should add children
2103
  @type new_cdevs: list of L{objects.Disk}
2104
  @param new_cdevs: the list of children which we should add
2105
  @rtype: None
2106

2107
  """
2108
  parent_bdev = _RecursiveFindBD(parent_cdev)
2109
  if parent_bdev is None:
2110
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
2111
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
2112
  if new_bdevs.count(None) > 0:
2113
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
2114
  parent_bdev.AddChildren(new_bdevs)
2115

    
2116

    
2117
def BlockdevRemovechildren(parent_cdev, new_cdevs):
2118
  """Shrink a mirrored block device.
2119

2120
  @type parent_cdev: L{objects.Disk}
2121
  @param parent_cdev: the disk from which we should remove children
2122
  @type new_cdevs: list of L{objects.Disk}
2123
  @param new_cdevs: the list of children which we should remove
2124
  @rtype: None
2125

2126
  """
2127
  parent_bdev = _RecursiveFindBD(parent_cdev)
2128
  if parent_bdev is None:
2129
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
2130
  devs = []
2131
  for disk in new_cdevs:
2132
    rpath = disk.StaticDevPath()
2133
    if rpath is None:
2134
      bd = _RecursiveFindBD(disk)
2135
      if bd is None:
2136
        _Fail("Can't find device %s while removing children", disk)
2137
      else:
2138
        devs.append(bd.dev_path)
2139
    else:
2140
      if not utils.IsNormAbsPath(rpath):
2141
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
2142
      devs.append(rpath)
2143
  parent_bdev.RemoveChildren(devs)
2144

    
2145

    
2146
def BlockdevGetmirrorstatus(disks):
2147
  """Get the mirroring status of a list of devices.
2148

2149
  @type disks: list of L{objects.Disk}
2150
  @param disks: the list of disks which we should query
2151
  @rtype: disk
2152
  @return: List of L{objects.BlockDevStatus}, one for each disk
2153
  @raise errors.BlockDeviceError: if any of the disks cannot be
2154
      found
2155

2156
  """
2157
  stats = []
2158
  for dsk in disks:
2159
    rbd = _RecursiveFindBD(dsk)
2160
    if rbd is None:
2161
      _Fail("Can't find device %s", dsk)
2162

    
2163
    stats.append(rbd.CombinedSyncStatus())
2164

    
2165
  return stats
2166

    
2167

    
2168
def BlockdevGetmirrorstatusMulti(disks):
2169
  """Get the mirroring status of a list of devices.
2170

2171
  @type disks: list of L{objects.Disk}
2172
  @param disks: the list of disks which we should query
2173
  @rtype: disk
2174
  @return: List of tuples, (bool, status), one for each disk; bool denotes
2175
    success/failure, status is L{objects.BlockDevStatus} on success, string
2176
    otherwise
2177

2178
  """
2179
  result = []
2180
  for disk in disks:
2181
    try:
2182
      rbd = _RecursiveFindBD(disk)
2183
      if rbd is None:
2184
        result.append((False, "Can't find device %s" % disk))
2185
        continue
2186

    
2187
      status = rbd.CombinedSyncStatus()
2188
    except errors.BlockDeviceError, err:
2189
      logging.exception("Error while getting disk status")
2190
      result.append((False, str(err)))
2191
    else:
2192
      result.append((True, status))
2193

    
2194
  assert len(disks) == len(result)
2195

    
2196
  return result
2197

    
2198

    
2199
def _RecursiveFindBD(disk):
2200
  """Check if a device is activated.
2201

2202
  If so, return information about the real device.
2203

2204
  @type disk: L{objects.Disk}
2205
  @param disk: the disk object we need to find
2206

2207
  @return: None if the device can't be found,
2208
      otherwise the device instance
2209

2210
  """
2211
  children = []
2212
  if disk.children:
2213
    for chdisk in disk.children:
2214
      children.append(_RecursiveFindBD(chdisk))
2215

    
2216
  return bdev.FindDevice(disk, children)
2217

    
2218

    
2219
def _OpenRealBD(disk):
2220
  """Opens the underlying block device of a disk.
2221

2222
  @type disk: L{objects.Disk}
2223
  @param disk: the disk object we want to open
2224

2225
  """
2226
  real_disk = _RecursiveFindBD(disk)
2227
  if real_disk is None:
2228
    _Fail("Block device '%s' is not set up", disk)
2229

    
2230
  real_disk.Open()
2231

    
2232
  return real_disk
2233

    
2234

    
2235
def BlockdevFind(disk):
2236
  """Check if a device is activated.
2237

2238
  If it is, return information about the real device.
2239

2240
  @type disk: L{objects.Disk}
2241
  @param disk: the disk to find
2242
  @rtype: None or objects.BlockDevStatus
2243
  @return: None if the disk cannot be found, otherwise a the current
2244
           information
2245

2246
  """
2247
  try:
2248
    rbd = _RecursiveFindBD(disk)
2249
  except errors.BlockDeviceError, err:
2250
    _Fail("Failed to find device: %s", err, exc=True)
2251

    
2252
  if rbd is None:
2253
    return None
2254

    
2255
  return rbd.GetSyncStatus()
2256

    
2257

    
2258
def BlockdevGetdimensions(disks):
2259
  """Computes the size of the given disks.
2260

2261
  If a disk is not found, returns None instead.
2262

2263
  @type disks: list of L{objects.Disk}
2264
  @param disks: the list of disk to compute the size for
2265
  @rtype: list
2266
  @return: list with elements None if the disk cannot be found,
2267
      otherwise the pair (size, spindles), where spindles is None if the
2268
      device doesn't support that
2269

2270
  """
2271
  result = []
2272
  for cf in disks:
2273
    try:
2274
      rbd = _RecursiveFindBD(cf)
2275
    except errors.BlockDeviceError:
2276
      result.append(None)
2277
      continue
2278
    if rbd is None:
2279
      result.append(None)
2280
    else:
2281
      result.append(rbd.GetActualDimensions())
2282
  return result
2283

    
2284

    
2285
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2286
  """Export a block device to a remote node.
2287

2288
  @type disk: L{objects.Disk}
2289
  @param disk: the description of the disk to export
2290
  @type dest_node: str
2291
  @param dest_node: the destination node to export to
2292
  @type dest_path: str
2293
  @param dest_path: the destination path on the target node
2294
  @type cluster_name: str
2295
  @param cluster_name: the cluster name, needed for SSH hostalias
2296
  @rtype: None
2297

2298
  """
2299
  real_disk = _OpenRealBD(disk)
2300

    
2301
  # the block size on the read dd is 1MiB to match our units
2302
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2303
                               "dd if=%s bs=1048576 count=%s",
2304
                               real_disk.dev_path, str(disk.size))
2305

    
2306
  # we set here a smaller block size as, due to ssh buffering, more
2307
  # than 64-128k will mostly ignored; we use nocreat to fail if the
2308
  # device is not already there or we pass a wrong path; we use
2309
  # notrunc to no attempt truncate on an LV device; we use oflag=dsync
2310
  # to not buffer too much memory; this means that at best, we flush
2311
  # every 64k, which will not be very fast
2312
  destcmd = utils.BuildShellCmd("dd of=%s conv=nocreat,notrunc bs=65536"
2313
                                " oflag=dsync", dest_path)
2314

    
2315
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2316
                                                   constants.SSH_LOGIN_USER,
2317
                                                   destcmd)
2318

    
2319
  # all commands have been checked, so we're safe to combine them
2320
  command = "|".join([expcmd, utils.ShellQuoteArgs(remotecmd)])
2321

    
2322
  result = utils.RunCmd(["bash", "-c", command])
2323

    
2324
  if result.failed:
2325
    _Fail("Disk copy command '%s' returned error: %s"
2326
          " output: %s", command, result.fail_reason, result.output)
2327

    
2328

    
2329
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2330
  """Write a file to the filesystem.
2331

2332
  This allows the master to overwrite(!) a file. It will only perform
2333
  the operation if the file belongs to a list of configuration files.
2334

2335
  @type file_name: str
2336
  @param file_name: the target file name
2337
  @type data: str
2338
  @param data: the new contents of the file
2339
  @type mode: int
2340
  @param mode: the mode to give the file (can be None)
2341
  @type uid: string
2342
  @param uid: the owner of the file
2343
  @type gid: string
2344
  @param gid: the group of the file
2345
  @type atime: float
2346
  @param atime: the atime to set on the file (can be None)
2347
  @type mtime: float
2348
  @param mtime: the mtime to set on the file (can be None)
2349
  @rtype: None
2350

2351
  """
2352
  file_name = vcluster.LocalizeVirtualPath(file_name)
2353

    
2354
  if not os.path.isabs(file_name):
2355
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2356

    
2357
  if file_name not in _ALLOWED_UPLOAD_FILES:
2358
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2359
          file_name)
2360

    
2361
  raw_data = _Decompress(data)
2362

    
2363
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2364
    _Fail("Invalid username/groupname type")
2365

    
2366
  getents = runtime.GetEnts()
2367
  uid = getents.LookupUser(uid)
2368
  gid = getents.LookupGroup(gid)
2369

    
2370
  utils.SafeWriteFile(file_name, None,
2371
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2372
                      atime=atime, mtime=mtime)
2373

    
2374

    
2375
def RunOob(oob_program, command, node, timeout):
2376
  """Executes oob_program with given command on given node.
2377

2378
  @param oob_program: The path to the executable oob_program
2379
  @param command: The command to invoke on oob_program
2380
  @param node: The node given as an argument to the program
2381
  @param timeout: Timeout after which we kill the oob program
2382

2383
  @return: stdout
2384
  @raise RPCFail: If execution fails for some reason
2385

2386
  """
2387
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2388

    
2389
  if result.failed:
2390
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2391
          result.fail_reason, result.output)
2392

    
2393
  return result.stdout
2394

    
2395

    
2396
def _OSOndiskAPIVersion(os_dir):
2397
  """Compute and return the API version of a given OS.
2398

2399
  This function will try to read the API version of the OS residing in
2400
  the 'os_dir' directory.
2401

2402
  @type os_dir: str
2403
  @param os_dir: the directory in which we should look for the OS
2404
  @rtype: tuple
2405
  @return: tuple (status, data) with status denoting the validity and
2406
      data holding either the vaid versions or an error message
2407

2408
  """
2409
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2410

    
2411
  try:
2412
    st = os.stat(api_file)
2413
  except EnvironmentError, err:
2414
    return False, ("Required file '%s' not found under path %s: %s" %
2415
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2416

    
2417
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2418
    return False, ("File '%s' in %s is not a regular file" %
2419
                   (constants.OS_API_FILE, os_dir))
2420

    
2421
  try:
2422
    api_versions = utils.ReadFile(api_file).splitlines()
2423
  except EnvironmentError, err:
2424
    return False, ("Error while reading the API version file at %s: %s" %
2425
                   (api_file, utils.ErrnoOrStr(err)))
2426

    
2427
  try:
2428
    api_versions = [int(version.strip()) for version in api_versions]
2429
  except (TypeError, ValueError), err:
2430
    return False, ("API version(s) can't be converted to integer: %s" %
2431
                   str(err))
2432

    
2433
  return True, api_versions
2434

    
2435

    
2436
def DiagnoseOS(top_dirs=None):
2437
  """Compute the validity for all OSes.
2438

2439
  @type top_dirs: list
2440
  @param top_dirs: the list of directories in which to
2441
      search (if not given defaults to
2442
      L{pathutils.OS_SEARCH_PATH})
2443
  @rtype: list of L{objects.OS}
2444
  @return: a list of tuples (name, path, status, diagnose, variants,
2445
      parameters, api_version) for all (potential) OSes under all
2446
      search paths, where:
2447
          - name is the (potential) OS name
2448
          - path is the full path to the OS
2449
          - status True/False is the validity of the OS
2450
          - diagnose is the error message for an invalid OS, otherwise empty
2451
          - variants is a list of supported OS variants, if any
2452
          - parameters is a list of (name, help) parameters, if any
2453
          - api_version is a list of support OS API versions
2454

2455
  """
2456
  if top_dirs is None:
2457
    top_dirs = pathutils.OS_SEARCH_PATH
2458

    
2459
  result = []
2460
  for dir_name in top_dirs:
2461
    if os.path.isdir(dir_name):
2462
      try:
2463
        f_names = utils.ListVisibleFiles(dir_name)
2464
      except EnvironmentError, err:
2465
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2466
        break
2467
      for name in f_names:
2468
        os_path = utils.PathJoin(dir_name, name)
2469
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2470
        if status:
2471
          diagnose = ""
2472
          variants = os_inst.supported_variants
2473
          parameters = os_inst.supported_parameters
2474
          api_versions = os_inst.api_versions
2475
        else:
2476
          diagnose = os_inst
2477
          variants = parameters = api_versions = []
2478
        result.append((name, os_path, status, diagnose, variants,
2479
                       parameters, api_versions))
2480

    
2481
  return result
2482

    
2483

    
2484
def _TryOSFromDisk(name, base_dir=None):
2485
  """Create an OS instance from disk.
2486

2487
  This function will return an OS instance if the given name is a
2488
  valid OS name.
2489

2490
  @type base_dir: string
2491
  @keyword base_dir: Base directory containing OS installations.
2492
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2493
  @rtype: tuple
2494
  @return: success and either the OS instance if we find a valid one,
2495
      or error message
2496

2497
  """
2498
  if base_dir is None:
2499
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2500
  else:
2501
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2502

    
2503
  if os_dir is None:
2504
    return False, "Directory for OS %s not found in search path" % name
2505

    
2506
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2507
  if not status:
2508
    # push the error up
2509
    return status, api_versions
2510

    
2511
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2512
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2513
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2514

    
2515
  # OS Files dictionary, we will populate it with the absolute path
2516
  # names; if the value is True, then it is a required file, otherwise
2517
  # an optional one
2518
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2519

    
2520
  if max(api_versions) >= constants.OS_API_V15:
2521
    os_files[constants.OS_VARIANTS_FILE] = False
2522

    
2523
  if max(api_versions) >= constants.OS_API_V20:
2524
    os_files[constants.OS_PARAMETERS_FILE] = True
2525
  else:
2526
    del os_files[constants.OS_SCRIPT_VERIFY]
2527

    
2528
  for (filename, required) in os_files.items():
2529
    os_files[filename] = utils.PathJoin(os_dir, filename)
2530

    
2531
    try:
2532
      st = os.stat(os_files[filename])
2533
    except EnvironmentError, err:
2534
      if err.errno == errno.ENOENT and not required:
2535
        del os_files[filename]
2536
        continue
2537
      return False, ("File '%s' under path '%s' is missing (%s)" %
2538
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2539

    
2540
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2541
      return False, ("File '%s' under path '%s' is not a regular file" %
2542
                     (filename, os_dir))
2543

    
2544
    if filename in constants.OS_SCRIPTS:
2545
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2546
        return False, ("File '%s' under path '%s' is not executable" %
2547
                       (filename, os_dir))
2548

    
2549
  variants = []
2550
  if constants.OS_VARIANTS_FILE in os_files:
2551
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2552
    try:
2553
      variants = \
2554
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2555
    except EnvironmentError, err:
2556
      # we accept missing files, but not other errors
2557
      if err.errno != errno.ENOENT:
2558
        return False, ("Error while reading the OS variants file at %s: %s" %
2559
                       (variants_file, utils.ErrnoOrStr(err)))
2560

    
2561
  parameters = []
2562
  if constants.OS_PARAMETERS_FILE in os_files:
2563
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2564
    try:
2565
      parameters = utils.ReadFile(parameters_file).splitlines()
2566
    except EnvironmentError, err:
2567
      return False, ("Error while reading the OS parameters file at %s: %s" %
2568
                     (parameters_file, utils.ErrnoOrStr(err)))
2569
    parameters = [v.split(None, 1) for v in parameters]
2570

    
2571
  os_obj = objects.OS(name=name, path=os_dir,
2572
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2573
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2574
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2575
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2576
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2577
                                                 None),
2578
                      supported_variants=variants,
2579
                      supported_parameters=parameters,
2580
                      api_versions=api_versions)
2581
  return True, os_obj
2582

    
2583

    
2584
def OSFromDisk(name, base_dir=None):
2585
  """Create an OS instance from disk.
2586

2587
  This function will return an OS instance if the given name is a
2588
  valid OS name. Otherwise, it will raise an appropriate
2589
  L{RPCFail} exception, detailing why this is not a valid OS.
2590

2591
  This is just a wrapper over L{_TryOSFromDisk}, which doesn't raise
2592
  an exception but returns true/false status data.
2593

2594
  @type base_dir: string
2595
  @keyword base_dir: Base directory containing OS installations.
2596
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2597
  @rtype: L{objects.OS}
2598
  @return: the OS instance if we find a valid one
2599
  @raise RPCFail: if we don't find a valid OS
2600

2601
  """
2602
  name_only = objects.OS.GetName(name)
2603
  status, payload = _TryOSFromDisk(name_only, base_dir)
2604

    
2605
  if not status:
2606
    _Fail(payload)
2607

    
2608
  return payload
2609

    
2610

    
2611
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2612
  """Calculate the basic environment for an os script.
2613

2614
  @type os_name: str
2615
  @param os_name: full operating system name (including variant)
2616
  @type inst_os: L{objects.OS}
2617
  @param inst_os: operating system for which the environment is being built
2618
  @type os_params: dict
2619
  @param os_params: the OS parameters
2620
  @type debug: integer
2621
  @param debug: debug level (0 or 1, for OS Api 10)
2622
  @rtype: dict
2623
  @return: dict of environment variables
2624
  @raise errors.BlockDeviceError: if the block device
2625
      cannot be found
2626

2627
  """
2628
  result = {}
2629
  api_version = \
2630
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2631
  result["OS_API_VERSION"] = "%d" % api_version
2632
  result["OS_NAME"] = inst_os.name
2633
  result["DEBUG_LEVEL"] = "%d" % debug
2634

    
2635
  # OS variants
2636
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2637
    variant = objects.OS.GetVariant(os_name)
2638
    if not variant:
2639
      variant = inst_os.supported_variants[0]
2640
  else:
2641
    variant = ""
2642
  result["OS_VARIANT"] = variant
2643

    
2644
  # OS params
2645
  for pname, pvalue in os_params.items():
2646
    result["OSP_%s" % pname.upper()] = pvalue
2647

    
2648
  # Set a default path otherwise programs called by OS scripts (or
2649
  # even hooks called from OS scripts) might break, and we don't want
2650
  # to have each script require setting a PATH variable
2651
  result["PATH"] = constants.HOOKS_PATH
2652

    
2653
  return result
2654

    
2655

    
2656
def OSEnvironment(instance, inst_os, debug=0):
2657
  """Calculate the environment for an os script.
2658

2659
  @type instance: L{objects.Instance}
2660
  @param instance: target instance for the os script run
2661
  @type inst_os: L{objects.OS}
2662
  @param inst_os: operating system for which the environment is being built
2663
  @type debug: integer
2664
  @param debug: debug level (0 or 1, for OS Api 10)
2665
  @rtype: dict
2666
  @return: dict of environment variables
2667
  @raise errors.BlockDeviceError: if the block device
2668
      cannot be found
2669

2670
  """
2671
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2672

    
2673
  for attr in ["name", "os", "uuid", "ctime", "mtime", "primary_node"]:
2674
    result["INSTANCE_%s" % attr.upper()] = str(getattr(instance, attr))
2675

    
2676
  result["HYPERVISOR"] = instance.hypervisor
2677
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2678
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2679
  result["INSTANCE_SECONDARY_NODES"] = \
2680
      ("%s" % " ".join(instance.secondary_nodes))
2681

    
2682
  # Disks
2683
  for idx, disk in enumerate(instance.disks):
2684
    real_disk = _OpenRealBD(disk)
2685
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2686
    result["DISK_%d_ACCESS" % idx] = disk.mode
2687
    if constants.HV_DISK_TYPE in instance.hvparams:
2688
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2689
        instance.hvparams[constants.HV_DISK_TYPE]
2690
    if disk.dev_type in constants.LDS_BLOCK:
2691
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2692
    elif disk.dev_type == constants.LD_FILE:
2693
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2694
        "file:%s" % disk.physical_id[0]
2695

    
2696
  # NICs
2697
  for idx, nic in enumerate(instance.nics):
2698
    result["NIC_%d_MAC" % idx] = nic.mac
2699
    if nic.ip:
2700
      result["NIC_%d_IP" % idx] = nic.ip
2701
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2702
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2703
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2704
    if nic.nicparams[constants.NIC_LINK]:
2705
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2706
    if nic.netinfo:
2707
      nobj = objects.Network.FromDict(nic.netinfo)
2708
      result.update(nobj.HooksDict("NIC_%d_" % idx))
2709
    if constants.HV_NIC_TYPE in instance.hvparams:
2710
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2711
        instance.hvparams[constants.HV_NIC_TYPE]
2712

    
2713
  # HV/BE params
2714
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2715
    for key, value in source.items():
2716
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2717

    
2718
  return result
2719

    
2720

    
2721
def DiagnoseExtStorage(top_dirs=None):
2722
  """Compute the validity for all ExtStorage Providers.
2723

2724
  @type top_dirs: list
2725
  @param top_dirs: the list of directories in which to
2726
      search (if not given defaults to
2727
      L{pathutils.ES_SEARCH_PATH})
2728
  @rtype: list of L{objects.ExtStorage}
2729
  @return: a list of tuples (name, path, status, diagnose, parameters)
2730
      for all (potential) ExtStorage Providers under all
2731
      search paths, where:
2732
          - name is the (potential) ExtStorage Provider
2733
          - path is the full path to the ExtStorage Provider
2734
          - status True/False is the validity of the ExtStorage Provider
2735
          - diagnose is the error message for an invalid ExtStorage Provider,
2736
            otherwise empty
2737
          - parameters is a list of (name, help) parameters, if any
2738

2739
  """
2740
  if top_dirs is None:
2741
    top_dirs = pathutils.ES_SEARCH_PATH
2742

    
2743
  result = []
2744
  for dir_name in top_dirs:
2745
    if os.path.isdir(dir_name):
2746
      try:
2747
        f_names = utils.ListVisibleFiles(dir_name)
2748
      except EnvironmentError, err:
2749
        logging.exception("Can't list the ExtStorage directory %s: %s",
2750
                          dir_name, err)
2751
        break
2752
      for name in f_names:
2753
        es_path = utils.PathJoin(dir_name, name)
2754
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2755
        if status:
2756
          diagnose = ""
2757
          parameters = es_inst.supported_parameters
2758
        else:
2759
          diagnose = es_inst
2760
          parameters = []
2761
        result.append((name, es_path, status, diagnose, parameters))
2762

    
2763
  return result
2764

    
2765

    
2766
def BlockdevGrow(disk, amount, dryrun, backingstore):
2767
  """Grow a stack of block devices.
2768

2769
  This function is called recursively, with the childrens being the
2770
  first ones to resize.
2771

2772
  @type disk: L{objects.Disk}
2773
  @param disk: the disk to be grown
2774
  @type amount: integer
2775
  @param amount: the amount (in mebibytes) to grow with
2776
  @type dryrun: boolean
2777
  @param dryrun: whether to execute the operation in simulation mode
2778
      only, without actually increasing the size
2779
  @param backingstore: whether to execute the operation on backing storage
2780
      only, or on "logical" storage only; e.g. DRBD is logical storage,
2781
      whereas LVM, file, RBD are backing storage
2782
  @rtype: (status, result)
2783
  @return: a tuple with the status of the operation (True/False), and
2784
      the errors message if status is False
2785

2786
  """
2787
  r_dev = _RecursiveFindBD(disk)
2788
  if r_dev is None:
2789
    _Fail("Cannot find block device %s", disk)
2790

    
2791
  try:
2792
    r_dev.Grow(amount, dryrun, backingstore)
2793
  except errors.BlockDeviceError, err:
2794
    _Fail("Failed to grow block device: %s", err, exc=True)
2795

    
2796

    
2797
def BlockdevSnapshot(disk):
2798
  """Create a snapshot copy of a block device.
2799

2800
  This function is called recursively, and the snapshot is actually created
2801
  just for the leaf lvm backend device.
2802

2803
  @type disk: L{objects.Disk}
2804
  @param disk: the disk to be snapshotted
2805
  @rtype: string
2806
  @return: snapshot disk ID as (vg, lv)
2807

2808
  """
2809
  if disk.dev_type == constants.LD_DRBD8:
2810
    if not disk.children:
2811
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2812
            disk.unique_id)
2813
    return BlockdevSnapshot(disk.children[0])
2814
  elif disk.dev_type == constants.LD_LV:
2815
    r_dev = _RecursiveFindBD(disk)
2816
    if r_dev is not None:
2817
      # FIXME: choose a saner value for the snapshot size
2818
      # let's stay on the safe side and ask for the full size, for now
2819
      return r_dev.Snapshot(disk.size)
2820
    else:
2821
      _Fail("Cannot find block device %s", disk)
2822
  else:
2823
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2824
          disk.unique_id, disk.dev_type)
2825

    
2826

    
2827
def BlockdevSetInfo(disk, info):
2828
  """Sets 'metadata' information on block devices.
2829

2830
  This function sets 'info' metadata on block devices. Initial
2831
  information is set at device creation; this function should be used
2832
  for example after renames.
2833

2834
  @type disk: L{objects.Disk}
2835
  @param disk: the disk to be grown
2836
  @type info: string
2837
  @param info: new 'info' metadata
2838
  @rtype: (status, result)
2839
  @return: a tuple with the status of the operation (True/False), and
2840
      the errors message if status is False
2841

2842
  """
2843
  r_dev = _RecursiveFindBD(disk)
2844
  if r_dev is None:
2845
    _Fail("Cannot find block device %s", disk)
2846

    
2847
  try:
2848
    r_dev.SetInfo(info)
2849
  except errors.BlockDeviceError, err:
2850
    _Fail("Failed to set information on block device: %s", err, exc=True)
2851

    
2852

    
2853
def FinalizeExport(instance, snap_disks):
2854
  """Write out the export configuration information.
2855

2856
  @type instance: L{objects.Instance}
2857
  @param instance: the instance which we export, used for
2858
      saving configuration
2859
  @type snap_disks: list of L{objects.Disk}
2860
  @param snap_disks: list of snapshot block devices, which
2861
      will be used to get the actual name of the dump file
2862

2863
  @rtype: None
2864

2865
  """
2866
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
2867
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
2868

    
2869
  config = objects.SerializableConfigParser()
2870

    
2871
  config.add_section(constants.INISECT_EXP)
2872
  config.set(constants.INISECT_EXP, "version", "0")
2873
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2874
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2875
  config.set(constants.INISECT_EXP, "os", instance.os)
2876
  config.set(constants.INISECT_EXP, "compression", "none")
2877

    
2878
  config.add_section(constants.INISECT_INS)
2879
  config.set(constants.INISECT_INS, "name", instance.name)
2880
  config.set(constants.INISECT_INS, "maxmem", "%d" %
2881
             instance.beparams[constants.BE_MAXMEM])
2882
  config.set(constants.INISECT_INS, "minmem", "%d" %
2883
             instance.beparams[constants.BE_MINMEM])
2884
  # "memory" is deprecated, but useful for exporting to old ganeti versions
2885
  config.set(constants.INISECT_INS, "memory", "%d" %
2886
             instance.beparams[constants.BE_MAXMEM])
2887
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2888
             instance.beparams[constants.BE_VCPUS])
2889
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2890
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2891
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2892

    
2893
  nic_total = 0
2894
  for nic_count, nic in enumerate(instance.nics):
2895
    nic_total += 1
2896
    config.set(constants.INISECT_INS, "nic%d_mac" %
2897
               nic_count, "%s" % nic.mac)
2898
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2899
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
2900
               "%s" % nic.network)
2901
    for param in constants.NICS_PARAMETER_TYPES:
2902
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2903
                 "%s" % nic.nicparams.get(param, None))
2904
  # TODO: redundant: on load can read nics until it doesn't exist
2905
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2906

    
2907
  disk_total = 0
2908
  for disk_count, disk in enumerate(snap_disks):
2909
    if disk:
2910
      disk_total += 1
2911
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2912
                 ("%s" % disk.iv_name))
2913
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2914
                 ("%s" % disk.physical_id[1]))
2915
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2916
                 ("%d" % disk.size))
2917

    
2918
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2919

    
2920
  # New-style hypervisor/backend parameters
2921

    
2922
  config.add_section(constants.INISECT_HYP)
2923
  for name, value in instance.hvparams.items():
2924
    if name not in constants.HVC_GLOBALS:
2925
      config.set(constants.INISECT_HYP, name, str(value))
2926

    
2927
  config.add_section(constants.INISECT_BEP)
2928
  for name, value in instance.beparams.items():
2929
    config.set(constants.INISECT_BEP, name, str(value))
2930

    
2931
  config.add_section(constants.INISECT_OSP)
2932
  for name, value in instance.osparams.items():
2933
    config.set(constants.INISECT_OSP, name, str(value))
2934

    
2935
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2936
                  data=config.Dumps())
2937
  shutil.rmtree(finaldestdir, ignore_errors=True)
2938
  shutil.move(destdir, finaldestdir)
2939

    
2940

    
2941
def ExportInfo(dest):
2942
  """Get export configuration information.
2943

2944
  @type dest: str
2945
  @param dest: directory containing the export
2946

2947
  @rtype: L{objects.SerializableConfigParser}
2948
  @return: a serializable config file containing the
2949
      export info
2950

2951
  """
2952
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2953

    
2954
  config = objects.SerializableConfigParser()
2955
  config.read(cff)
2956

    
2957
  if (not config.has_section(constants.INISECT_EXP) or
2958
      not config.has_section(constants.INISECT_INS)):
2959
    _Fail("Export info file doesn't have the required fields")
2960

    
2961
  return config.Dumps()
2962

    
2963

    
2964
def ListExports():
2965
  """Return a list of exports currently available on this machine.
2966

2967
  @rtype: list
2968
  @return: list of the exports
2969

2970
  """
2971
  if os.path.isdir(pathutils.EXPORT_DIR):
2972
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
2973
  else:
2974
    _Fail("No exports directory")
2975

    
2976

    
2977
def RemoveExport(export):
2978
  """Remove an existing export from the node.
2979

2980
  @type export: str
2981
  @param export: the name of the export to remove
2982
  @rtype: None
2983

2984
  """
2985
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
2986

    
2987
  try:
2988
    shutil.rmtree(target)
2989
  except EnvironmentError, err:
2990
    _Fail("Error while removing the export: %s", err, exc=True)
2991

    
2992

    
2993
def BlockdevRename(devlist):
2994
  """Rename a list of block devices.
2995

2996
  @type devlist: list of tuples
2997
  @param devlist: list of tuples of the form  (disk,
2998
      new_logical_id, new_physical_id); disk is an
2999
      L{objects.Disk} object describing the current disk,
3000
      and new logical_id/physical_id is the name we
3001
      rename it to
3002
  @rtype: boolean
3003
  @return: True if all renames succeeded, False otherwise
3004

3005
  """
3006
  msgs = []
3007
  result = True
3008
  for disk, unique_id in devlist:
3009
    dev = _RecursiveFindBD(disk)
3010
    if dev is None:
3011
      msgs.append("Can't find device %s in rename" % str(disk))
3012
      result = False
3013
      continue
3014
    try:
3015
      old_rpath = dev.dev_path
3016
      dev.Rename(unique_id)
3017
      new_rpath = dev.dev_path
3018
      if old_rpath != new_rpath:
3019
        DevCacheManager.RemoveCache(old_rpath)
3020
        # FIXME: we should add the new cache information here, like:
3021
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
3022
        # but we don't have the owner here - maybe parse from existing
3023
        # cache? for now, we only lose lvm data when we rename, which
3024
        # is less critical than DRBD or MD
3025
    except errors.BlockDeviceError, err:
3026
      msgs.append("Can't rename device '%s' to '%s': %s" %
3027
                  (dev, unique_id, err))
3028
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
3029
      result = False
3030
  if not result:
3031
    _Fail("; ".join(msgs))
3032

    
3033

    
3034
def _TransformFileStorageDir(fs_dir):
3035
  """Checks whether given file_storage_dir is valid.
3036

3037
  Checks wheter the given fs_dir is within the cluster-wide default
3038
  file_storage_dir or the shared_file_storage_dir, which are stored in
3039
  SimpleStore. Only paths under those directories are allowed.
3040

3041
  @type fs_dir: str
3042
  @param fs_dir: the path to check
3043

3044
  @return: the normalized path if valid, None otherwise
3045

3046
  """
3047
  if not (constants.ENABLE_FILE_STORAGE or
3048
          constants.ENABLE_SHARED_FILE_STORAGE):
3049
    _Fail("File storage disabled at configure time")
3050

    
3051
  bdev.CheckFileStoragePath(fs_dir)
3052

    
3053
  return os.path.normpath(fs_dir)
3054

    
3055

    
3056
def CreateFileStorageDir(file_storage_dir):
3057
  """Create file storage directory.
3058

3059
  @type file_storage_dir: str
3060
  @param file_storage_dir: directory to create
3061

3062
  @rtype: tuple
3063
  @return: tuple with first element a boolean indicating wheter dir
3064
      creation was successful or not
3065

3066
  """
3067
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3068
  if os.path.exists(file_storage_dir):
3069
    if not os.path.isdir(file_storage_dir):
3070
      _Fail("Specified storage dir '%s' is not a directory",
3071
            file_storage_dir)
3072
  else:
3073
    try:
3074
      os.makedirs(file_storage_dir, 0750)
3075
    except OSError, err:
3076
      _Fail("Cannot create file storage directory '%s': %s",
3077
            file_storage_dir, err, exc=True)
3078

    
3079

    
3080
def RemoveFileStorageDir(file_storage_dir):
3081
  """Remove file storage directory.
3082

3083
  Remove it only if it's empty. If not log an error and return.
3084

3085
  @type file_storage_dir: str
3086
  @param file_storage_dir: the directory we should cleanup
3087
  @rtype: tuple (success,)
3088
  @return: tuple of one element, C{success}, denoting
3089
      whether the operation was successful
3090

3091
  """
3092
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3093
  if os.path.exists(file_storage_dir):
3094
    if not os.path.isdir(file_storage_dir):
3095
      _Fail("Specified Storage directory '%s' is not a directory",
3096
            file_storage_dir)
3097
    # deletes dir only if empty, otherwise we want to fail the rpc call
3098
    try:
3099
      os.rmdir(file_storage_dir)
3100
    except OSError, err:
3101
      _Fail("Cannot remove file storage directory '%s': %s",
3102
            file_storage_dir, err)
3103

    
3104

    
3105
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
3106
  """Rename the file storage directory.
3107

3108
  @type old_file_storage_dir: str
3109
  @param old_file_storage_dir: the current path
3110
  @type new_file_storage_dir: str
3111
  @param new_file_storage_dir: the name we should rename to
3112
  @rtype: tuple (success,)
3113
  @return: tuple of one element, C{success}, denoting
3114
      whether the operation was successful
3115

3116
  """
3117
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
3118
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
3119
  if not os.path.exists(new_file_storage_dir):
3120
    if os.path.isdir(old_file_storage_dir):
3121
      try:
3122
        os.rename(old_file_storage_dir, new_file_storage_dir)
3123
      except OSError, err:
3124
        _Fail("Cannot rename '%s' to '%s': %s",
3125
              old_file_storage_dir, new_file_storage_dir, err)
3126
    else:
3127
      _Fail("Specified storage dir '%s' is not a directory",
3128
            old_file_storage_dir)
3129
  else:
3130
    if os.path.exists(old_file_storage_dir):
3131
      _Fail("Cannot rename '%s' to '%s': both locations exist",
3132
            old_file_storage_dir, new_file_storage_dir)
3133

    
3134

    
3135
def _EnsureJobQueueFile(file_name):
3136
  """Checks whether the given filename is in the queue directory.
3137

3138
  @type file_name: str
3139
  @param file_name: the file name we should check
3140
  @rtype: None
3141
  @raises RPCFail: if the file is not valid
3142

3143
  """
3144
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
3145
    _Fail("Passed job queue file '%s' does not belong to"
3146
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
3147

    
3148

    
3149
def JobQueueUpdate(file_name, content):
3150
  """Updates a file in the queue directory.
3151

3152
  This is just a wrapper over L{utils.io.WriteFile}, with proper
3153
  checking.
3154

3155
  @type file_name: str
3156
  @param file_name: the job file name
3157
  @type content: str
3158
  @param content: the new job contents
3159
  @rtype: boolean
3160
  @return: the success of the operation
3161

3162
  """
3163
  file_name = vcluster.LocalizeVirtualPath(file_name)
3164

    
3165
  _EnsureJobQueueFile(file_name)
3166
  getents = runtime.GetEnts()
3167

    
3168
  # Write and replace the file atomically
3169
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3170
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3171

    
3172

    
3173
def JobQueueRename(old, new):
3174
  """Renames a job queue file.
3175

3176
  This is just a wrapper over os.rename with proper checking.
3177

3178
  @type old: str
3179
  @param old: the old (actual) file name
3180
  @type new: str
3181
  @param new: the desired file name
3182
  @rtype: tuple
3183
  @return: the success of the operation and payload
3184

3185
  """
3186
  old = vcluster.LocalizeVirtualPath(old)
3187
  new = vcluster.LocalizeVirtualPath(new)
3188

    
3189
  _EnsureJobQueueFile(old)
3190
  _EnsureJobQueueFile(new)
3191

    
3192
  getents = runtime.GetEnts()
3193

    
3194
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3195
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3196

    
3197

    
3198
def BlockdevClose(instance_name, disks):
3199
  """Closes the given block devices.
3200

3201
  This means they will be switched to secondary mode (in case of
3202
  DRBD).
3203

3204
  @param instance_name: if the argument is not empty, the symlinks
3205
      of this instance will be removed
3206
  @type disks: list of L{objects.Disk}
3207
  @param disks: the list of disks to be closed
3208
  @rtype: tuple (success, message)
3209
  @return: a tuple of success and message, where success
3210
      indicates the succes of the operation, and message
3211
      which will contain the error details in case we
3212
      failed
3213

3214
  """
3215
  bdevs = []
3216
  for cf in disks:
3217
    rd = _RecursiveFindBD(cf)
3218
    if rd is None:
3219
      _Fail("Can't find device %s", cf)
3220
    bdevs.append(rd)
3221

    
3222
  msg = []
3223
  for rd in bdevs:
3224
    try:
3225
      rd.Close()
3226
    except errors.BlockDeviceError, err:
3227
      msg.append(str(err))
3228
  if msg:
3229
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3230
  else:
3231
    if instance_name:
3232
      _RemoveBlockDevLinks(instance_name, disks)
3233

    
3234

    
3235
def ValidateHVParams(hvname, hvparams):
3236
  """Validates the given hypervisor parameters.
3237

3238
  @type hvname: string
3239
  @param hvname: the hypervisor name
3240
  @type hvparams: dict
3241
  @param hvparams: the hypervisor parameters to be validated
3242
  @rtype: None
3243

3244
  """
3245
  try:
3246
    hv_type = hypervisor.GetHypervisor(hvname)
3247
    hv_type.ValidateParameters(hvparams)
3248
  except errors.HypervisorError, err:
3249
    _Fail(str(err), log=False)
3250

    
3251

    
3252
def _CheckOSPList(os_obj, parameters):
3253
  """Check whether a list of parameters is supported by the OS.
3254

3255
  @type os_obj: L{objects.OS}
3256
  @param os_obj: OS object to check
3257
  @type parameters: list
3258
  @param parameters: the list of parameters to check
3259

3260
  """
3261
  supported = [v[0] for v in os_obj.supported_parameters]
3262
  delta = frozenset(parameters).difference(supported)
3263
  if delta:
3264
    _Fail("The following parameters are not supported"
3265
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3266

    
3267

    
3268
def ValidateOS(required, osname, checks, osparams):
3269
  """Validate the given OS' parameters.
3270

3271
  @type required: boolean
3272
  @param required: whether absence of the OS should translate into
3273
      failure or not
3274
  @type osname: string
3275
  @param osname: the OS to be validated
3276
  @type checks: list
3277
  @param checks: list of the checks to run (currently only 'parameters')
3278
  @type osparams: dict
3279
  @param osparams: dictionary with OS parameters
3280
  @rtype: boolean
3281
  @return: True if the validation passed, or False if the OS was not
3282
      found and L{required} was false
3283

3284
  """
3285
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3286
    _Fail("Unknown checks required for OS %s: %s", osname,
3287
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3288

    
3289
  name_only = objects.OS.GetName(osname)
3290
  status, tbv = _TryOSFromDisk(name_only, None)
3291

    
3292
  if not status:
3293
    if required:
3294
      _Fail(tbv)
3295
    else:
3296
      return False
3297

    
3298
  if max(tbv.api_versions) < constants.OS_API_V20:
3299
    return True
3300

    
3301
  if constants.OS_VALIDATE_PARAMETERS in checks:
3302
    _CheckOSPList(tbv, osparams.keys())
3303

    
3304
  validate_env = OSCoreEnv(osname, tbv, osparams)
3305
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3306
                        cwd=tbv.path, reset_env=True)
3307
  if result.failed:
3308
    logging.error("os validate command '%s' returned error: %s output: %s",
3309
                  result.cmd, result.fail_reason, result.output)
3310
    _Fail("OS validation script failed (%s), output: %s",
3311
          result.fail_reason, result.output, log=False)
3312

    
3313
  return True
3314

    
3315

    
3316
def DemoteFromMC():
3317
  """Demotes the current node from master candidate role.
3318

3319
  """
3320
  # try to ensure we're not the master by mistake
3321
  master, myself = ssconf.GetMasterAndMyself()
3322
  if master == myself:
3323
    _Fail("ssconf status shows I'm the master node, will not demote")
3324

    
3325
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3326
  if not result.failed:
3327
    _Fail("The master daemon is running, will not demote")
3328

    
3329
  try:
3330
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3331
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3332
  except EnvironmentError, err:
3333
    if err.errno != errno.ENOENT:
3334
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3335

    
3336
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3337

    
3338

    
3339
def _GetX509Filenames(cryptodir, name):
3340
  """Returns the full paths for the private key and certificate.
3341

3342
  """
3343
  return (utils.PathJoin(cryptodir, name),
3344
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3345
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3346

    
3347

    
3348
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3349
  """Creates a new X509 certificate for SSL/TLS.
3350

3351
  @type validity: int
3352
  @param validity: Validity in seconds
3353
  @rtype: tuple; (string, string)
3354
  @return: Certificate name and public part
3355

3356
  """
3357
  (key_pem, cert_pem) = \
3358
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3359
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3360

    
3361
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3362
                              prefix="x509-%s-" % utils.TimestampForFilename())
3363
  try:
3364
    name = os.path.basename(cert_dir)
3365
    assert len(name) > 5
3366

    
3367
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3368

    
3369
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3370
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3371

    
3372
    # Never return private key as it shouldn't leave the node
3373
    return (name, cert_pem)
3374
  except Exception:
3375
    shutil.rmtree(cert_dir, ignore_errors=True)
3376
    raise
3377

    
3378

    
3379
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3380
  """Removes a X509 certificate.
3381

3382
  @type name: string
3383
  @param name: Certificate name
3384

3385
  """
3386
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3387

    
3388
  utils.RemoveFile(key_file)
3389
  utils.RemoveFile(cert_file)
3390

    
3391
  try:
3392
    os.rmdir(cert_dir)
3393
  except EnvironmentError, err:
3394
    _Fail("Cannot remove certificate directory '%s': %s",
3395
          cert_dir, err)
3396

    
3397

    
3398
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3399
  """Returns the command for the requested input/output.
3400

3401
  @type instance: L{objects.Instance}
3402
  @param instance: The instance object
3403
  @param mode: Import/export mode
3404
  @param ieio: Input/output type
3405
  @param ieargs: Input/output arguments
3406

3407
  """
3408
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3409

    
3410
  env = None
3411
  prefix = None
3412
  suffix = None
3413
  exp_size = None
3414

    
3415
  if ieio == constants.IEIO_FILE:
3416
    (filename, ) = ieargs
3417

    
3418
    if not utils.IsNormAbsPath(filename):
3419
      _Fail("Path '%s' is not normalized or absolute", filename)
3420

    
3421
    real_filename = os.path.realpath(filename)
3422
    directory = os.path.dirname(real_filename)
3423

    
3424
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3425
      _Fail("File '%s' is not under exports directory '%s': %s",
3426
            filename, pathutils.EXPORT_DIR, real_filename)
3427

    
3428
    # Create directory
3429
    utils.Makedirs(directory, mode=0750)
3430

    
3431
    quoted_filename = utils.ShellQuote(filename)
3432

    
3433
    if mode == constants.IEM_IMPORT:
3434
      suffix = "> %s" % quoted_filename
3435
    elif mode == constants.IEM_EXPORT:
3436
      suffix = "< %s" % quoted_filename
3437

    
3438
      # Retrieve file size
3439
      try:
3440
        st = os.stat(filename)
3441
      except EnvironmentError, err:
3442
        logging.error("Can't stat(2) %s: %s", filename, err)
3443
      else:
3444
        exp_size = utils.BytesToMebibyte(st.st_size)
3445

    
3446
  elif ieio == constants.IEIO_RAW_DISK:
3447
    (disk, ) = ieargs
3448

    
3449
    real_disk = _OpenRealBD(disk)
3450

    
3451
    if mode == constants.IEM_IMPORT:
3452
      # we set here a smaller block size as, due to transport buffering, more
3453
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3454
      # is not already there or we pass a wrong path; we use notrunc to no
3455
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3456
      # much memory; this means that at best, we flush every 64k, which will
3457
      # not be very fast
3458
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3459
                                    " bs=%s oflag=dsync"),
3460
                                    real_disk.dev_path,
3461
                                    str(64 * 1024))
3462

    
3463
    elif mode == constants.IEM_EXPORT:
3464
      # the block size on the read dd is 1MiB to match our units
3465
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3466
                                   real_disk.dev_path,
3467
                                   str(1024 * 1024), # 1 MB
3468
                                   str(disk.size))
3469
      exp_size = disk.size
3470

    
3471
  elif ieio == constants.IEIO_SCRIPT:
3472
    (disk, disk_index, ) = ieargs
3473

    
3474
    assert isinstance(disk_index, (int, long))
3475

    
3476
    real_disk = _OpenRealBD(disk)
3477

    
3478
    inst_os = OSFromDisk(instance.os)
3479
    env = OSEnvironment(instance, inst_os)
3480

    
3481
    if mode == constants.IEM_IMPORT:
3482
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3483
      env["IMPORT_INDEX"] = str(disk_index)
3484
      script = inst_os.import_script
3485

    
3486
    elif mode == constants.IEM_EXPORT:
3487
      env["EXPORT_DEVICE"] = real_disk.dev_path
3488
      env["EXPORT_INDEX"] = str(disk_index)
3489
      script = inst_os.export_script
3490

    
3491
    # TODO: Pass special environment only to script
3492
    script_cmd = utils.BuildShellCmd("( cd %s && %s; )", inst_os.path, script)
3493

    
3494
    if mode == constants.IEM_IMPORT:
3495
      suffix = "| %s" % script_cmd
3496

    
3497
    elif mode == constants.IEM_EXPORT:
3498
      prefix = "%s |" % script_cmd
3499

    
3500
    # Let script predict size
3501
    exp_size = constants.IE_CUSTOM_SIZE
3502

    
3503
  else:
3504
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3505

    
3506
  return (env, prefix, suffix, exp_size)
3507

    
3508

    
3509
def _CreateImportExportStatusDir(prefix):
3510
  """Creates status directory for import/export.
3511

3512
  """
3513
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3514
                          prefix=("%s-%s-" %
3515
                                  (prefix, utils.TimestampForFilename())))
3516

    
3517

    
3518
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3519
                            ieio, ieioargs):
3520
  """Starts an import or export daemon.
3521

3522
  @param mode: Import/output mode
3523
  @type opts: L{objects.ImportExportOptions}
3524
  @param opts: Daemon options
3525
  @type host: string
3526
  @param host: Remote host for export (None for import)
3527
  @type port: int
3528
  @param port: Remote port for export (None for import)
3529
  @type instance: L{objects.Instance}
3530
  @param instance: Instance object
3531
  @type component: string
3532
  @param component: which part of the instance is transferred now,
3533
      e.g. 'disk/0'
3534
  @param ieio: Input/output type
3535
  @param ieioargs: Input/output arguments
3536

3537
  """
3538
  if mode == constants.IEM_IMPORT:
3539
    prefix = "import"
3540

    
3541
    if not (host is None and port is None):
3542
      _Fail("Can not specify host or port on import")
3543

    
3544
  elif mode == constants.IEM_EXPORT:
3545
    prefix = "export"
3546

    
3547
    if host is None or port is None:
3548
      _Fail("Host and port must be specified for an export")
3549

    
3550
  else:
3551
    _Fail("Invalid mode %r", mode)
3552

    
3553
  if (opts.key_name is None) ^ (opts.ca_pem is None):
3554
    _Fail("Cluster certificate can only be used for both key and CA")
3555

    
3556
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3557
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3558

    
3559
  if opts.key_name is None:
3560
    # Use server.pem
3561
    key_path = pathutils.NODED_CERT_FILE
3562
    cert_path = pathutils.NODED_CERT_FILE
3563
    assert opts.ca_pem is None
3564
  else:
3565
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3566
                                                 opts.key_name)
3567
    assert opts.ca_pem is not None
3568

    
3569
  for i in [key_path, cert_path]:
3570
    if not os.path.exists(i):
3571
      _Fail("File '%s' does not exist" % i)
3572

    
3573
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3574
  try:
3575
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3576
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3577
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3578

    
3579
    if opts.ca_pem is None:
3580
      # Use server.pem
3581
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3582
    else:
3583
      ca = opts.ca_pem
3584

    
3585
    # Write CA file
3586
    utils.WriteFile(ca_file, data=ca, mode=0400)
3587

    
3588
    cmd = [
3589
      pathutils.IMPORT_EXPORT_DAEMON,
3590
      status_file, mode,
3591
      "--key=%s" % key_path,
3592
      "--cert=%s" % cert_path,
3593
      "--ca=%s" % ca_file,
3594
      ]
3595

    
3596
    if host:
3597
      cmd.append("--host=%s" % host)
3598

    
3599
    if port:
3600
      cmd.append("--port=%s" % port)
3601

    
3602
    if opts.ipv6:
3603
      cmd.append("--ipv6")
3604
    else:
3605
      cmd.append("--ipv4")
3606

    
3607
    if opts.compress:
3608
      cmd.append("--compress=%s" % opts.compress)
3609

    
3610
    if opts.magic:
3611
      cmd.append("--magic=%s" % opts.magic)
3612

    
3613
    if exp_size is not None:
3614
      cmd.append("--expected-size=%s" % exp_size)
3615

    
3616
    if cmd_prefix:
3617
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3618

    
3619
    if cmd_suffix:
3620
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3621

    
3622
    if mode == constants.IEM_EXPORT:
3623
      # Retry connection a few times when connecting to remote peer
3624
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3625
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3626
    elif opts.connect_timeout is not None:
3627
      assert mode == constants.IEM_IMPORT
3628
      # Overall timeout for establishing connection while listening
3629
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3630

    
3631
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3632

    
3633
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3634
    # support for receiving a file descriptor for output
3635
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3636
                      output=logfile)
3637

    
3638
    # The import/export name is simply the status directory name
3639
    return os.path.basename(status_dir)
3640

    
3641
  except Exception:
3642
    shutil.rmtree(status_dir, ignore_errors=True)
3643
    raise
3644

    
3645

    
3646
def GetImportExportStatus(names):
3647
  """Returns import/export daemon status.
3648

3649
  @type names: sequence
3650
  @param names: List of names
3651
  @rtype: List of dicts
3652
  @return: Returns a list of the state of each named import/export or None if a
3653
           status couldn't be read
3654

3655
  """
3656
  result = []
3657

    
3658
  for name in names:
3659
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3660
                                 _IES_STATUS_FILE)
3661

    
3662
    try:
3663
      data = utils.ReadFile(status_file)
3664
    except EnvironmentError, err:
3665
      if err.errno != errno.ENOENT:
3666
        raise
3667
      data = None
3668

    
3669
    if not data:
3670
      result.append(None)
3671
      continue
3672

    
3673
    result.append(serializer.LoadJson(data))
3674

    
3675
  return result
3676

    
3677

    
3678
def AbortImportExport(name):
3679
  """Sends SIGTERM to a running import/export daemon.
3680

3681
  """
3682
  logging.info("Abort import/export %s", name)
3683

    
3684
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3685
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3686

    
3687
  if pid:
3688
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3689
                 name, pid)
3690
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3691

    
3692

    
3693
def CleanupImportExport(name):
3694
  """Cleanup after an import or export.
3695

3696
  If the import/export daemon is still running it's killed. Afterwards the
3697
  whole status directory is removed.
3698

3699
  """
3700
  logging.info("Finalizing import/export %s", name)
3701

    
3702
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3703

    
3704
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3705

    
3706
  if pid:
3707
    logging.info("Import/export %s is still running with PID %s",
3708
                 name, pid)
3709
    utils.KillProcess(pid, waitpid=False)
3710

    
3711
  shutil.rmtree(status_dir, ignore_errors=True)
3712

    
3713

    
3714
def _FindDisks(nodes_ip, disks):
3715
  """Sets the physical ID on disks and returns the block devices.
3716

3717
  """
3718
  # set the correct physical ID
3719
  my_name = netutils.Hostname.GetSysName()
3720
  for cf in disks:
3721
    cf.SetPhysicalID(my_name, nodes_ip)
3722

    
3723
  bdevs = []
3724

    
3725
  for cf in disks:
3726
    rd = _RecursiveFindBD(cf)
3727
    if rd is None:
3728
      _Fail("Can't find device %s", cf)
3729
    bdevs.append(rd)
3730
  return bdevs
3731

    
3732

    
3733
def DrbdDisconnectNet(nodes_ip, disks):
3734
  """Disconnects the network on a list of drbd devices.
3735

3736
  """
3737
  bdevs = _FindDisks(nodes_ip, disks)
3738

    
3739
  # disconnect disks
3740
  for rd in bdevs:
3741
    try:
3742
      rd.DisconnectNet()
3743
    except errors.BlockDeviceError, err:
3744
      _Fail("Can't change network configuration to standalone mode: %s",
3745
            err, exc=True)
3746

    
3747

    
3748
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3749
  """Attaches the network on a list of drbd devices.
3750

3751
  """
3752
  bdevs = _FindDisks(nodes_ip, disks)
3753

    
3754
  if multimaster:
3755
    for idx, rd in enumerate(bdevs):
3756
      try:
3757
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3758
      except EnvironmentError, err:
3759
        _Fail("Can't create symlink: %s", err)
3760
  # reconnect disks, switch to new master configuration and if
3761
  # needed primary mode
3762
  for rd in bdevs:
3763
    try:
3764
      rd.AttachNet(multimaster)
3765
    except errors.BlockDeviceError, err:
3766
      _Fail("Can't change network configuration: %s", err)
3767

    
3768
  # wait until the disks are connected; we need to retry the re-attach
3769
  # if the device becomes standalone, as this might happen if the one
3770
  # node disconnects and reconnects in a different mode before the
3771
  # other node reconnects; in this case, one or both of the nodes will
3772
  # decide it has wrong configuration and switch to standalone
3773

    
3774
  def _Attach():
3775
    all_connected = True
3776

    
3777
    for rd in bdevs:
3778
      stats = rd.GetProcStatus()
3779

    
3780
      all_connected = (all_connected and
3781
                       (stats.is_connected or stats.is_in_resync))
3782

    
3783
      if stats.is_standalone:
3784
        # peer had different config info and this node became
3785
        # standalone, even though this should not happen with the
3786
        # new staged way of changing disk configs
3787
        try:
3788
          rd.AttachNet(multimaster)
3789
        except errors.BlockDeviceError, err:
3790
          _Fail("Can't change network configuration: %s", err)
3791

    
3792
    if not all_connected:
3793
      raise utils.RetryAgain()
3794

    
3795
  try:
3796
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3797
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3798
  except utils.RetryTimeout:
3799
    _Fail("Timeout in disk reconnecting")
3800

    
3801
  if multimaster:
3802
    # change to primary mode
3803
    for rd in bdevs:
3804
      try:
3805
        rd.Open()
3806
      except errors.BlockDeviceError, err:
3807
        _Fail("Can't change to primary mode: %s", err)
3808

    
3809

    
3810
def DrbdWaitSync(nodes_ip, disks):
3811
  """Wait until DRBDs have synchronized.
3812

3813
  """
3814
  def _helper(rd):
3815
    stats = rd.GetProcStatus()
3816
    if not (stats.is_connected or stats.is_in_resync):
3817
      raise utils.RetryAgain()
3818
    return stats
3819

    
3820
  bdevs = _FindDisks(nodes_ip, disks)
3821

    
3822
  min_resync = 100
3823
  alldone = True
3824
  for rd in bdevs:
3825
    try:
3826
      # poll each second for 15 seconds
3827
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3828
    except utils.RetryTimeout:
3829
      stats = rd.GetProcStatus()
3830
      # last check
3831
      if not (stats.is_connected or stats.is_in_resync):
3832
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3833
    alldone = alldone and (not stats.is_in_resync)
3834
    if stats.sync_percent is not None:
3835
      min_resync = min(min_resync, stats.sync_percent)
3836

    
3837
  return (alldone, min_resync)
3838

    
3839

    
3840
def GetDrbdUsermodeHelper():
3841
  """Returns DRBD usermode helper currently configured.
3842

3843
  """
3844
  try:
3845
    return drbd.DRBD8.GetUsermodeHelper()
3846
  except errors.BlockDeviceError, err:
3847
    _Fail(str(err))
3848

    
3849

    
3850
def PowercycleNode(hypervisor_type):
3851
  """Hard-powercycle the node.
3852

3853
  Because we need to return first, and schedule the powercycle in the
3854
  background, we won't be able to report failures nicely.
3855

3856
  """
3857
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3858
  try:
3859
    pid = os.fork()
3860
  except OSError:
3861
    # if we can't fork, we'll pretend that we're in the child process
3862
    pid = 0
3863
  if pid > 0:
3864
    return "Reboot scheduled in 5 seconds"
3865
  # ensure the child is running on ram
3866
  try:
3867
    utils.Mlockall()
3868
  except Exception: # pylint: disable=W0703
3869
    pass
3870
  time.sleep(5)
3871
  hyper.PowercycleNode()
3872

    
3873

    
3874
def _VerifyRestrictedCmdName(cmd):
3875
  """Verifies a restricted command name.
3876

3877
  @type cmd: string
3878
  @param cmd: Command name
3879
  @rtype: tuple; (boolean, string or None)
3880
  @return: The tuple's first element is the status; if C{False}, the second
3881
    element is an error message string, otherwise it's C{None}
3882

3883
  """
3884
  if not cmd.strip():
3885
    return (False, "Missing command name")
3886

    
3887
  if os.path.basename(cmd) != cmd:
3888
    return (False, "Invalid command name")
3889

    
3890
  if not constants.EXT_PLUGIN_MASK.match(cmd):
3891
    return (False, "Command name contains forbidden characters")
3892

    
3893
  return (True, None)
3894

    
3895

    
3896
def _CommonRestrictedCmdCheck(path, owner):
3897
  """Common checks for restricted command file system directories and files.
3898

3899
  @type path: string
3900
  @param path: Path to check
3901
  @param owner: C{None} or tuple containing UID and GID
3902
  @rtype: tuple; (boolean, string or C{os.stat} result)
3903
  @return: The tuple's first element is the status; if C{False}, the second
3904
    element is an error message string, otherwise it's the result of C{os.stat}
3905

3906
  """
3907
  if owner is None:
3908
    # Default to root as owner
3909
    owner = (0, 0)
3910

    
3911
  try:
3912
    st = os.stat(path)
3913
  except EnvironmentError, err:
3914
    return (False, "Can't stat(2) '%s': %s" % (path, err))
3915

    
3916
  if stat.S_IMODE(st.st_mode) & (~_RCMD_MAX_MODE):
3917
    return (False, "Permissions on '%s' are too permissive" % path)
3918

    
3919
  if (st.st_uid, st.st_gid) != owner:
3920
    (owner_uid, owner_gid) = owner
3921
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
3922

    
3923
  return (True, st)
3924

    
3925

    
3926
def _VerifyRestrictedCmdDirectory(path, _owner=None):
3927
  """Verifies restricted command directory.
3928

3929
  @type path: string
3930
  @param path: Path to check
3931
  @rtype: tuple; (boolean, string or None)
3932
  @return: The tuple's first element is the status; if C{False}, the second
3933
    element is an error message string, otherwise it's C{None}
3934

3935
  """
3936
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
3937

    
3938
  if not status:
3939
    return (False, value)
3940

    
3941
  if not stat.S_ISDIR(value.st_mode):
3942
    return (False, "Path '%s' is not a directory" % path)
3943

    
3944
  return (True, None)
3945

    
3946

    
3947
def _VerifyRestrictedCmd(path, cmd, _owner=None):
3948
  """Verifies a whole restricted command and returns its executable filename.
3949

3950
  @type path: string
3951
  @param path: Directory containing restricted commands
3952
  @type cmd: string
3953
  @param cmd: Command name
3954
  @rtype: tuple; (boolean, string)
3955
  @return: The tuple's first element is the status; if C{False}, the second
3956
    element is an error message string, otherwise the second element is the
3957
    absolute path to the executable
3958

3959
  """
3960
  executable = utils.PathJoin(path, cmd)
3961

    
3962
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
3963

    
3964
  if not status:
3965
    return (False, msg)
3966

    
3967
  if not utils.IsExecutable(executable):
3968
    return (False, "access(2) thinks '%s' can't be executed" % executable)
3969

    
3970
  return (True, executable)
3971

    
3972

    
3973
def _PrepareRestrictedCmd(path, cmd,
3974
                          _verify_dir=_VerifyRestrictedCmdDirectory,
3975
                          _verify_name=_VerifyRestrictedCmdName,
3976
                          _verify_cmd=_VerifyRestrictedCmd):
3977
  """Performs a number of tests on a restricted command.
3978

3979
  @type path: string
3980
  @param path: Directory containing restricted commands
3981
  @type cmd: string
3982
  @param cmd: Command name
3983
  @return: Same as L{_VerifyRestrictedCmd}
3984

3985
  """
3986
  # Verify the directory first
3987
  (status, msg) = _verify_dir(path)
3988
  if status:
3989
    # Check command if everything was alright
3990
    (status, msg) = _verify_name(cmd)
3991

    
3992
  if not status:
3993
    return (False, msg)
3994

    
3995
  # Check actual executable
3996
  return _verify_cmd(path, cmd)
3997

    
3998

    
3999
def RunRestrictedCmd(cmd,
4000
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
4001
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
4002
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
4003
                     _sleep_fn=time.sleep,
4004
                     _prepare_fn=_PrepareRestrictedCmd,
4005
                     _runcmd_fn=utils.RunCmd,
4006
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
4007
  """Executes a restricted command after performing strict tests.
4008

4009
  @type cmd: string
4010
  @param cmd: Command name
4011
  @rtype: string
4012
  @return: Command output
4013
  @raise RPCFail: In case of an error
4014

4015
  """
4016
  logging.info("Preparing to run restricted command '%s'", cmd)
4017

    
4018
  if not _enabled:
4019
    _Fail("Restricted commands disabled at configure time")
4020

    
4021
  lock = None
4022
  try:
4023
    cmdresult = None
4024
    try:
4025
      lock = utils.FileLock.Open(_lock_file)
4026
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
4027

    
4028
      (status, value) = _prepare_fn(_path, cmd)
4029

    
4030
      if status:
4031
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
4032
                               postfork_fn=lambda _: lock.Unlock())
4033
      else:
4034
        logging.error(value)
4035
    except Exception: # pylint: disable=W0703
4036
      # Keep original error in log
4037
      logging.exception("Caught exception")
4038

    
4039
    if cmdresult is None:
4040
      logging.info("Sleeping for %0.1f seconds before returning",
4041
                   _RCMD_INVALID_DELAY)
4042
      _sleep_fn(_RCMD_INVALID_DELAY)
4043

    
4044
      # Do not include original error message in returned error
4045
      _Fail("Executing command '%s' failed" % cmd)
4046
    elif cmdresult.failed or cmdresult.fail_reason:
4047
      _Fail("Restricted command '%s' failed: %s; output: %s",
4048
            cmd, cmdresult.fail_reason, cmdresult.output)
4049
    else:
4050
      return cmdresult.output
4051
  finally:
4052
    if lock is not None:
4053
      # Release lock at last
4054
      lock.Close()
4055
      lock = None
4056

    
4057

    
4058
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
4059
  """Creates or removes the watcher pause file.
4060

4061
  @type until: None or number
4062
  @param until: Unix timestamp saying until when the watcher shouldn't run
4063

4064
  """
4065
  if until is None:
4066
    logging.info("Received request to no longer pause watcher")
4067
    utils.RemoveFile(_filename)
4068
  else:
4069
    logging.info("Received request to pause watcher until %s", until)
4070

    
4071
    if not ht.TNumber(until):
4072
      _Fail("Duration must be numeric")
4073

    
4074
    utils.WriteFile(_filename, data="%d\n" % (until, ), mode=0644)
4075

    
4076

    
4077
class HooksRunner(object):
4078
  """Hook runner.
4079

4080
  This class is instantiated on the node side (ganeti-noded) and not
4081
  on the master side.
4082

4083
  """
4084
  def __init__(self, hooks_base_dir=None):
4085
    """Constructor for hooks runner.
4086

4087
    @type hooks_base_dir: str or None
4088
    @param hooks_base_dir: if not None, this overrides the
4089
        L{pathutils.HOOKS_BASE_DIR} (useful for unittests)
4090

4091
    """
4092
    if hooks_base_dir is None:
4093
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
4094
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
4095
    # constant
4096
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
4097

    
4098
  def RunLocalHooks(self, node_list, hpath, phase, env):
4099
    """Check that the hooks will be run only locally and then run them.
4100

4101
    """
4102
    assert len(node_list) == 1
4103
    node = node_list[0]
4104
    _, myself = ssconf.GetMasterAndMyself()
4105
    assert node == myself
4106

    
4107
    results = self.RunHooks(hpath, phase, env)
4108

    
4109
    # Return values in the form expected by HooksMaster
4110
    return {node: (None, False, results)}
4111

    
4112
  def RunHooks(self, hpath, phase, env):
4113
    """Run the scripts in the hooks directory.
4114

4115
    @type hpath: str
4116
    @param hpath: the path to the hooks directory which
4117
        holds the scripts
4118
    @type phase: str
4119
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
4120
        L{constants.HOOKS_PHASE_POST}
4121
    @type env: dict
4122
    @param env: dictionary with the environment for the hook
4123
    @rtype: list
4124
    @return: list of 3-element tuples:
4125
      - script path
4126
      - script result, either L{constants.HKR_SUCCESS} or
4127
        L{constants.HKR_FAIL}
4128
      - output of the script
4129

4130
    @raise errors.ProgrammerError: for invalid input
4131
        parameters
4132

4133
    """
4134
    if phase == constants.HOOKS_PHASE_PRE:
4135
      suffix = "pre"
4136
    elif phase == constants.HOOKS_PHASE_POST:
4137
      suffix = "post"
4138
    else:
4139
      _Fail("Unknown hooks phase '%s'", phase)
4140

    
4141
    subdir = "%s-%s.d" % (hpath, suffix)
4142
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
4143

    
4144
    results = []
4145

    
4146
    if not os.path.isdir(dir_name):
4147
      # for non-existing/non-dirs, we simply exit instead of logging a
4148
      # warning at every operation
4149
      return results
4150

    
4151
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
4152

    
4153
    for (relname, relstatus, runresult) in runparts_results:
4154
      if relstatus == constants.RUNPARTS_SKIP:
4155
        rrval = constants.HKR_SKIP
4156
        output = ""
4157
      elif relstatus == constants.RUNPARTS_ERR:
4158
        rrval = constants.HKR_FAIL
4159
        output = "Hook script execution error: %s" % runresult
4160
      elif relstatus == constants.RUNPARTS_RUN:
4161
        if runresult.failed:
4162
          rrval = constants.HKR_FAIL
4163
        else:
4164
          rrval = constants.HKR_SUCCESS
4165
        output = utils.SafeEncode(runresult.output.strip())
4166
      results.append(("%s/%s" % (subdir, relname), rrval, output))
4167

    
4168
    return results
4169

    
4170

    
4171
class IAllocatorRunner(object):
4172
  """IAllocator runner.
4173

4174
  This class is instantiated on the node side (ganeti-noded) and not on
4175
  the master side.
4176

4177
  """
4178
  @staticmethod
4179
  def Run(name, idata):
4180
    """Run an iallocator script.
4181

4182
    @type name: str
4183
    @param name: the iallocator script name
4184
    @type idata: str
4185
    @param idata: the allocator input data
4186

4187
    @rtype: tuple
4188
    @return: two element tuple of:
4189
       - status
4190
       - either error message or stdout of allocator (for success)
4191

4192
    """
4193
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
4194
                                  os.path.isfile)
4195
    if alloc_script is None:
4196
      _Fail("iallocator module '%s' not found in the search path", name)
4197

    
4198
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
4199
    try:
4200
      os.write(fd, idata)
4201
      os.close(fd)
4202
      result = utils.RunCmd([alloc_script, fin_name])
4203
      if result.failed:
4204
        _Fail("iallocator module '%s' failed: %s, output '%s'",
4205
              name, result.fail_reason, result.output)
4206
    finally:
4207
      os.unlink(fin_name)
4208

    
4209
    return result.stdout
4210

    
4211

    
4212
class DevCacheManager(object):
4213
  """Simple class for managing a cache of block device information.
4214

4215
  """
4216
  _DEV_PREFIX = "/dev/"
4217
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4218

    
4219
  @classmethod
4220
  def _ConvertPath(cls, dev_path):
4221
    """Converts a /dev/name path to the cache file name.
4222

4223
    This replaces slashes with underscores and strips the /dev
4224
    prefix. It then returns the full path to the cache file.
4225

4226
    @type dev_path: str
4227
    @param dev_path: the C{/dev/} path name
4228
    @rtype: str
4229
    @return: the converted path name
4230

4231
    """
4232
    if dev_path.startswith(cls._DEV_PREFIX):
4233
      dev_path = dev_path[len(cls._DEV_PREFIX):]
4234
    dev_path = dev_path.replace("/", "_")
4235
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4236
    return fpath
4237

    
4238
  @classmethod
4239
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4240
    """Updates the cache information for a given device.
4241

4242
    @type dev_path: str
4243
    @param dev_path: the pathname of the device
4244
    @type owner: str
4245
    @param owner: the owner (instance name) of the device
4246
    @type on_primary: bool
4247
    @param on_primary: whether this is the primary
4248
        node nor not
4249
    @type iv_name: str
4250
    @param iv_name: the instance-visible name of the
4251
        device, as in objects.Disk.iv_name
4252

4253
    @rtype: None
4254

4255
    """
4256
    if dev_path is None:
4257
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
4258
      return
4259
    fpath = cls._ConvertPath(dev_path)
4260
    if on_primary:
4261
      state = "primary"
4262
    else:
4263
      state = "secondary"
4264
    if iv_name is None:
4265
      iv_name = "not_visible"
4266
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4267
    try:
4268
      utils.WriteFile(fpath, data=fdata)
4269
    except EnvironmentError, err:
4270
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4271

    
4272
  @classmethod
4273
  def RemoveCache(cls, dev_path):
4274
    """Remove data for a dev_path.
4275

4276
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
4277
    path name and logging.
4278

4279
    @type dev_path: str
4280
    @param dev_path: the pathname of the device
4281

4282
    @rtype: None
4283

4284
    """
4285
    if dev_path is None:
4286
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
4287
      return
4288
    fpath = cls._ConvertPath(dev_path)
4289
    try:
4290
      utils.RemoveFile(fpath)
4291
    except EnvironmentError, err:
4292
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)