Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ a1860404

History | View | Annotate | Download (128.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 VerifyNode(what, cluster_name):
730
  """Verify the status of the local node.
731

732
  Based on the input L{what} parameter, various checks are done on the
733
  local node.
734

735
  If the I{filelist} key is present, this list of
736
  files is checksummed and the file/checksum pairs are returned.
737

738
  If the I{nodelist} key is present, we check that we have
739
  connectivity via ssh with the target nodes (and check the hostname
740
  report).
741

742
  If the I{node-net-test} key is present, we check that we have
743
  connectivity to the given nodes via both primary IP and, if
744
  applicable, secondary IPs.
745

746
  @type what: C{dict}
747
  @param what: a dictionary of things to check:
748
      - filelist: list of files for which to compute checksums
749
      - nodelist: list of nodes we should check ssh communication with
750
      - node-net-test: list of nodes we should check node daemon port
751
        connectivity with
752
      - hypervisor: list with hypervisors to run the verify for
753
  @rtype: dict
754
  @return: a dictionary with the same keys as the input dict, and
755
      values representing the result of the checks
756

757
  """
758
  result = {}
759
  my_name = netutils.Hostname.GetSysName()
760
  port = netutils.GetDaemonPort(constants.NODED)
761
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
762

    
763
  if constants.NV_HYPERVISOR in what and vm_capable:
764
    result[constants.NV_HYPERVISOR] = tmp = {}
765
    for hv_name in what[constants.NV_HYPERVISOR]:
766
      try:
767
        val = hypervisor.GetHypervisor(hv_name).Verify()
768
      except errors.HypervisorError, err:
769
        val = "Error while checking hypervisor: %s" % str(err)
770
      tmp[hv_name] = val
771

    
772
  if constants.NV_HVPARAMS in what and vm_capable:
773
    result[constants.NV_HVPARAMS] = tmp = []
774
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
775
      try:
776
        logging.info("Validating hv %s, %s", hv_name, hvparms)
777
        hypervisor.GetHypervisor(hv_name).ValidateParameters(hvparms)
778
      except errors.HypervisorError, err:
779
        tmp.append((source, hv_name, str(err)))
780

    
781
  if constants.NV_FILELIST in what:
782
    fingerprints = utils.FingerprintFiles(map(vcluster.LocalizeVirtualPath,
783
                                              what[constants.NV_FILELIST]))
784
    result[constants.NV_FILELIST] = \
785
      dict((vcluster.MakeVirtualPath(key), value)
786
           for (key, value) in fingerprints.items())
787

    
788
  if constants.NV_NODELIST in what:
789
    (nodes, bynode) = what[constants.NV_NODELIST]
790

    
791
    # Add nodes from other groups (different for each node)
792
    try:
793
      nodes.extend(bynode[my_name])
794
    except KeyError:
795
      pass
796

    
797
    # Use a random order
798
    random.shuffle(nodes)
799

    
800
    # Try to contact all nodes
801
    val = {}
802
    for node in nodes:
803
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
804
      if not success:
805
        val[node] = message
806

    
807
    result[constants.NV_NODELIST] = val
808

    
809
  if constants.NV_NODENETTEST in what:
810
    result[constants.NV_NODENETTEST] = tmp = {}
811
    my_pip = my_sip = None
812
    for name, pip, sip in what[constants.NV_NODENETTEST]:
813
      if name == my_name:
814
        my_pip = pip
815
        my_sip = sip
816
        break
817
    if not my_pip:
818
      tmp[my_name] = ("Can't find my own primary/secondary IP"
819
                      " in the node list")
820
    else:
821
      for name, pip, sip in what[constants.NV_NODENETTEST]:
822
        fail = []
823
        if not netutils.TcpPing(pip, port, source=my_pip):
824
          fail.append("primary")
825
        if sip != pip:
826
          if not netutils.TcpPing(sip, port, source=my_sip):
827
            fail.append("secondary")
828
        if fail:
829
          tmp[name] = ("failure using the %s interface(s)" %
830
                       " and ".join(fail))
831

    
832
  if constants.NV_MASTERIP in what:
833
    # FIXME: add checks on incoming data structures (here and in the
834
    # rest of the function)
835
    master_name, master_ip = what[constants.NV_MASTERIP]
836
    if master_name == my_name:
837
      source = constants.IP4_ADDRESS_LOCALHOST
838
    else:
839
      source = None
840
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
841
                                                     source=source)
842

    
843
  if constants.NV_USERSCRIPTS in what:
844
    result[constants.NV_USERSCRIPTS] = \
845
      [script for script in what[constants.NV_USERSCRIPTS]
846
       if not utils.IsExecutable(script)]
847

    
848
  if constants.NV_OOB_PATHS in what:
849
    result[constants.NV_OOB_PATHS] = tmp = []
850
    for path in what[constants.NV_OOB_PATHS]:
851
      try:
852
        st = os.stat(path)
853
      except OSError, err:
854
        tmp.append("error stating out of band helper: %s" % err)
855
      else:
856
        if stat.S_ISREG(st.st_mode):
857
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
858
            tmp.append(None)
859
          else:
860
            tmp.append("out of band helper %s is not executable" % path)
861
        else:
862
          tmp.append("out of band helper %s is not a file" % path)
863

    
864
  if constants.NV_LVLIST in what and vm_capable:
865
    try:
866
      val = GetVolumeList(utils.ListVolumeGroups().keys())
867
    except RPCFail, err:
868
      val = str(err)
869
    result[constants.NV_LVLIST] = val
870

    
871
  if constants.NV_INSTANCELIST in what and vm_capable:
872
    # GetInstanceList can fail
873
    try:
874
      val = GetInstanceList(what[constants.NV_INSTANCELIST])
875
    except RPCFail, err:
876
      val = str(err)
877
    result[constants.NV_INSTANCELIST] = val
878

    
879
  if constants.NV_VGLIST in what and vm_capable:
880
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
881

    
882
  if constants.NV_PVLIST in what and vm_capable:
883
    check_exclusive_pvs = constants.NV_EXCLUSIVEPVS in what
884
    val = bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
885
                                       filter_allocatable=False,
886
                                       include_lvs=check_exclusive_pvs)
887
    if check_exclusive_pvs:
888
      result[constants.NV_EXCLUSIVEPVS] = _CheckExclusivePvs(val)
889
      for pvi in val:
890
        # Avoid sending useless data on the wire
891
        pvi.lv_list = []
892
    result[constants.NV_PVLIST] = map(objects.LvmPvInfo.ToDict, val)
893

    
894
  if constants.NV_VERSION in what:
895
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
896
                                    constants.RELEASE_VERSION)
897

    
898
  if constants.NV_HVINFO in what and vm_capable:
899
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
900
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
901

    
902
  if constants.NV_DRBDVERSION in what and vm_capable:
903
    try:
904
      drbd_version = DRBD8.GetProcInfo().GetVersionString()
905
    except errors.BlockDeviceError, err:
906
      logging.warning("Can't get DRBD version", exc_info=True)
907
      drbd_version = str(err)
908
    result[constants.NV_DRBDVERSION] = drbd_version
909

    
910
  if constants.NV_DRBDLIST in what and vm_capable:
911
    try:
912
      used_minors = drbd.DRBD8.GetUsedDevs()
913
    except errors.BlockDeviceError, err:
914
      logging.warning("Can't get used minors list", exc_info=True)
915
      used_minors = str(err)
916
    result[constants.NV_DRBDLIST] = used_minors
917

    
918
  if constants.NV_DRBDHELPER in what and vm_capable:
919
    status = True
920
    try:
921
      payload = drbd.DRBD8.GetUsermodeHelper()
922
    except errors.BlockDeviceError, err:
923
      logging.error("Can't get DRBD usermode helper: %s", str(err))
924
      status = False
925
      payload = str(err)
926
    result[constants.NV_DRBDHELPER] = (status, payload)
927

    
928
  if constants.NV_NODESETUP in what:
929
    result[constants.NV_NODESETUP] = tmpr = []
930
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
931
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
932
                  " under /sys, missing required directories /sys/block"
933
                  " and /sys/class/net")
934
    if (not os.path.isdir("/proc/sys") or
935
        not os.path.isfile("/proc/sysrq-trigger")):
936
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
937
                  " under /proc, missing required directory /proc/sys and"
938
                  " the file /proc/sysrq-trigger")
939

    
940
  if constants.NV_TIME in what:
941
    result[constants.NV_TIME] = utils.SplitTime(time.time())
942

    
943
  if constants.NV_OSLIST in what and vm_capable:
944
    result[constants.NV_OSLIST] = DiagnoseOS()
945

    
946
  if constants.NV_BRIDGES in what and vm_capable:
947
    result[constants.NV_BRIDGES] = [bridge
948
                                    for bridge in what[constants.NV_BRIDGES]
949
                                    if not utils.BridgeExists(bridge)]
950

    
951
  if what.get(constants.NV_FILE_STORAGE_PATHS) == my_name:
952
    result[constants.NV_FILE_STORAGE_PATHS] = \
953
      bdev.ComputeWrongFileStoragePaths()
954

    
955
  return result
956

    
957

    
958
def GetBlockDevSizes(devices):
959
  """Return the size of the given block devices
960

961
  @type devices: list
962
  @param devices: list of block device nodes to query
963
  @rtype: dict
964
  @return:
965
    dictionary of all block devices under /dev (key). The value is their
966
    size in MiB.
967

968
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
969

970
  """
971
  DEV_PREFIX = "/dev/"
972
  blockdevs = {}
973

    
974
  for devpath in devices:
975
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
976
      continue
977

    
978
    try:
979
      st = os.stat(devpath)
980
    except EnvironmentError, err:
981
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
982
      continue
983

    
984
    if stat.S_ISBLK(st.st_mode):
985
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
986
      if result.failed:
987
        # We don't want to fail, just do not list this device as available
988
        logging.warning("Cannot get size for block device %s", devpath)
989
        continue
990

    
991
      size = int(result.stdout) / (1024 * 1024)
992
      blockdevs[devpath] = size
993
  return blockdevs
994

    
995

    
996
def GetVolumeList(vg_names):
997
  """Compute list of logical volumes and their size.
998

999
  @type vg_names: list
1000
  @param vg_names: the volume groups whose LVs we should list, or
1001
      empty for all volume groups
1002
  @rtype: dict
1003
  @return:
1004
      dictionary of all partions (key) with value being a tuple of
1005
      their size (in MiB), inactive and online status::
1006

1007
        {'xenvg/test1': ('20.06', True, True)}
1008

1009
      in case of errors, a string is returned with the error
1010
      details.
1011

1012
  """
1013
  lvs = {}
1014
  sep = "|"
1015
  if not vg_names:
1016
    vg_names = []
1017
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1018
                         "--separator=%s" % sep,
1019
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
1020
  if result.failed:
1021
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
1022

    
1023
  for line in result.stdout.splitlines():
1024
    line = line.strip()
1025
    match = _LVSLINE_REGEX.match(line)
1026
    if not match:
1027
      logging.error("Invalid line returned from lvs output: '%s'", line)
1028
      continue
1029
    vg_name, name, size, attr = match.groups()
1030
    inactive = attr[4] == "-"
1031
    online = attr[5] == "o"
1032
    virtual = attr[0] == "v"
1033
    if virtual:
1034
      # we don't want to report such volumes as existing, since they
1035
      # don't really hold data
1036
      continue
1037
    lvs[vg_name + "/" + name] = (size, inactive, online)
1038

    
1039
  return lvs
1040

    
1041

    
1042
def ListVolumeGroups():
1043
  """List the volume groups and their size.
1044

1045
  @rtype: dict
1046
  @return: dictionary with keys volume name and values the
1047
      size of the volume
1048

1049
  """
1050
  return utils.ListVolumeGroups()
1051

    
1052

    
1053
def NodeVolumes():
1054
  """List all volumes on this node.
1055

1056
  @rtype: list
1057
  @return:
1058
    A list of dictionaries, each having four keys:
1059
      - name: the logical volume name,
1060
      - size: the size of the logical volume
1061
      - dev: the physical device on which the LV lives
1062
      - vg: the volume group to which it belongs
1063

1064
    In case of errors, we return an empty list and log the
1065
    error.
1066

1067
    Note that since a logical volume can live on multiple physical
1068
    volumes, the resulting list might include a logical volume
1069
    multiple times.
1070

1071
  """
1072
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1073
                         "--separator=|",
1074
                         "--options=lv_name,lv_size,devices,vg_name"])
1075
  if result.failed:
1076
    _Fail("Failed to list logical volumes, lvs output: %s",
1077
          result.output)
1078

    
1079
  def parse_dev(dev):
1080
    return dev.split("(")[0]
1081

    
1082
  def handle_dev(dev):
1083
    return [parse_dev(x) for x in dev.split(",")]
1084

    
1085
  def map_line(line):
1086
    line = [v.strip() for v in line]
1087
    return [{"name": line[0], "size": line[1],
1088
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
1089

    
1090
  all_devs = []
1091
  for line in result.stdout.splitlines():
1092
    if line.count("|") >= 3:
1093
      all_devs.extend(map_line(line.split("|")))
1094
    else:
1095
      logging.warning("Strange line in the output from lvs: '%s'", line)
1096
  return all_devs
1097

    
1098

    
1099
def BridgesExist(bridges_list):
1100
  """Check if a list of bridges exist on the current node.
1101

1102
  @rtype: boolean
1103
  @return: C{True} if all of them exist, C{False} otherwise
1104

1105
  """
1106
  missing = []
1107
  for bridge in bridges_list:
1108
    if not utils.BridgeExists(bridge):
1109
      missing.append(bridge)
1110

    
1111
  if missing:
1112
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
1113

    
1114

    
1115
def GetInstanceList(hypervisor_list):
1116
  """Provides a list of instances.
1117

1118
  @type hypervisor_list: list
1119
  @param hypervisor_list: the list of hypervisors to query information
1120

1121
  @rtype: list
1122
  @return: a list of all running instances on the current node
1123
    - instance1.example.com
1124
    - instance2.example.com
1125

1126
  """
1127
  results = []
1128
  for hname in hypervisor_list:
1129
    try:
1130
      names = hypervisor.GetHypervisor(hname).ListInstances()
1131
      results.extend(names)
1132
    except errors.HypervisorError, err:
1133
      _Fail("Error enumerating instances (hypervisor %s): %s",
1134
            hname, err, exc=True)
1135

    
1136
  return results
1137

    
1138

    
1139
def GetInstanceInfo(instance, hname):
1140
  """Gives back the information about an instance as a dictionary.
1141

1142
  @type instance: string
1143
  @param instance: the instance name
1144
  @type hname: string
1145
  @param hname: the hypervisor type of the instance
1146

1147
  @rtype: dict
1148
  @return: dictionary with the following keys:
1149
      - memory: memory size of instance (int)
1150
      - state: xen state of instance (string)
1151
      - time: cpu time of instance (float)
1152
      - vcpus: the number of vcpus (int)
1153

1154
  """
1155
  output = {}
1156

    
1157
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
1158
  if iinfo is not None:
1159
    output["memory"] = iinfo[2]
1160
    output["vcpus"] = iinfo[3]
1161
    output["state"] = iinfo[4]
1162
    output["time"] = iinfo[5]
1163

    
1164
  return output
1165

    
1166

    
1167
def GetInstanceMigratable(instance):
1168
  """Gives whether an instance can be migrated.
1169

1170
  @type instance: L{objects.Instance}
1171
  @param instance: object representing the instance to be checked.
1172

1173
  @rtype: tuple
1174
  @return: tuple of (result, description) where:
1175
      - result: whether the instance can be migrated or not
1176
      - description: a description of the issue, if relevant
1177

1178
  """
1179
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1180
  iname = instance.name
1181
  if iname not in hyper.ListInstances():
1182
    _Fail("Instance %s is not running", iname)
1183

    
1184
  for idx in range(len(instance.disks)):
1185
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1186
    if not os.path.islink(link_name):
1187
      logging.warning("Instance %s is missing symlink %s for disk %d",
1188
                      iname, link_name, idx)
1189

    
1190

    
1191
def GetAllInstancesInfo(hypervisor_list):
1192
  """Gather data about all instances.
1193

1194
  This is the equivalent of L{GetInstanceInfo}, except that it
1195
  computes data for all instances at once, thus being faster if one
1196
  needs data about more than one instance.
1197

1198
  @type hypervisor_list: list
1199
  @param hypervisor_list: list of hypervisors to query for instance data
1200

1201
  @rtype: dict
1202
  @return: dictionary of instance: data, with data having the following keys:
1203
      - memory: memory size of instance (int)
1204
      - state: xen state of instance (string)
1205
      - time: cpu time of instance (float)
1206
      - vcpus: the number of vcpus
1207

1208
  """
1209
  output = {}
1210

    
1211
  for hname in hypervisor_list:
1212
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
1213
    if iinfo:
1214
      for name, _, memory, vcpus, state, times in iinfo:
1215
        value = {
1216
          "memory": memory,
1217
          "vcpus": vcpus,
1218
          "state": state,
1219
          "time": times,
1220
          }
1221
        if name in output:
1222
          # we only check static parameters, like memory and vcpus,
1223
          # and not state and time which can change between the
1224
          # invocations of the different hypervisors
1225
          for key in "memory", "vcpus":
1226
            if value[key] != output[name][key]:
1227
              _Fail("Instance %s is running twice"
1228
                    " with different parameters", name)
1229
        output[name] = value
1230

    
1231
  return output
1232

    
1233

    
1234
def _InstanceLogName(kind, os_name, instance, component):
1235
  """Compute the OS log filename for a given instance and operation.
1236

1237
  The instance name and os name are passed in as strings since not all
1238
  operations have these as part of an instance object.
1239

1240
  @type kind: string
1241
  @param kind: the operation type (e.g. add, import, etc.)
1242
  @type os_name: string
1243
  @param os_name: the os name
1244
  @type instance: string
1245
  @param instance: the name of the instance being imported/added/etc.
1246
  @type component: string or None
1247
  @param component: the name of the component of the instance being
1248
      transferred
1249

1250
  """
1251
  # TODO: Use tempfile.mkstemp to create unique filename
1252
  if component:
1253
    assert "/" not in component
1254
    c_msg = "-%s" % component
1255
  else:
1256
    c_msg = ""
1257
  base = ("%s-%s-%s%s-%s.log" %
1258
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1259
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1260

    
1261

    
1262
def InstanceOsAdd(instance, reinstall, debug):
1263
  """Add an OS to an instance.
1264

1265
  @type instance: L{objects.Instance}
1266
  @param instance: Instance whose OS is to be installed
1267
  @type reinstall: boolean
1268
  @param reinstall: whether this is an instance reinstall
1269
  @type debug: integer
1270
  @param debug: debug level, passed to the OS scripts
1271
  @rtype: None
1272

1273
  """
1274
  inst_os = OSFromDisk(instance.os)
1275

    
1276
  create_env = OSEnvironment(instance, inst_os, debug)
1277
  if reinstall:
1278
    create_env["INSTANCE_REINSTALL"] = "1"
1279

    
1280
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1281

    
1282
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1283
                        cwd=inst_os.path, output=logfile, reset_env=True)
1284
  if result.failed:
1285
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1286
                  " output: %s", result.cmd, result.fail_reason, logfile,
1287
                  result.output)
1288
    lines = [utils.SafeEncode(val)
1289
             for val in utils.TailFile(logfile, lines=20)]
1290
    _Fail("OS create script failed (%s), last lines in the"
1291
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1292

    
1293

    
1294
def RunRenameInstance(instance, old_name, debug):
1295
  """Run the OS rename script for an instance.
1296

1297
  @type instance: L{objects.Instance}
1298
  @param instance: Instance whose OS is to be installed
1299
  @type old_name: string
1300
  @param old_name: previous instance name
1301
  @type debug: integer
1302
  @param debug: debug level, passed to the OS scripts
1303
  @rtype: boolean
1304
  @return: the success of the operation
1305

1306
  """
1307
  inst_os = OSFromDisk(instance.os)
1308

    
1309
  rename_env = OSEnvironment(instance, inst_os, debug)
1310
  rename_env["OLD_INSTANCE_NAME"] = old_name
1311

    
1312
  logfile = _InstanceLogName("rename", instance.os,
1313
                             "%s-%s" % (old_name, instance.name), None)
1314

    
1315
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1316
                        cwd=inst_os.path, output=logfile, reset_env=True)
1317

    
1318
  if result.failed:
1319
    logging.error("os create command '%s' returned error: %s output: %s",
1320
                  result.cmd, result.fail_reason, result.output)
1321
    lines = [utils.SafeEncode(val)
1322
             for val in utils.TailFile(logfile, lines=20)]
1323
    _Fail("OS rename script failed (%s), last lines in the"
1324
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1325

    
1326

    
1327
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1328
  """Returns symlink path for block device.
1329

1330
  """
1331
  if _dir is None:
1332
    _dir = pathutils.DISK_LINKS_DIR
1333

    
1334
  return utils.PathJoin(_dir,
1335
                        ("%s%s%s" %
1336
                         (instance_name, constants.DISK_SEPARATOR, idx)))
1337

    
1338

    
1339
def _SymlinkBlockDev(instance_name, device_path, idx):
1340
  """Set up symlinks to a instance's block device.
1341

1342
  This is an auxiliary function run when an instance is start (on the primary
1343
  node) or when an instance is migrated (on the target node).
1344

1345

1346
  @param instance_name: the name of the target instance
1347
  @param device_path: path of the physical block device, on the node
1348
  @param idx: the disk index
1349
  @return: absolute path to the disk's symlink
1350

1351
  """
1352
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1353
  try:
1354
    os.symlink(device_path, link_name)
1355
  except OSError, err:
1356
    if err.errno == errno.EEXIST:
1357
      if (not os.path.islink(link_name) or
1358
          os.readlink(link_name) != device_path):
1359
        os.remove(link_name)
1360
        os.symlink(device_path, link_name)
1361
    else:
1362
      raise
1363

    
1364
  return link_name
1365

    
1366

    
1367
def _RemoveBlockDevLinks(instance_name, disks):
1368
  """Remove the block device symlinks belonging to the given instance.
1369

1370
  """
1371
  for idx, _ in enumerate(disks):
1372
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1373
    if os.path.islink(link_name):
1374
      try:
1375
        os.remove(link_name)
1376
      except OSError:
1377
        logging.exception("Can't remove symlink '%s'", link_name)
1378

    
1379

    
1380
def _GatherAndLinkBlockDevs(instance):
1381
  """Set up an instance's block device(s).
1382

1383
  This is run on the primary node at instance startup. The block
1384
  devices must be already assembled.
1385

1386
  @type instance: L{objects.Instance}
1387
  @param instance: the instance whose disks we shoul assemble
1388
  @rtype: list
1389
  @return: list of (disk_object, device_path)
1390

1391
  """
1392
  block_devices = []
1393
  for idx, disk in enumerate(instance.disks):
1394
    device = _RecursiveFindBD(disk)
1395
    if device is None:
1396
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1397
                                    str(disk))
1398
    device.Open()
1399
    try:
1400
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1401
    except OSError, e:
1402
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1403
                                    e.strerror)
1404

    
1405
    block_devices.append((disk, link_name))
1406

    
1407
  return block_devices
1408

    
1409

    
1410
def StartInstance(instance, startup_paused, reason, store_reason=True):
1411
  """Start an instance.
1412

1413
  @type instance: L{objects.Instance}
1414
  @param instance: the instance object
1415
  @type startup_paused: bool
1416
  @param instance: pause instance at startup?
1417
  @type reason: list of reasons
1418
  @param reason: the reason trail for this startup
1419
  @type store_reason: boolean
1420
  @param store_reason: whether to store the shutdown reason trail on file
1421
  @rtype: None
1422

1423
  """
1424
  running_instances = GetInstanceList([instance.hypervisor])
1425

    
1426
  if instance.name in running_instances:
1427
    logging.info("Instance %s already running, not starting", instance.name)
1428
    return
1429

    
1430
  try:
1431
    block_devices = _GatherAndLinkBlockDevs(instance)
1432
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1433
    hyper.StartInstance(instance, block_devices, startup_paused)
1434
    if store_reason:
1435
      _StoreInstReasonTrail(instance.name, reason)
1436
  except errors.BlockDeviceError, err:
1437
    _Fail("Block device error: %s", err, exc=True)
1438
  except errors.HypervisorError, err:
1439
    _RemoveBlockDevLinks(instance.name, instance.disks)
1440
    _Fail("Hypervisor error: %s", err, exc=True)
1441

    
1442

    
1443
def InstanceShutdown(instance, timeout, reason, store_reason=True):
1444
  """Shut an instance down.
1445

1446
  @note: this functions uses polling with a hardcoded timeout.
1447

1448
  @type instance: L{objects.Instance}
1449
  @param instance: the instance object
1450
  @type timeout: integer
1451
  @param timeout: maximum timeout for soft shutdown
1452
  @type reason: list of reasons
1453
  @param reason: the reason trail for this shutdown
1454
  @type store_reason: boolean
1455
  @param store_reason: whether to store the shutdown reason trail on file
1456
  @rtype: None
1457

1458
  """
1459
  hv_name = instance.hypervisor
1460
  hyper = hypervisor.GetHypervisor(hv_name)
1461
  iname = instance.name
1462

    
1463
  if instance.name not in hyper.ListInstances():
1464
    logging.info("Instance %s not running, doing nothing", iname)
1465
    return
1466

    
1467
  class _TryShutdown:
1468
    def __init__(self):
1469
      self.tried_once = False
1470

    
1471
    def __call__(self):
1472
      if iname not in hyper.ListInstances():
1473
        return
1474

    
1475
      try:
1476
        hyper.StopInstance(instance, retry=self.tried_once)
1477
        if store_reason:
1478
          _StoreInstReasonTrail(instance.name, reason)
1479
      except errors.HypervisorError, err:
1480
        if iname not in hyper.ListInstances():
1481
          # if the instance is no longer existing, consider this a
1482
          # success and go to cleanup
1483
          return
1484

    
1485
        _Fail("Failed to stop instance %s: %s", iname, err)
1486

    
1487
      self.tried_once = True
1488

    
1489
      raise utils.RetryAgain()
1490

    
1491
  try:
1492
    utils.Retry(_TryShutdown(), 5, timeout)
1493
  except utils.RetryTimeout:
1494
    # the shutdown did not succeed
1495
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1496

    
1497
    try:
1498
      hyper.StopInstance(instance, force=True)
1499
    except errors.HypervisorError, err:
1500
      if iname in hyper.ListInstances():
1501
        # only raise an error if the instance still exists, otherwise
1502
        # the error could simply be "instance ... unknown"!
1503
        _Fail("Failed to force stop instance %s: %s", iname, err)
1504

    
1505
    time.sleep(1)
1506

    
1507
    if iname in hyper.ListInstances():
1508
      _Fail("Could not shutdown instance %s even by destroy", iname)
1509

    
1510
  try:
1511
    hyper.CleanupInstance(instance.name)
1512
  except errors.HypervisorError, err:
1513
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1514

    
1515
  _RemoveBlockDevLinks(iname, instance.disks)
1516

    
1517

    
1518
def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1519
  """Reboot an instance.
1520

1521
  @type instance: L{objects.Instance}
1522
  @param instance: the instance object to reboot
1523
  @type reboot_type: str
1524
  @param reboot_type: the type of reboot, one the following
1525
    constants:
1526
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1527
        instance OS, do not recreate the VM
1528
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1529
        restart the VM (at the hypervisor level)
1530
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1531
        not accepted here, since that mode is handled differently, in
1532
        cmdlib, and translates into full stop and start of the
1533
        instance (instead of a call_instance_reboot RPC)
1534
  @type shutdown_timeout: integer
1535
  @param shutdown_timeout: maximum timeout for soft shutdown
1536
  @type reason: list of reasons
1537
  @param reason: the reason trail for this reboot
1538
  @rtype: None
1539

1540
  """
1541
  running_instances = GetInstanceList([instance.hypervisor])
1542

    
1543
  if instance.name not in running_instances:
1544
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1545

    
1546
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1547
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1548
    try:
1549
      hyper.RebootInstance(instance)
1550
    except errors.HypervisorError, err:
1551
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1552
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1553
    try:
1554
      InstanceShutdown(instance, shutdown_timeout, reason, store_reason=False)
1555
      result = StartInstance(instance, False, reason, store_reason=False)
1556
      _StoreInstReasonTrail(instance.name, reason)
1557
      return result
1558
    except errors.HypervisorError, err:
1559
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1560
  else:
1561
    _Fail("Invalid reboot_type received: %s", reboot_type)
1562

    
1563

    
1564
def InstanceBalloonMemory(instance, memory):
1565
  """Resize an instance's memory.
1566

1567
  @type instance: L{objects.Instance}
1568
  @param instance: the instance object
1569
  @type memory: int
1570
  @param memory: new memory amount in MB
1571
  @rtype: None
1572

1573
  """
1574
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1575
  running = hyper.ListInstances()
1576
  if instance.name not in running:
1577
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1578
    return
1579
  try:
1580
    hyper.BalloonInstanceMemory(instance, memory)
1581
  except errors.HypervisorError, err:
1582
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1583

    
1584

    
1585
def MigrationInfo(instance):
1586
  """Gather information about an instance to be migrated.
1587

1588
  @type instance: L{objects.Instance}
1589
  @param instance: the instance definition
1590

1591
  """
1592
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1593
  try:
1594
    info = hyper.MigrationInfo(instance)
1595
  except errors.HypervisorError, err:
1596
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1597
  return info
1598

    
1599

    
1600
def AcceptInstance(instance, info, target):
1601
  """Prepare the node to accept an instance.
1602

1603
  @type instance: L{objects.Instance}
1604
  @param instance: the instance definition
1605
  @type info: string/data (opaque)
1606
  @param info: migration information, from the source node
1607
  @type target: string
1608
  @param target: target host (usually ip), on this node
1609

1610
  """
1611
  # TODO: why is this required only for DTS_EXT_MIRROR?
1612
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1613
    # Create the symlinks, as the disks are not active
1614
    # in any way
1615
    try:
1616
      _GatherAndLinkBlockDevs(instance)
1617
    except errors.BlockDeviceError, err:
1618
      _Fail("Block device error: %s", err, exc=True)
1619

    
1620
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1621
  try:
1622
    hyper.AcceptInstance(instance, info, target)
1623
  except errors.HypervisorError, err:
1624
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1625
      _RemoveBlockDevLinks(instance.name, instance.disks)
1626
    _Fail("Failed to accept instance: %s", err, exc=True)
1627

    
1628

    
1629
def FinalizeMigrationDst(instance, info, success):
1630
  """Finalize any preparation to accept an instance.
1631

1632
  @type instance: L{objects.Instance}
1633
  @param instance: the instance definition
1634
  @type info: string/data (opaque)
1635
  @param info: migration information, from the source node
1636
  @type success: boolean
1637
  @param success: whether the migration was a success or a failure
1638

1639
  """
1640
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1641
  try:
1642
    hyper.FinalizeMigrationDst(instance, info, success)
1643
  except errors.HypervisorError, err:
1644
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1645

    
1646

    
1647
def MigrateInstance(instance, target, live):
1648
  """Migrates an instance to another node.
1649

1650
  @type instance: L{objects.Instance}
1651
  @param instance: the instance definition
1652
  @type target: string
1653
  @param target: the target node name
1654
  @type live: boolean
1655
  @param live: whether the migration should be done live or not (the
1656
      interpretation of this parameter is left to the hypervisor)
1657
  @raise RPCFail: if migration fails for some reason
1658

1659
  """
1660
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1661

    
1662
  try:
1663
    hyper.MigrateInstance(instance, target, live)
1664
  except errors.HypervisorError, err:
1665
    _Fail("Failed to migrate instance: %s", err, exc=True)
1666

    
1667

    
1668
def FinalizeMigrationSource(instance, success, live):
1669
  """Finalize the instance migration on the source node.
1670

1671
  @type instance: L{objects.Instance}
1672
  @param instance: the instance definition of the migrated instance
1673
  @type success: bool
1674
  @param success: whether the migration succeeded or not
1675
  @type live: bool
1676
  @param live: whether the user requested a live migration or not
1677
  @raise RPCFail: If the execution fails for some reason
1678

1679
  """
1680
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1681

    
1682
  try:
1683
    hyper.FinalizeMigrationSource(instance, success, live)
1684
  except Exception, err:  # pylint: disable=W0703
1685
    _Fail("Failed to finalize the migration on the source node: %s", err,
1686
          exc=True)
1687

    
1688

    
1689
def GetMigrationStatus(instance):
1690
  """Get the migration status
1691

1692
  @type instance: L{objects.Instance}
1693
  @param instance: the instance that is being migrated
1694
  @rtype: L{objects.MigrationStatus}
1695
  @return: the status of the current migration (one of
1696
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1697
           progress info that can be retrieved from the hypervisor
1698
  @raise RPCFail: If the migration status cannot be retrieved
1699

1700
  """
1701
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1702
  try:
1703
    return hyper.GetMigrationStatus(instance)
1704
  except Exception, err:  # pylint: disable=W0703
1705
    _Fail("Failed to get migration status: %s", err, exc=True)
1706

    
1707

    
1708
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
1709
  """Creates a block device for an instance.
1710

1711
  @type disk: L{objects.Disk}
1712
  @param disk: the object describing the disk we should create
1713
  @type size: int
1714
  @param size: the size of the physical underlying device, in MiB
1715
  @type owner: str
1716
  @param owner: the name of the instance for which disk is created,
1717
      used for device cache data
1718
  @type on_primary: boolean
1719
  @param on_primary:  indicates if it is the primary node or not
1720
  @type info: string
1721
  @param info: string that will be sent to the physical device
1722
      creation, used for example to set (LVM) tags on LVs
1723
  @type excl_stor: boolean
1724
  @param excl_stor: Whether exclusive_storage is active
1725

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

1730
  """
1731
  # TODO: remove the obsolete "size" argument
1732
  # pylint: disable=W0613
1733
  clist = []
1734
  if disk.children:
1735
    for child in disk.children:
1736
      try:
1737
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1738
      except errors.BlockDeviceError, err:
1739
        _Fail("Can't assemble device %s: %s", child, err)
1740
      if on_primary or disk.AssembleOnSecondary():
1741
        # we need the children open in case the device itself has to
1742
        # be assembled
1743
        try:
1744
          # pylint: disable=E1103
1745
          crdev.Open()
1746
        except errors.BlockDeviceError, err:
1747
          _Fail("Can't make child '%s' read-write: %s", child, err)
1748
      clist.append(crdev)
1749

    
1750
  try:
1751
    device = bdev.Create(disk, clist, excl_stor)
1752
  except errors.BlockDeviceError, err:
1753
    _Fail("Can't create block device: %s", err)
1754

    
1755
  if on_primary or disk.AssembleOnSecondary():
1756
    try:
1757
      device.Assemble()
1758
    except errors.BlockDeviceError, err:
1759
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1760
    if on_primary or disk.OpenOnSecondary():
1761
      try:
1762
        device.Open(force=True)
1763
      except errors.BlockDeviceError, err:
1764
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1765
    DevCacheManager.UpdateCache(device.dev_path, owner,
1766
                                on_primary, disk.iv_name)
1767

    
1768
  device.SetInfo(info)
1769

    
1770
  return device.unique_id
1771

    
1772

    
1773
def _WipeDevice(path, offset, size):
1774
  """This function actually wipes the device.
1775

1776
  @param path: The path to the device to wipe
1777
  @param offset: The offset in MiB in the file
1778
  @param size: The size in MiB to write
1779

1780
  """
1781
  # Internal sizes are always in Mebibytes; if the following "dd" command
1782
  # should use a different block size the offset and size given to this
1783
  # function must be adjusted accordingly before being passed to "dd".
1784
  block_size = 1024 * 1024
1785

    
1786
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1787
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
1788
         "count=%d" % size]
1789
  result = utils.RunCmd(cmd)
1790

    
1791
  if result.failed:
1792
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1793
          result.fail_reason, result.output)
1794

    
1795

    
1796
def BlockdevWipe(disk, offset, size):
1797
  """Wipes a block device.
1798

1799
  @type disk: L{objects.Disk}
1800
  @param disk: the disk object we want to wipe
1801
  @type offset: int
1802
  @param offset: The offset in MiB in the file
1803
  @type size: int
1804
  @param size: The size in MiB to write
1805

1806
  """
1807
  try:
1808
    rdev = _RecursiveFindBD(disk)
1809
  except errors.BlockDeviceError:
1810
    rdev = None
1811

    
1812
  if not rdev:
1813
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1814

    
1815
  # Do cross verify some of the parameters
1816
  if offset < 0:
1817
    _Fail("Negative offset")
1818
  if size < 0:
1819
    _Fail("Negative size")
1820
  if offset > rdev.size:
1821
    _Fail("Offset is bigger than device size")
1822
  if (offset + size) > rdev.size:
1823
    _Fail("The provided offset and size to wipe is bigger than device size")
1824

    
1825
  _WipeDevice(rdev.dev_path, offset, size)
1826

    
1827

    
1828
def BlockdevPauseResumeSync(disks, pause):
1829
  """Pause or resume the sync of the block device.
1830

1831
  @type disks: list of L{objects.Disk}
1832
  @param disks: the disks object we want to pause/resume
1833
  @type pause: bool
1834
  @param pause: Wheater to pause or resume
1835

1836
  """
1837
  success = []
1838
  for disk in disks:
1839
    try:
1840
      rdev = _RecursiveFindBD(disk)
1841
    except errors.BlockDeviceError:
1842
      rdev = None
1843

    
1844
    if not rdev:
1845
      success.append((False, ("Cannot change sync for device %s:"
1846
                              " device not found" % disk.iv_name)))
1847
      continue
1848

    
1849
    result = rdev.PauseResumeSync(pause)
1850

    
1851
    if result:
1852
      success.append((result, None))
1853
    else:
1854
      if pause:
1855
        msg = "Pause"
1856
      else:
1857
        msg = "Resume"
1858
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1859

    
1860
  return success
1861

    
1862

    
1863
def BlockdevRemove(disk):
1864
  """Remove a block device.
1865

1866
  @note: This is intended to be called recursively.
1867

1868
  @type disk: L{objects.Disk}
1869
  @param disk: the disk object we should remove
1870
  @rtype: boolean
1871
  @return: the success of the operation
1872

1873
  """
1874
  msgs = []
1875
  try:
1876
    rdev = _RecursiveFindBD(disk)
1877
  except errors.BlockDeviceError, err:
1878
    # probably can't attach
1879
    logging.info("Can't attach to device %s in remove", disk)
1880
    rdev = None
1881
  if rdev is not None:
1882
    r_path = rdev.dev_path
1883
    try:
1884
      rdev.Remove()
1885
    except errors.BlockDeviceError, err:
1886
      msgs.append(str(err))
1887
    if not msgs:
1888
      DevCacheManager.RemoveCache(r_path)
1889

    
1890
  if disk.children:
1891
    for child in disk.children:
1892
      try:
1893
        BlockdevRemove(child)
1894
      except RPCFail, err:
1895
        msgs.append(str(err))
1896

    
1897
  if msgs:
1898
    _Fail("; ".join(msgs))
1899

    
1900

    
1901
def _RecursiveAssembleBD(disk, owner, as_primary):
1902
  """Activate a block device for an instance.
1903

1904
  This is run on the primary and secondary nodes for an instance.
1905

1906
  @note: this function is called recursively.
1907

1908
  @type disk: L{objects.Disk}
1909
  @param disk: the disk we try to assemble
1910
  @type owner: str
1911
  @param owner: the name of the instance which owns the disk
1912
  @type as_primary: boolean
1913
  @param as_primary: if we should make the block device
1914
      read/write
1915

1916
  @return: the assembled device or None (in case no device
1917
      was assembled)
1918
  @raise errors.BlockDeviceError: in case there is an error
1919
      during the activation of the children or the device
1920
      itself
1921

1922
  """
1923
  children = []
1924
  if disk.children:
1925
    mcn = disk.ChildrenNeeded()
1926
    if mcn == -1:
1927
      mcn = 0 # max number of Nones allowed
1928
    else:
1929
      mcn = len(disk.children) - mcn # max number of Nones
1930
    for chld_disk in disk.children:
1931
      try:
1932
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1933
      except errors.BlockDeviceError, err:
1934
        if children.count(None) >= mcn:
1935
          raise
1936
        cdev = None
1937
        logging.error("Error in child activation (but continuing): %s",
1938
                      str(err))
1939
      children.append(cdev)
1940

    
1941
  if as_primary or disk.AssembleOnSecondary():
1942
    r_dev = bdev.Assemble(disk, children)
1943
    result = r_dev
1944
    if as_primary or disk.OpenOnSecondary():
1945
      r_dev.Open()
1946
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1947
                                as_primary, disk.iv_name)
1948

    
1949
  else:
1950
    result = True
1951
  return result
1952

    
1953

    
1954
def BlockdevAssemble(disk, owner, as_primary, idx):
1955
  """Activate a block device for an instance.
1956

1957
  This is a wrapper over _RecursiveAssembleBD.
1958

1959
  @rtype: str or boolean
1960
  @return: a C{/dev/...} path for primary nodes, and
1961
      C{True} for secondary nodes
1962

1963
  """
1964
  try:
1965
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1966
    if isinstance(result, BlockDev):
1967
      # pylint: disable=E1103
1968
      result = result.dev_path
1969
      if as_primary:
1970
        _SymlinkBlockDev(owner, result, idx)
1971
  except errors.BlockDeviceError, err:
1972
    _Fail("Error while assembling disk: %s", err, exc=True)
1973
  except OSError, err:
1974
    _Fail("Error while symlinking disk: %s", err, exc=True)
1975

    
1976
  return result
1977

    
1978

    
1979
def BlockdevShutdown(disk):
1980
  """Shut down a block device.
1981

1982
  First, if the device is assembled (Attach() is successful), then
1983
  the device is shutdown. Then the children of the device are
1984
  shutdown.
1985

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

1990
  @type disk: L{objects.Disk}
1991
  @param disk: the description of the disk we should
1992
      shutdown
1993
  @rtype: None
1994

1995
  """
1996
  msgs = []
1997
  r_dev = _RecursiveFindBD(disk)
1998
  if r_dev is not None:
1999
    r_path = r_dev.dev_path
2000
    try:
2001
      r_dev.Shutdown()
2002
      DevCacheManager.RemoveCache(r_path)
2003
    except errors.BlockDeviceError, err:
2004
      msgs.append(str(err))
2005

    
2006
  if disk.children:
2007
    for child in disk.children:
2008
      try:
2009
        BlockdevShutdown(child)
2010
      except RPCFail, err:
2011
        msgs.append(str(err))
2012

    
2013
  if msgs:
2014
    _Fail("; ".join(msgs))
2015

    
2016

    
2017
def BlockdevAddchildren(parent_cdev, new_cdevs):
2018
  """Extend a mirrored block device.
2019

2020
  @type parent_cdev: L{objects.Disk}
2021
  @param parent_cdev: the disk to which we should add children
2022
  @type new_cdevs: list of L{objects.Disk}
2023
  @param new_cdevs: the list of children which we should add
2024
  @rtype: None
2025

2026
  """
2027
  parent_bdev = _RecursiveFindBD(parent_cdev)
2028
  if parent_bdev is None:
2029
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
2030
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
2031
  if new_bdevs.count(None) > 0:
2032
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
2033
  parent_bdev.AddChildren(new_bdevs)
2034

    
2035

    
2036
def BlockdevRemovechildren(parent_cdev, new_cdevs):
2037
  """Shrink a mirrored block device.
2038

2039
  @type parent_cdev: L{objects.Disk}
2040
  @param parent_cdev: the disk from which we should remove children
2041
  @type new_cdevs: list of L{objects.Disk}
2042
  @param new_cdevs: the list of children which we should remove
2043
  @rtype: None
2044

2045
  """
2046
  parent_bdev = _RecursiveFindBD(parent_cdev)
2047
  if parent_bdev is None:
2048
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
2049
  devs = []
2050
  for disk in new_cdevs:
2051
    rpath = disk.StaticDevPath()
2052
    if rpath is None:
2053
      bd = _RecursiveFindBD(disk)
2054
      if bd is None:
2055
        _Fail("Can't find device %s while removing children", disk)
2056
      else:
2057
        devs.append(bd.dev_path)
2058
    else:
2059
      if not utils.IsNormAbsPath(rpath):
2060
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
2061
      devs.append(rpath)
2062
  parent_bdev.RemoveChildren(devs)
2063

    
2064

    
2065
def BlockdevGetmirrorstatus(disks):
2066
  """Get the mirroring status of a list of devices.
2067

2068
  @type disks: list of L{objects.Disk}
2069
  @param disks: the list of disks which we should query
2070
  @rtype: disk
2071
  @return: List of L{objects.BlockDevStatus}, one for each disk
2072
  @raise errors.BlockDeviceError: if any of the disks cannot be
2073
      found
2074

2075
  """
2076
  stats = []
2077
  for dsk in disks:
2078
    rbd = _RecursiveFindBD(dsk)
2079
    if rbd is None:
2080
      _Fail("Can't find device %s", dsk)
2081

    
2082
    stats.append(rbd.CombinedSyncStatus())
2083

    
2084
  return stats
2085

    
2086

    
2087
def BlockdevGetmirrorstatusMulti(disks):
2088
  """Get the mirroring status of a list of devices.
2089

2090
  @type disks: list of L{objects.Disk}
2091
  @param disks: the list of disks which we should query
2092
  @rtype: disk
2093
  @return: List of tuples, (bool, status), one for each disk; bool denotes
2094
    success/failure, status is L{objects.BlockDevStatus} on success, string
2095
    otherwise
2096

2097
  """
2098
  result = []
2099
  for disk in disks:
2100
    try:
2101
      rbd = _RecursiveFindBD(disk)
2102
      if rbd is None:
2103
        result.append((False, "Can't find device %s" % disk))
2104
        continue
2105

    
2106
      status = rbd.CombinedSyncStatus()
2107
    except errors.BlockDeviceError, err:
2108
      logging.exception("Error while getting disk status")
2109
      result.append((False, str(err)))
2110
    else:
2111
      result.append((True, status))
2112

    
2113
  assert len(disks) == len(result)
2114

    
2115
  return result
2116

    
2117

    
2118
def _RecursiveFindBD(disk):
2119
  """Check if a device is activated.
2120

2121
  If so, return information about the real device.
2122

2123
  @type disk: L{objects.Disk}
2124
  @param disk: the disk object we need to find
2125

2126
  @return: None if the device can't be found,
2127
      otherwise the device instance
2128

2129
  """
2130
  children = []
2131
  if disk.children:
2132
    for chdisk in disk.children:
2133
      children.append(_RecursiveFindBD(chdisk))
2134

    
2135
  return bdev.FindDevice(disk, children)
2136

    
2137

    
2138
def _OpenRealBD(disk):
2139
  """Opens the underlying block device of a disk.
2140

2141
  @type disk: L{objects.Disk}
2142
  @param disk: the disk object we want to open
2143

2144
  """
2145
  real_disk = _RecursiveFindBD(disk)
2146
  if real_disk is None:
2147
    _Fail("Block device '%s' is not set up", disk)
2148

    
2149
  real_disk.Open()
2150

    
2151
  return real_disk
2152

    
2153

    
2154
def BlockdevFind(disk):
2155
  """Check if a device is activated.
2156

2157
  If it is, return information about the real device.
2158

2159
  @type disk: L{objects.Disk}
2160
  @param disk: the disk to find
2161
  @rtype: None or objects.BlockDevStatus
2162
  @return: None if the disk cannot be found, otherwise a the current
2163
           information
2164

2165
  """
2166
  try:
2167
    rbd = _RecursiveFindBD(disk)
2168
  except errors.BlockDeviceError, err:
2169
    _Fail("Failed to find device: %s", err, exc=True)
2170

    
2171
  if rbd is None:
2172
    return None
2173

    
2174
  return rbd.GetSyncStatus()
2175

    
2176

    
2177
def BlockdevGetdimensions(disks):
2178
  """Computes the size of the given disks.
2179

2180
  If a disk is not found, returns None instead.
2181

2182
  @type disks: list of L{objects.Disk}
2183
  @param disks: the list of disk to compute the size for
2184
  @rtype: list
2185
  @return: list with elements None if the disk cannot be found,
2186
      otherwise the pair (size, spindles), where spindles is None if the
2187
      device doesn't support that
2188

2189
  """
2190
  result = []
2191
  for cf in disks:
2192
    try:
2193
      rbd = _RecursiveFindBD(cf)
2194
    except errors.BlockDeviceError:
2195
      result.append(None)
2196
      continue
2197
    if rbd is None:
2198
      result.append(None)
2199
    else:
2200
      result.append(rbd.GetActualDimensions())
2201
  return result
2202

    
2203

    
2204
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2205
  """Export a block device to a remote node.
2206

2207
  @type disk: L{objects.Disk}
2208
  @param disk: the description of the disk to export
2209
  @type dest_node: str
2210
  @param dest_node: the destination node to export to
2211
  @type dest_path: str
2212
  @param dest_path: the destination path on the target node
2213
  @type cluster_name: str
2214
  @param cluster_name: the cluster name, needed for SSH hostalias
2215
  @rtype: None
2216

2217
  """
2218
  real_disk = _OpenRealBD(disk)
2219

    
2220
  # the block size on the read dd is 1MiB to match our units
2221
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2222
                               "dd if=%s bs=1048576 count=%s",
2223
                               real_disk.dev_path, str(disk.size))
2224

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

    
2234
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2235
                                                   constants.SSH_LOGIN_USER,
2236
                                                   destcmd)
2237

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

    
2241
  result = utils.RunCmd(["bash", "-c", command])
2242

    
2243
  if result.failed:
2244
    _Fail("Disk copy command '%s' returned error: %s"
2245
          " output: %s", command, result.fail_reason, result.output)
2246

    
2247

    
2248
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2249
  """Write a file to the filesystem.
2250

2251
  This allows the master to overwrite(!) a file. It will only perform
2252
  the operation if the file belongs to a list of configuration files.
2253

2254
  @type file_name: str
2255
  @param file_name: the target file name
2256
  @type data: str
2257
  @param data: the new contents of the file
2258
  @type mode: int
2259
  @param mode: the mode to give the file (can be None)
2260
  @type uid: string
2261
  @param uid: the owner of the file
2262
  @type gid: string
2263
  @param gid: the group of the file
2264
  @type atime: float
2265
  @param atime: the atime to set on the file (can be None)
2266
  @type mtime: float
2267
  @param mtime: the mtime to set on the file (can be None)
2268
  @rtype: None
2269

2270
  """
2271
  file_name = vcluster.LocalizeVirtualPath(file_name)
2272

    
2273
  if not os.path.isabs(file_name):
2274
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2275

    
2276
  if file_name not in _ALLOWED_UPLOAD_FILES:
2277
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2278
          file_name)
2279

    
2280
  raw_data = _Decompress(data)
2281

    
2282
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2283
    _Fail("Invalid username/groupname type")
2284

    
2285
  getents = runtime.GetEnts()
2286
  uid = getents.LookupUser(uid)
2287
  gid = getents.LookupGroup(gid)
2288

    
2289
  utils.SafeWriteFile(file_name, None,
2290
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2291
                      atime=atime, mtime=mtime)
2292

    
2293

    
2294
def RunOob(oob_program, command, node, timeout):
2295
  """Executes oob_program with given command on given node.
2296

2297
  @param oob_program: The path to the executable oob_program
2298
  @param command: The command to invoke on oob_program
2299
  @param node: The node given as an argument to the program
2300
  @param timeout: Timeout after which we kill the oob program
2301

2302
  @return: stdout
2303
  @raise RPCFail: If execution fails for some reason
2304

2305
  """
2306
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2307

    
2308
  if result.failed:
2309
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2310
          result.fail_reason, result.output)
2311

    
2312
  return result.stdout
2313

    
2314

    
2315
def _OSOndiskAPIVersion(os_dir):
2316
  """Compute and return the API version of a given OS.
2317

2318
  This function will try to read the API version of the OS residing in
2319
  the 'os_dir' directory.
2320

2321
  @type os_dir: str
2322
  @param os_dir: the directory in which we should look for the OS
2323
  @rtype: tuple
2324
  @return: tuple (status, data) with status denoting the validity and
2325
      data holding either the vaid versions or an error message
2326

2327
  """
2328
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2329

    
2330
  try:
2331
    st = os.stat(api_file)
2332
  except EnvironmentError, err:
2333
    return False, ("Required file '%s' not found under path %s: %s" %
2334
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2335

    
2336
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2337
    return False, ("File '%s' in %s is not a regular file" %
2338
                   (constants.OS_API_FILE, os_dir))
2339

    
2340
  try:
2341
    api_versions = utils.ReadFile(api_file).splitlines()
2342
  except EnvironmentError, err:
2343
    return False, ("Error while reading the API version file at %s: %s" %
2344
                   (api_file, utils.ErrnoOrStr(err)))
2345

    
2346
  try:
2347
    api_versions = [int(version.strip()) for version in api_versions]
2348
  except (TypeError, ValueError), err:
2349
    return False, ("API version(s) can't be converted to integer: %s" %
2350
                   str(err))
2351

    
2352
  return True, api_versions
2353

    
2354

    
2355
def DiagnoseOS(top_dirs=None):
2356
  """Compute the validity for all OSes.
2357

2358
  @type top_dirs: list
2359
  @param top_dirs: the list of directories in which to
2360
      search (if not given defaults to
2361
      L{pathutils.OS_SEARCH_PATH})
2362
  @rtype: list of L{objects.OS}
2363
  @return: a list of tuples (name, path, status, diagnose, variants,
2364
      parameters, api_version) for all (potential) OSes under all
2365
      search paths, where:
2366
          - name is the (potential) OS name
2367
          - path is the full path to the OS
2368
          - status True/False is the validity of the OS
2369
          - diagnose is the error message for an invalid OS, otherwise empty
2370
          - variants is a list of supported OS variants, if any
2371
          - parameters is a list of (name, help) parameters, if any
2372
          - api_version is a list of support OS API versions
2373

2374
  """
2375
  if top_dirs is None:
2376
    top_dirs = pathutils.OS_SEARCH_PATH
2377

    
2378
  result = []
2379
  for dir_name in top_dirs:
2380
    if os.path.isdir(dir_name):
2381
      try:
2382
        f_names = utils.ListVisibleFiles(dir_name)
2383
      except EnvironmentError, err:
2384
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2385
        break
2386
      for name in f_names:
2387
        os_path = utils.PathJoin(dir_name, name)
2388
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2389
        if status:
2390
          diagnose = ""
2391
          variants = os_inst.supported_variants
2392
          parameters = os_inst.supported_parameters
2393
          api_versions = os_inst.api_versions
2394
        else:
2395
          diagnose = os_inst
2396
          variants = parameters = api_versions = []
2397
        result.append((name, os_path, status, diagnose, variants,
2398
                       parameters, api_versions))
2399

    
2400
  return result
2401

    
2402

    
2403
def _TryOSFromDisk(name, base_dir=None):
2404
  """Create an OS instance from disk.
2405

2406
  This function will return an OS instance if the given name is a
2407
  valid OS name.
2408

2409
  @type base_dir: string
2410
  @keyword base_dir: Base directory containing OS installations.
2411
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2412
  @rtype: tuple
2413
  @return: success and either the OS instance if we find a valid one,
2414
      or error message
2415

2416
  """
2417
  if base_dir is None:
2418
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2419
  else:
2420
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2421

    
2422
  if os_dir is None:
2423
    return False, "Directory for OS %s not found in search path" % name
2424

    
2425
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2426
  if not status:
2427
    # push the error up
2428
    return status, api_versions
2429

    
2430
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2431
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2432
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2433

    
2434
  # OS Files dictionary, we will populate it with the absolute path
2435
  # names; if the value is True, then it is a required file, otherwise
2436
  # an optional one
2437
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2438

    
2439
  if max(api_versions) >= constants.OS_API_V15:
2440
    os_files[constants.OS_VARIANTS_FILE] = False
2441

    
2442
  if max(api_versions) >= constants.OS_API_V20:
2443
    os_files[constants.OS_PARAMETERS_FILE] = True
2444
  else:
2445
    del os_files[constants.OS_SCRIPT_VERIFY]
2446

    
2447
  for (filename, required) in os_files.items():
2448
    os_files[filename] = utils.PathJoin(os_dir, filename)
2449

    
2450
    try:
2451
      st = os.stat(os_files[filename])
2452
    except EnvironmentError, err:
2453
      if err.errno == errno.ENOENT and not required:
2454
        del os_files[filename]
2455
        continue
2456
      return False, ("File '%s' under path '%s' is missing (%s)" %
2457
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2458

    
2459
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2460
      return False, ("File '%s' under path '%s' is not a regular file" %
2461
                     (filename, os_dir))
2462

    
2463
    if filename in constants.OS_SCRIPTS:
2464
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2465
        return False, ("File '%s' under path '%s' is not executable" %
2466
                       (filename, os_dir))
2467

    
2468
  variants = []
2469
  if constants.OS_VARIANTS_FILE in os_files:
2470
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2471
    try:
2472
      variants = \
2473
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2474
    except EnvironmentError, err:
2475
      # we accept missing files, but not other errors
2476
      if err.errno != errno.ENOENT:
2477
        return False, ("Error while reading the OS variants file at %s: %s" %
2478
                       (variants_file, utils.ErrnoOrStr(err)))
2479

    
2480
  parameters = []
2481
  if constants.OS_PARAMETERS_FILE in os_files:
2482
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2483
    try:
2484
      parameters = utils.ReadFile(parameters_file).splitlines()
2485
    except EnvironmentError, err:
2486
      return False, ("Error while reading the OS parameters file at %s: %s" %
2487
                     (parameters_file, utils.ErrnoOrStr(err)))
2488
    parameters = [v.split(None, 1) for v in parameters]
2489

    
2490
  os_obj = objects.OS(name=name, path=os_dir,
2491
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2492
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2493
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2494
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2495
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2496
                                                 None),
2497
                      supported_variants=variants,
2498
                      supported_parameters=parameters,
2499
                      api_versions=api_versions)
2500
  return True, os_obj
2501

    
2502

    
2503
def OSFromDisk(name, base_dir=None):
2504
  """Create an OS instance from disk.
2505

2506
  This function will return an OS instance if the given name is a
2507
  valid OS name. Otherwise, it will raise an appropriate
2508
  L{RPCFail} exception, detailing why this is not a valid OS.
2509

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

2513
  @type base_dir: string
2514
  @keyword base_dir: Base directory containing OS installations.
2515
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2516
  @rtype: L{objects.OS}
2517
  @return: the OS instance if we find a valid one
2518
  @raise RPCFail: if we don't find a valid OS
2519

2520
  """
2521
  name_only = objects.OS.GetName(name)
2522
  status, payload = _TryOSFromDisk(name_only, base_dir)
2523

    
2524
  if not status:
2525
    _Fail(payload)
2526

    
2527
  return payload
2528

    
2529

    
2530
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2531
  """Calculate the basic environment for an os script.
2532

2533
  @type os_name: str
2534
  @param os_name: full operating system name (including variant)
2535
  @type inst_os: L{objects.OS}
2536
  @param inst_os: operating system for which the environment is being built
2537
  @type os_params: dict
2538
  @param os_params: the OS parameters
2539
  @type debug: integer
2540
  @param debug: debug level (0 or 1, for OS Api 10)
2541
  @rtype: dict
2542
  @return: dict of environment variables
2543
  @raise errors.BlockDeviceError: if the block device
2544
      cannot be found
2545

2546
  """
2547
  result = {}
2548
  api_version = \
2549
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2550
  result["OS_API_VERSION"] = "%d" % api_version
2551
  result["OS_NAME"] = inst_os.name
2552
  result["DEBUG_LEVEL"] = "%d" % debug
2553

    
2554
  # OS variants
2555
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2556
    variant = objects.OS.GetVariant(os_name)
2557
    if not variant:
2558
      variant = inst_os.supported_variants[0]
2559
  else:
2560
    variant = ""
2561
  result["OS_VARIANT"] = variant
2562

    
2563
  # OS params
2564
  for pname, pvalue in os_params.items():
2565
    result["OSP_%s" % pname.upper()] = pvalue
2566

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

    
2572
  return result
2573

    
2574

    
2575
def OSEnvironment(instance, inst_os, debug=0):
2576
  """Calculate the environment for an os script.
2577

2578
  @type instance: L{objects.Instance}
2579
  @param instance: target instance for the os script run
2580
  @type inst_os: L{objects.OS}
2581
  @param inst_os: operating system for which the environment is being built
2582
  @type debug: integer
2583
  @param debug: debug level (0 or 1, for OS Api 10)
2584
  @rtype: dict
2585
  @return: dict of environment variables
2586
  @raise errors.BlockDeviceError: if the block device
2587
      cannot be found
2588

2589
  """
2590
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2591

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

    
2595
  result["HYPERVISOR"] = instance.hypervisor
2596
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2597
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2598
  result["INSTANCE_SECONDARY_NODES"] = \
2599
      ("%s" % " ".join(instance.secondary_nodes))
2600

    
2601
  # Disks
2602
  for idx, disk in enumerate(instance.disks):
2603
    real_disk = _OpenRealBD(disk)
2604
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2605
    result["DISK_%d_ACCESS" % idx] = disk.mode
2606
    if constants.HV_DISK_TYPE in instance.hvparams:
2607
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2608
        instance.hvparams[constants.HV_DISK_TYPE]
2609
    if disk.dev_type in constants.LDS_BLOCK:
2610
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2611
    elif disk.dev_type == constants.LD_FILE:
2612
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2613
        "file:%s" % disk.physical_id[0]
2614

    
2615
  # NICs
2616
  for idx, nic in enumerate(instance.nics):
2617
    result["NIC_%d_MAC" % idx] = nic.mac
2618
    if nic.ip:
2619
      result["NIC_%d_IP" % idx] = nic.ip
2620
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2621
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2622
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2623
    if nic.nicparams[constants.NIC_LINK]:
2624
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2625
    if nic.netinfo:
2626
      nobj = objects.Network.FromDict(nic.netinfo)
2627
      result.update(nobj.HooksDict("NIC_%d_" % idx))
2628
    if constants.HV_NIC_TYPE in instance.hvparams:
2629
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2630
        instance.hvparams[constants.HV_NIC_TYPE]
2631

    
2632
  # HV/BE params
2633
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2634
    for key, value in source.items():
2635
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2636

    
2637
  return result
2638

    
2639

    
2640
def DiagnoseExtStorage(top_dirs=None):
2641
  """Compute the validity for all ExtStorage Providers.
2642

2643
  @type top_dirs: list
2644
  @param top_dirs: the list of directories in which to
2645
      search (if not given defaults to
2646
      L{pathutils.ES_SEARCH_PATH})
2647
  @rtype: list of L{objects.ExtStorage}
2648
  @return: a list of tuples (name, path, status, diagnose, parameters)
2649
      for all (potential) ExtStorage Providers under all
2650
      search paths, where:
2651
          - name is the (potential) ExtStorage Provider
2652
          - path is the full path to the ExtStorage Provider
2653
          - status True/False is the validity of the ExtStorage Provider
2654
          - diagnose is the error message for an invalid ExtStorage Provider,
2655
            otherwise empty
2656
          - parameters is a list of (name, help) parameters, if any
2657

2658
  """
2659
  if top_dirs is None:
2660
    top_dirs = pathutils.ES_SEARCH_PATH
2661

    
2662
  result = []
2663
  for dir_name in top_dirs:
2664
    if os.path.isdir(dir_name):
2665
      try:
2666
        f_names = utils.ListVisibleFiles(dir_name)
2667
      except EnvironmentError, err:
2668
        logging.exception("Can't list the ExtStorage directory %s: %s",
2669
                          dir_name, err)
2670
        break
2671
      for name in f_names:
2672
        es_path = utils.PathJoin(dir_name, name)
2673
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2674
        if status:
2675
          diagnose = ""
2676
          parameters = es_inst.supported_parameters
2677
        else:
2678
          diagnose = es_inst
2679
          parameters = []
2680
        result.append((name, es_path, status, diagnose, parameters))
2681

    
2682
  return result
2683

    
2684

    
2685
def BlockdevGrow(disk, amount, dryrun, backingstore):
2686
  """Grow a stack of block devices.
2687

2688
  This function is called recursively, with the childrens being the
2689
  first ones to resize.
2690

2691
  @type disk: L{objects.Disk}
2692
  @param disk: the disk to be grown
2693
  @type amount: integer
2694
  @param amount: the amount (in mebibytes) to grow with
2695
  @type dryrun: boolean
2696
  @param dryrun: whether to execute the operation in simulation mode
2697
      only, without actually increasing the size
2698
  @param backingstore: whether to execute the operation on backing storage
2699
      only, or on "logical" storage only; e.g. DRBD is logical storage,
2700
      whereas LVM, file, RBD are backing storage
2701
  @rtype: (status, result)
2702
  @return: a tuple with the status of the operation (True/False), and
2703
      the errors message if status is False
2704

2705
  """
2706
  r_dev = _RecursiveFindBD(disk)
2707
  if r_dev is None:
2708
    _Fail("Cannot find block device %s", disk)
2709

    
2710
  try:
2711
    r_dev.Grow(amount, dryrun, backingstore)
2712
  except errors.BlockDeviceError, err:
2713
    _Fail("Failed to grow block device: %s", err, exc=True)
2714

    
2715

    
2716
def BlockdevSnapshot(disk):
2717
  """Create a snapshot copy of a block device.
2718

2719
  This function is called recursively, and the snapshot is actually created
2720
  just for the leaf lvm backend device.
2721

2722
  @type disk: L{objects.Disk}
2723
  @param disk: the disk to be snapshotted
2724
  @rtype: string
2725
  @return: snapshot disk ID as (vg, lv)
2726

2727
  """
2728
  if disk.dev_type == constants.LD_DRBD8:
2729
    if not disk.children:
2730
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2731
            disk.unique_id)
2732
    return BlockdevSnapshot(disk.children[0])
2733
  elif disk.dev_type == constants.LD_LV:
2734
    r_dev = _RecursiveFindBD(disk)
2735
    if r_dev is not None:
2736
      # FIXME: choose a saner value for the snapshot size
2737
      # let's stay on the safe side and ask for the full size, for now
2738
      return r_dev.Snapshot(disk.size)
2739
    else:
2740
      _Fail("Cannot find block device %s", disk)
2741
  else:
2742
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2743
          disk.unique_id, disk.dev_type)
2744

    
2745

    
2746
def BlockdevSetInfo(disk, info):
2747
  """Sets 'metadata' information on block devices.
2748

2749
  This function sets 'info' metadata on block devices. Initial
2750
  information is set at device creation; this function should be used
2751
  for example after renames.
2752

2753
  @type disk: L{objects.Disk}
2754
  @param disk: the disk to be grown
2755
  @type info: string
2756
  @param info: new 'info' metadata
2757
  @rtype: (status, result)
2758
  @return: a tuple with the status of the operation (True/False), and
2759
      the errors message if status is False
2760

2761
  """
2762
  r_dev = _RecursiveFindBD(disk)
2763
  if r_dev is None:
2764
    _Fail("Cannot find block device %s", disk)
2765

    
2766
  try:
2767
    r_dev.SetInfo(info)
2768
  except errors.BlockDeviceError, err:
2769
    _Fail("Failed to set information on block device: %s", err, exc=True)
2770

    
2771

    
2772
def FinalizeExport(instance, snap_disks):
2773
  """Write out the export configuration information.
2774

2775
  @type instance: L{objects.Instance}
2776
  @param instance: the instance which we export, used for
2777
      saving configuration
2778
  @type snap_disks: list of L{objects.Disk}
2779
  @param snap_disks: list of snapshot block devices, which
2780
      will be used to get the actual name of the dump file
2781

2782
  @rtype: None
2783

2784
  """
2785
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
2786
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
2787

    
2788
  config = objects.SerializableConfigParser()
2789

    
2790
  config.add_section(constants.INISECT_EXP)
2791
  config.set(constants.INISECT_EXP, "version", "0")
2792
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2793
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2794
  config.set(constants.INISECT_EXP, "os", instance.os)
2795
  config.set(constants.INISECT_EXP, "compression", "none")
2796

    
2797
  config.add_section(constants.INISECT_INS)
2798
  config.set(constants.INISECT_INS, "name", instance.name)
2799
  config.set(constants.INISECT_INS, "maxmem", "%d" %
2800
             instance.beparams[constants.BE_MAXMEM])
2801
  config.set(constants.INISECT_INS, "minmem", "%d" %
2802
             instance.beparams[constants.BE_MINMEM])
2803
  # "memory" is deprecated, but useful for exporting to old ganeti versions
2804
  config.set(constants.INISECT_INS, "memory", "%d" %
2805
             instance.beparams[constants.BE_MAXMEM])
2806
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2807
             instance.beparams[constants.BE_VCPUS])
2808
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2809
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2810
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2811

    
2812
  nic_total = 0
2813
  for nic_count, nic in enumerate(instance.nics):
2814
    nic_total += 1
2815
    config.set(constants.INISECT_INS, "nic%d_mac" %
2816
               nic_count, "%s" % nic.mac)
2817
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2818
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
2819
               "%s" % nic.network)
2820
    for param in constants.NICS_PARAMETER_TYPES:
2821
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2822
                 "%s" % nic.nicparams.get(param, None))
2823
  # TODO: redundant: on load can read nics until it doesn't exist
2824
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2825

    
2826
  disk_total = 0
2827
  for disk_count, disk in enumerate(snap_disks):
2828
    if disk:
2829
      disk_total += 1
2830
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2831
                 ("%s" % disk.iv_name))
2832
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2833
                 ("%s" % disk.physical_id[1]))
2834
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2835
                 ("%d" % disk.size))
2836

    
2837
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2838

    
2839
  # New-style hypervisor/backend parameters
2840

    
2841
  config.add_section(constants.INISECT_HYP)
2842
  for name, value in instance.hvparams.items():
2843
    if name not in constants.HVC_GLOBALS:
2844
      config.set(constants.INISECT_HYP, name, str(value))
2845

    
2846
  config.add_section(constants.INISECT_BEP)
2847
  for name, value in instance.beparams.items():
2848
    config.set(constants.INISECT_BEP, name, str(value))
2849

    
2850
  config.add_section(constants.INISECT_OSP)
2851
  for name, value in instance.osparams.items():
2852
    config.set(constants.INISECT_OSP, name, str(value))
2853

    
2854
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2855
                  data=config.Dumps())
2856
  shutil.rmtree(finaldestdir, ignore_errors=True)
2857
  shutil.move(destdir, finaldestdir)
2858

    
2859

    
2860
def ExportInfo(dest):
2861
  """Get export configuration information.
2862

2863
  @type dest: str
2864
  @param dest: directory containing the export
2865

2866
  @rtype: L{objects.SerializableConfigParser}
2867
  @return: a serializable config file containing the
2868
      export info
2869

2870
  """
2871
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2872

    
2873
  config = objects.SerializableConfigParser()
2874
  config.read(cff)
2875

    
2876
  if (not config.has_section(constants.INISECT_EXP) or
2877
      not config.has_section(constants.INISECT_INS)):
2878
    _Fail("Export info file doesn't have the required fields")
2879

    
2880
  return config.Dumps()
2881

    
2882

    
2883
def ListExports():
2884
  """Return a list of exports currently available on this machine.
2885

2886
  @rtype: list
2887
  @return: list of the exports
2888

2889
  """
2890
  if os.path.isdir(pathutils.EXPORT_DIR):
2891
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
2892
  else:
2893
    _Fail("No exports directory")
2894

    
2895

    
2896
def RemoveExport(export):
2897
  """Remove an existing export from the node.
2898

2899
  @type export: str
2900
  @param export: the name of the export to remove
2901
  @rtype: None
2902

2903
  """
2904
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
2905

    
2906
  try:
2907
    shutil.rmtree(target)
2908
  except EnvironmentError, err:
2909
    _Fail("Error while removing the export: %s", err, exc=True)
2910

    
2911

    
2912
def BlockdevRename(devlist):
2913
  """Rename a list of block devices.
2914

2915
  @type devlist: list of tuples
2916
  @param devlist: list of tuples of the form  (disk,
2917
      new_logical_id, new_physical_id); disk is an
2918
      L{objects.Disk} object describing the current disk,
2919
      and new logical_id/physical_id is the name we
2920
      rename it to
2921
  @rtype: boolean
2922
  @return: True if all renames succeeded, False otherwise
2923

2924
  """
2925
  msgs = []
2926
  result = True
2927
  for disk, unique_id in devlist:
2928
    dev = _RecursiveFindBD(disk)
2929
    if dev is None:
2930
      msgs.append("Can't find device %s in rename" % str(disk))
2931
      result = False
2932
      continue
2933
    try:
2934
      old_rpath = dev.dev_path
2935
      dev.Rename(unique_id)
2936
      new_rpath = dev.dev_path
2937
      if old_rpath != new_rpath:
2938
        DevCacheManager.RemoveCache(old_rpath)
2939
        # FIXME: we should add the new cache information here, like:
2940
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2941
        # but we don't have the owner here - maybe parse from existing
2942
        # cache? for now, we only lose lvm data when we rename, which
2943
        # is less critical than DRBD or MD
2944
    except errors.BlockDeviceError, err:
2945
      msgs.append("Can't rename device '%s' to '%s': %s" %
2946
                  (dev, unique_id, err))
2947
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2948
      result = False
2949
  if not result:
2950
    _Fail("; ".join(msgs))
2951

    
2952

    
2953
def _TransformFileStorageDir(fs_dir):
2954
  """Checks whether given file_storage_dir is valid.
2955

2956
  Checks wheter the given fs_dir is within the cluster-wide default
2957
  file_storage_dir or the shared_file_storage_dir, which are stored in
2958
  SimpleStore. Only paths under those directories are allowed.
2959

2960
  @type fs_dir: str
2961
  @param fs_dir: the path to check
2962

2963
  @return: the normalized path if valid, None otherwise
2964

2965
  """
2966
  if not (constants.ENABLE_FILE_STORAGE or
2967
          constants.ENABLE_SHARED_FILE_STORAGE):
2968
    _Fail("File storage disabled at configure time")
2969

    
2970
  bdev.CheckFileStoragePath(fs_dir)
2971

    
2972
  return os.path.normpath(fs_dir)
2973

    
2974

    
2975
def CreateFileStorageDir(file_storage_dir):
2976
  """Create file storage directory.
2977

2978
  @type file_storage_dir: str
2979
  @param file_storage_dir: directory to create
2980

2981
  @rtype: tuple
2982
  @return: tuple with first element a boolean indicating wheter dir
2983
      creation was successful or not
2984

2985
  """
2986
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2987
  if os.path.exists(file_storage_dir):
2988
    if not os.path.isdir(file_storage_dir):
2989
      _Fail("Specified storage dir '%s' is not a directory",
2990
            file_storage_dir)
2991
  else:
2992
    try:
2993
      os.makedirs(file_storage_dir, 0750)
2994
    except OSError, err:
2995
      _Fail("Cannot create file storage directory '%s': %s",
2996
            file_storage_dir, err, exc=True)
2997

    
2998

    
2999
def RemoveFileStorageDir(file_storage_dir):
3000
  """Remove file storage directory.
3001

3002
  Remove it only if it's empty. If not log an error and return.
3003

3004
  @type file_storage_dir: str
3005
  @param file_storage_dir: the directory we should cleanup
3006
  @rtype: tuple (success,)
3007
  @return: tuple of one element, C{success}, denoting
3008
      whether the operation was successful
3009

3010
  """
3011
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3012
  if os.path.exists(file_storage_dir):
3013
    if not os.path.isdir(file_storage_dir):
3014
      _Fail("Specified Storage directory '%s' is not a directory",
3015
            file_storage_dir)
3016
    # deletes dir only if empty, otherwise we want to fail the rpc call
3017
    try:
3018
      os.rmdir(file_storage_dir)
3019
    except OSError, err:
3020
      _Fail("Cannot remove file storage directory '%s': %s",
3021
            file_storage_dir, err)
3022

    
3023

    
3024
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
3025
  """Rename the file storage directory.
3026

3027
  @type old_file_storage_dir: str
3028
  @param old_file_storage_dir: the current path
3029
  @type new_file_storage_dir: str
3030
  @param new_file_storage_dir: the name we should rename to
3031
  @rtype: tuple (success,)
3032
  @return: tuple of one element, C{success}, denoting
3033
      whether the operation was successful
3034

3035
  """
3036
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
3037
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
3038
  if not os.path.exists(new_file_storage_dir):
3039
    if os.path.isdir(old_file_storage_dir):
3040
      try:
3041
        os.rename(old_file_storage_dir, new_file_storage_dir)
3042
      except OSError, err:
3043
        _Fail("Cannot rename '%s' to '%s': %s",
3044
              old_file_storage_dir, new_file_storage_dir, err)
3045
    else:
3046
      _Fail("Specified storage dir '%s' is not a directory",
3047
            old_file_storage_dir)
3048
  else:
3049
    if os.path.exists(old_file_storage_dir):
3050
      _Fail("Cannot rename '%s' to '%s': both locations exist",
3051
            old_file_storage_dir, new_file_storage_dir)
3052

    
3053

    
3054
def _EnsureJobQueueFile(file_name):
3055
  """Checks whether the given filename is in the queue directory.
3056

3057
  @type file_name: str
3058
  @param file_name: the file name we should check
3059
  @rtype: None
3060
  @raises RPCFail: if the file is not valid
3061

3062
  """
3063
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
3064
    _Fail("Passed job queue file '%s' does not belong to"
3065
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
3066

    
3067

    
3068
def JobQueueUpdate(file_name, content):
3069
  """Updates a file in the queue directory.
3070

3071
  This is just a wrapper over L{utils.io.WriteFile}, with proper
3072
  checking.
3073

3074
  @type file_name: str
3075
  @param file_name: the job file name
3076
  @type content: str
3077
  @param content: the new job contents
3078
  @rtype: boolean
3079
  @return: the success of the operation
3080

3081
  """
3082
  file_name = vcluster.LocalizeVirtualPath(file_name)
3083

    
3084
  _EnsureJobQueueFile(file_name)
3085
  getents = runtime.GetEnts()
3086

    
3087
  # Write and replace the file atomically
3088
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3089
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3090

    
3091

    
3092
def JobQueueRename(old, new):
3093
  """Renames a job queue file.
3094

3095
  This is just a wrapper over os.rename with proper checking.
3096

3097
  @type old: str
3098
  @param old: the old (actual) file name
3099
  @type new: str
3100
  @param new: the desired file name
3101
  @rtype: tuple
3102
  @return: the success of the operation and payload
3103

3104
  """
3105
  old = vcluster.LocalizeVirtualPath(old)
3106
  new = vcluster.LocalizeVirtualPath(new)
3107

    
3108
  _EnsureJobQueueFile(old)
3109
  _EnsureJobQueueFile(new)
3110

    
3111
  getents = runtime.GetEnts()
3112

    
3113
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3114
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3115

    
3116

    
3117
def BlockdevClose(instance_name, disks):
3118
  """Closes the given block devices.
3119

3120
  This means they will be switched to secondary mode (in case of
3121
  DRBD).
3122

3123
  @param instance_name: if the argument is not empty, the symlinks
3124
      of this instance will be removed
3125
  @type disks: list of L{objects.Disk}
3126
  @param disks: the list of disks to be closed
3127
  @rtype: tuple (success, message)
3128
  @return: a tuple of success and message, where success
3129
      indicates the succes of the operation, and message
3130
      which will contain the error details in case we
3131
      failed
3132

3133
  """
3134
  bdevs = []
3135
  for cf in disks:
3136
    rd = _RecursiveFindBD(cf)
3137
    if rd is None:
3138
      _Fail("Can't find device %s", cf)
3139
    bdevs.append(rd)
3140

    
3141
  msg = []
3142
  for rd in bdevs:
3143
    try:
3144
      rd.Close()
3145
    except errors.BlockDeviceError, err:
3146
      msg.append(str(err))
3147
  if msg:
3148
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3149
  else:
3150
    if instance_name:
3151
      _RemoveBlockDevLinks(instance_name, disks)
3152

    
3153

    
3154
def ValidateHVParams(hvname, hvparams):
3155
  """Validates the given hypervisor parameters.
3156

3157
  @type hvname: string
3158
  @param hvname: the hypervisor name
3159
  @type hvparams: dict
3160
  @param hvparams: the hypervisor parameters to be validated
3161
  @rtype: None
3162

3163
  """
3164
  try:
3165
    hv_type = hypervisor.GetHypervisor(hvname)
3166
    hv_type.ValidateParameters(hvparams)
3167
  except errors.HypervisorError, err:
3168
    _Fail(str(err), log=False)
3169

    
3170

    
3171
def _CheckOSPList(os_obj, parameters):
3172
  """Check whether a list of parameters is supported by the OS.
3173

3174
  @type os_obj: L{objects.OS}
3175
  @param os_obj: OS object to check
3176
  @type parameters: list
3177
  @param parameters: the list of parameters to check
3178

3179
  """
3180
  supported = [v[0] for v in os_obj.supported_parameters]
3181
  delta = frozenset(parameters).difference(supported)
3182
  if delta:
3183
    _Fail("The following parameters are not supported"
3184
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3185

    
3186

    
3187
def ValidateOS(required, osname, checks, osparams):
3188
  """Validate the given OS' parameters.
3189

3190
  @type required: boolean
3191
  @param required: whether absence of the OS should translate into
3192
      failure or not
3193
  @type osname: string
3194
  @param osname: the OS to be validated
3195
  @type checks: list
3196
  @param checks: list of the checks to run (currently only 'parameters')
3197
  @type osparams: dict
3198
  @param osparams: dictionary with OS parameters
3199
  @rtype: boolean
3200
  @return: True if the validation passed, or False if the OS was not
3201
      found and L{required} was false
3202

3203
  """
3204
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3205
    _Fail("Unknown checks required for OS %s: %s", osname,
3206
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3207

    
3208
  name_only = objects.OS.GetName(osname)
3209
  status, tbv = _TryOSFromDisk(name_only, None)
3210

    
3211
  if not status:
3212
    if required:
3213
      _Fail(tbv)
3214
    else:
3215
      return False
3216

    
3217
  if max(tbv.api_versions) < constants.OS_API_V20:
3218
    return True
3219

    
3220
  if constants.OS_VALIDATE_PARAMETERS in checks:
3221
    _CheckOSPList(tbv, osparams.keys())
3222

    
3223
  validate_env = OSCoreEnv(osname, tbv, osparams)
3224
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3225
                        cwd=tbv.path, reset_env=True)
3226
  if result.failed:
3227
    logging.error("os validate command '%s' returned error: %s output: %s",
3228
                  result.cmd, result.fail_reason, result.output)
3229
    _Fail("OS validation script failed (%s), output: %s",
3230
          result.fail_reason, result.output, log=False)
3231

    
3232
  return True
3233

    
3234

    
3235
def DemoteFromMC():
3236
  """Demotes the current node from master candidate role.
3237

3238
  """
3239
  # try to ensure we're not the master by mistake
3240
  master, myself = ssconf.GetMasterAndMyself()
3241
  if master == myself:
3242
    _Fail("ssconf status shows I'm the master node, will not demote")
3243

    
3244
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3245
  if not result.failed:
3246
    _Fail("The master daemon is running, will not demote")
3247

    
3248
  try:
3249
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3250
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3251
  except EnvironmentError, err:
3252
    if err.errno != errno.ENOENT:
3253
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3254

    
3255
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3256

    
3257

    
3258
def _GetX509Filenames(cryptodir, name):
3259
  """Returns the full paths for the private key and certificate.
3260

3261
  """
3262
  return (utils.PathJoin(cryptodir, name),
3263
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3264
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3265

    
3266

    
3267
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3268
  """Creates a new X509 certificate for SSL/TLS.
3269

3270
  @type validity: int
3271
  @param validity: Validity in seconds
3272
  @rtype: tuple; (string, string)
3273
  @return: Certificate name and public part
3274

3275
  """
3276
  (key_pem, cert_pem) = \
3277
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3278
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3279

    
3280
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3281
                              prefix="x509-%s-" % utils.TimestampForFilename())
3282
  try:
3283
    name = os.path.basename(cert_dir)
3284
    assert len(name) > 5
3285

    
3286
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3287

    
3288
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3289
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3290

    
3291
    # Never return private key as it shouldn't leave the node
3292
    return (name, cert_pem)
3293
  except Exception:
3294
    shutil.rmtree(cert_dir, ignore_errors=True)
3295
    raise
3296

    
3297

    
3298
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3299
  """Removes a X509 certificate.
3300

3301
  @type name: string
3302
  @param name: Certificate name
3303

3304
  """
3305
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3306

    
3307
  utils.RemoveFile(key_file)
3308
  utils.RemoveFile(cert_file)
3309

    
3310
  try:
3311
    os.rmdir(cert_dir)
3312
  except EnvironmentError, err:
3313
    _Fail("Cannot remove certificate directory '%s': %s",
3314
          cert_dir, err)
3315

    
3316

    
3317
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3318
  """Returns the command for the requested input/output.
3319

3320
  @type instance: L{objects.Instance}
3321
  @param instance: The instance object
3322
  @param mode: Import/export mode
3323
  @param ieio: Input/output type
3324
  @param ieargs: Input/output arguments
3325

3326
  """
3327
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3328

    
3329
  env = None
3330
  prefix = None
3331
  suffix = None
3332
  exp_size = None
3333

    
3334
  if ieio == constants.IEIO_FILE:
3335
    (filename, ) = ieargs
3336

    
3337
    if not utils.IsNormAbsPath(filename):
3338
      _Fail("Path '%s' is not normalized or absolute", filename)
3339

    
3340
    real_filename = os.path.realpath(filename)
3341
    directory = os.path.dirname(real_filename)
3342

    
3343
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3344
      _Fail("File '%s' is not under exports directory '%s': %s",
3345
            filename, pathutils.EXPORT_DIR, real_filename)
3346

    
3347
    # Create directory
3348
    utils.Makedirs(directory, mode=0750)
3349

    
3350
    quoted_filename = utils.ShellQuote(filename)
3351

    
3352
    if mode == constants.IEM_IMPORT:
3353
      suffix = "> %s" % quoted_filename
3354
    elif mode == constants.IEM_EXPORT:
3355
      suffix = "< %s" % quoted_filename
3356

    
3357
      # Retrieve file size
3358
      try:
3359
        st = os.stat(filename)
3360
      except EnvironmentError, err:
3361
        logging.error("Can't stat(2) %s: %s", filename, err)
3362
      else:
3363
        exp_size = utils.BytesToMebibyte(st.st_size)
3364

    
3365
  elif ieio == constants.IEIO_RAW_DISK:
3366
    (disk, ) = ieargs
3367

    
3368
    real_disk = _OpenRealBD(disk)
3369

    
3370
    if mode == constants.IEM_IMPORT:
3371
      # we set here a smaller block size as, due to transport buffering, more
3372
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3373
      # is not already there or we pass a wrong path; we use notrunc to no
3374
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3375
      # much memory; this means that at best, we flush every 64k, which will
3376
      # not be very fast
3377
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3378
                                    " bs=%s oflag=dsync"),
3379
                                    real_disk.dev_path,
3380
                                    str(64 * 1024))
3381

    
3382
    elif mode == constants.IEM_EXPORT:
3383
      # the block size on the read dd is 1MiB to match our units
3384
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3385
                                   real_disk.dev_path,
3386
                                   str(1024 * 1024), # 1 MB
3387
                                   str(disk.size))
3388
      exp_size = disk.size
3389

    
3390
  elif ieio == constants.IEIO_SCRIPT:
3391
    (disk, disk_index, ) = ieargs
3392

    
3393
    assert isinstance(disk_index, (int, long))
3394

    
3395
    real_disk = _OpenRealBD(disk)
3396

    
3397
    inst_os = OSFromDisk(instance.os)
3398
    env = OSEnvironment(instance, inst_os)
3399

    
3400
    if mode == constants.IEM_IMPORT:
3401
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3402
      env["IMPORT_INDEX"] = str(disk_index)
3403
      script = inst_os.import_script
3404

    
3405
    elif mode == constants.IEM_EXPORT:
3406
      env["EXPORT_DEVICE"] = real_disk.dev_path
3407
      env["EXPORT_INDEX"] = str(disk_index)
3408
      script = inst_os.export_script
3409

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

    
3413
    if mode == constants.IEM_IMPORT:
3414
      suffix = "| %s" % script_cmd
3415

    
3416
    elif mode == constants.IEM_EXPORT:
3417
      prefix = "%s |" % script_cmd
3418

    
3419
    # Let script predict size
3420
    exp_size = constants.IE_CUSTOM_SIZE
3421

    
3422
  else:
3423
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3424

    
3425
  return (env, prefix, suffix, exp_size)
3426

    
3427

    
3428
def _CreateImportExportStatusDir(prefix):
3429
  """Creates status directory for import/export.
3430

3431
  """
3432
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3433
                          prefix=("%s-%s-" %
3434
                                  (prefix, utils.TimestampForFilename())))
3435

    
3436

    
3437
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3438
                            ieio, ieioargs):
3439
  """Starts an import or export daemon.
3440

3441
  @param mode: Import/output mode
3442
  @type opts: L{objects.ImportExportOptions}
3443
  @param opts: Daemon options
3444
  @type host: string
3445
  @param host: Remote host for export (None for import)
3446
  @type port: int
3447
  @param port: Remote port for export (None for import)
3448
  @type instance: L{objects.Instance}
3449
  @param instance: Instance object
3450
  @type component: string
3451
  @param component: which part of the instance is transferred now,
3452
      e.g. 'disk/0'
3453
  @param ieio: Input/output type
3454
  @param ieioargs: Input/output arguments
3455

3456
  """
3457
  if mode == constants.IEM_IMPORT:
3458
    prefix = "import"
3459

    
3460
    if not (host is None and port is None):
3461
      _Fail("Can not specify host or port on import")
3462

    
3463
  elif mode == constants.IEM_EXPORT:
3464
    prefix = "export"
3465

    
3466
    if host is None or port is None:
3467
      _Fail("Host and port must be specified for an export")
3468

    
3469
  else:
3470
    _Fail("Invalid mode %r", mode)
3471

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

    
3475
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3476
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3477

    
3478
  if opts.key_name is None:
3479
    # Use server.pem
3480
    key_path = pathutils.NODED_CERT_FILE
3481
    cert_path = pathutils.NODED_CERT_FILE
3482
    assert opts.ca_pem is None
3483
  else:
3484
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3485
                                                 opts.key_name)
3486
    assert opts.ca_pem is not None
3487

    
3488
  for i in [key_path, cert_path]:
3489
    if not os.path.exists(i):
3490
      _Fail("File '%s' does not exist" % i)
3491

    
3492
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3493
  try:
3494
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3495
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3496
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3497

    
3498
    if opts.ca_pem is None:
3499
      # Use server.pem
3500
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3501
    else:
3502
      ca = opts.ca_pem
3503

    
3504
    # Write CA file
3505
    utils.WriteFile(ca_file, data=ca, mode=0400)
3506

    
3507
    cmd = [
3508
      pathutils.IMPORT_EXPORT_DAEMON,
3509
      status_file, mode,
3510
      "--key=%s" % key_path,
3511
      "--cert=%s" % cert_path,
3512
      "--ca=%s" % ca_file,
3513
      ]
3514

    
3515
    if host:
3516
      cmd.append("--host=%s" % host)
3517

    
3518
    if port:
3519
      cmd.append("--port=%s" % port)
3520

    
3521
    if opts.ipv6:
3522
      cmd.append("--ipv6")
3523
    else:
3524
      cmd.append("--ipv4")
3525

    
3526
    if opts.compress:
3527
      cmd.append("--compress=%s" % opts.compress)
3528

    
3529
    if opts.magic:
3530
      cmd.append("--magic=%s" % opts.magic)
3531

    
3532
    if exp_size is not None:
3533
      cmd.append("--expected-size=%s" % exp_size)
3534

    
3535
    if cmd_prefix:
3536
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3537

    
3538
    if cmd_suffix:
3539
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3540

    
3541
    if mode == constants.IEM_EXPORT:
3542
      # Retry connection a few times when connecting to remote peer
3543
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3544
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3545
    elif opts.connect_timeout is not None:
3546
      assert mode == constants.IEM_IMPORT
3547
      # Overall timeout for establishing connection while listening
3548
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3549

    
3550
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3551

    
3552
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3553
    # support for receiving a file descriptor for output
3554
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3555
                      output=logfile)
3556

    
3557
    # The import/export name is simply the status directory name
3558
    return os.path.basename(status_dir)
3559

    
3560
  except Exception:
3561
    shutil.rmtree(status_dir, ignore_errors=True)
3562
    raise
3563

    
3564

    
3565
def GetImportExportStatus(names):
3566
  """Returns import/export daemon status.
3567

3568
  @type names: sequence
3569
  @param names: List of names
3570
  @rtype: List of dicts
3571
  @return: Returns a list of the state of each named import/export or None if a
3572
           status couldn't be read
3573

3574
  """
3575
  result = []
3576

    
3577
  for name in names:
3578
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3579
                                 _IES_STATUS_FILE)
3580

    
3581
    try:
3582
      data = utils.ReadFile(status_file)
3583
    except EnvironmentError, err:
3584
      if err.errno != errno.ENOENT:
3585
        raise
3586
      data = None
3587

    
3588
    if not data:
3589
      result.append(None)
3590
      continue
3591

    
3592
    result.append(serializer.LoadJson(data))
3593

    
3594
  return result
3595

    
3596

    
3597
def AbortImportExport(name):
3598
  """Sends SIGTERM to a running import/export daemon.
3599

3600
  """
3601
  logging.info("Abort import/export %s", name)
3602

    
3603
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3604
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3605

    
3606
  if pid:
3607
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3608
                 name, pid)
3609
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3610

    
3611

    
3612
def CleanupImportExport(name):
3613
  """Cleanup after an import or export.
3614

3615
  If the import/export daemon is still running it's killed. Afterwards the
3616
  whole status directory is removed.
3617

3618
  """
3619
  logging.info("Finalizing import/export %s", name)
3620

    
3621
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3622

    
3623
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3624

    
3625
  if pid:
3626
    logging.info("Import/export %s is still running with PID %s",
3627
                 name, pid)
3628
    utils.KillProcess(pid, waitpid=False)
3629

    
3630
  shutil.rmtree(status_dir, ignore_errors=True)
3631

    
3632

    
3633
def _FindDisks(nodes_ip, disks):
3634
  """Sets the physical ID on disks and returns the block devices.
3635

3636
  """
3637
  # set the correct physical ID
3638
  my_name = netutils.Hostname.GetSysName()
3639
  for cf in disks:
3640
    cf.SetPhysicalID(my_name, nodes_ip)
3641

    
3642
  bdevs = []
3643

    
3644
  for cf in disks:
3645
    rd = _RecursiveFindBD(cf)
3646
    if rd is None:
3647
      _Fail("Can't find device %s", cf)
3648
    bdevs.append(rd)
3649
  return bdevs
3650

    
3651

    
3652
def DrbdDisconnectNet(nodes_ip, disks):
3653
  """Disconnects the network on a list of drbd devices.
3654

3655
  """
3656
  bdevs = _FindDisks(nodes_ip, disks)
3657

    
3658
  # disconnect disks
3659
  for rd in bdevs:
3660
    try:
3661
      rd.DisconnectNet()
3662
    except errors.BlockDeviceError, err:
3663
      _Fail("Can't change network configuration to standalone mode: %s",
3664
            err, exc=True)
3665

    
3666

    
3667
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3668
  """Attaches the network on a list of drbd devices.
3669

3670
  """
3671
  bdevs = _FindDisks(nodes_ip, disks)
3672

    
3673
  if multimaster:
3674
    for idx, rd in enumerate(bdevs):
3675
      try:
3676
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3677
      except EnvironmentError, err:
3678
        _Fail("Can't create symlink: %s", err)
3679
  # reconnect disks, switch to new master configuration and if
3680
  # needed primary mode
3681
  for rd in bdevs:
3682
    try:
3683
      rd.AttachNet(multimaster)
3684
    except errors.BlockDeviceError, err:
3685
      _Fail("Can't change network configuration: %s", err)
3686

    
3687
  # wait until the disks are connected; we need to retry the re-attach
3688
  # if the device becomes standalone, as this might happen if the one
3689
  # node disconnects and reconnects in a different mode before the
3690
  # other node reconnects; in this case, one or both of the nodes will
3691
  # decide it has wrong configuration and switch to standalone
3692

    
3693
  def _Attach():
3694
    all_connected = True
3695

    
3696
    for rd in bdevs:
3697
      stats = rd.GetProcStatus()
3698

    
3699
      all_connected = (all_connected and
3700
                       (stats.is_connected or stats.is_in_resync))
3701

    
3702
      if stats.is_standalone:
3703
        # peer had different config info and this node became
3704
        # standalone, even though this should not happen with the
3705
        # new staged way of changing disk configs
3706
        try:
3707
          rd.AttachNet(multimaster)
3708
        except errors.BlockDeviceError, err:
3709
          _Fail("Can't change network configuration: %s", err)
3710

    
3711
    if not all_connected:
3712
      raise utils.RetryAgain()
3713

    
3714
  try:
3715
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3716
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3717
  except utils.RetryTimeout:
3718
    _Fail("Timeout in disk reconnecting")
3719

    
3720
  if multimaster:
3721
    # change to primary mode
3722
    for rd in bdevs:
3723
      try:
3724
        rd.Open()
3725
      except errors.BlockDeviceError, err:
3726
        _Fail("Can't change to primary mode: %s", err)
3727

    
3728

    
3729
def DrbdWaitSync(nodes_ip, disks):
3730
  """Wait until DRBDs have synchronized.
3731

3732
  """
3733
  def _helper(rd):
3734
    stats = rd.GetProcStatus()
3735
    if not (stats.is_connected or stats.is_in_resync):
3736
      raise utils.RetryAgain()
3737
    return stats
3738

    
3739
  bdevs = _FindDisks(nodes_ip, disks)
3740

    
3741
  min_resync = 100
3742
  alldone = True
3743
  for rd in bdevs:
3744
    try:
3745
      # poll each second for 15 seconds
3746
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3747
    except utils.RetryTimeout:
3748
      stats = rd.GetProcStatus()
3749
      # last check
3750
      if not (stats.is_connected or stats.is_in_resync):
3751
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3752
    alldone = alldone and (not stats.is_in_resync)
3753
    if stats.sync_percent is not None:
3754
      min_resync = min(min_resync, stats.sync_percent)
3755

    
3756
  return (alldone, min_resync)
3757

    
3758

    
3759
def GetDrbdUsermodeHelper():
3760
  """Returns DRBD usermode helper currently configured.
3761

3762
  """
3763
  try:
3764
    return drbd.DRBD8.GetUsermodeHelper()
3765
  except errors.BlockDeviceError, err:
3766
    _Fail(str(err))
3767

    
3768

    
3769
def PowercycleNode(hypervisor_type):
3770
  """Hard-powercycle the node.
3771

3772
  Because we need to return first, and schedule the powercycle in the
3773
  background, we won't be able to report failures nicely.
3774

3775
  """
3776
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3777
  try:
3778
    pid = os.fork()
3779
  except OSError:
3780
    # if we can't fork, we'll pretend that we're in the child process
3781
    pid = 0
3782
  if pid > 0:
3783
    return "Reboot scheduled in 5 seconds"
3784
  # ensure the child is running on ram
3785
  try:
3786
    utils.Mlockall()
3787
  except Exception: # pylint: disable=W0703
3788
    pass
3789
  time.sleep(5)
3790
  hyper.PowercycleNode()
3791

    
3792

    
3793
def _VerifyRestrictedCmdName(cmd):
3794
  """Verifies a restricted command name.
3795

3796
  @type cmd: string
3797
  @param cmd: Command name
3798
  @rtype: tuple; (boolean, string or None)
3799
  @return: The tuple's first element is the status; if C{False}, the second
3800
    element is an error message string, otherwise it's C{None}
3801

3802
  """
3803
  if not cmd.strip():
3804
    return (False, "Missing command name")
3805

    
3806
  if os.path.basename(cmd) != cmd:
3807
    return (False, "Invalid command name")
3808

    
3809
  if not constants.EXT_PLUGIN_MASK.match(cmd):
3810
    return (False, "Command name contains forbidden characters")
3811

    
3812
  return (True, None)
3813

    
3814

    
3815
def _CommonRestrictedCmdCheck(path, owner):
3816
  """Common checks for restricted command file system directories and files.
3817

3818
  @type path: string
3819
  @param path: Path to check
3820
  @param owner: C{None} or tuple containing UID and GID
3821
  @rtype: tuple; (boolean, string or C{os.stat} result)
3822
  @return: The tuple's first element is the status; if C{False}, the second
3823
    element is an error message string, otherwise it's the result of C{os.stat}
3824

3825
  """
3826
  if owner is None:
3827
    # Default to root as owner
3828
    owner = (0, 0)
3829

    
3830
  try:
3831
    st = os.stat(path)
3832
  except EnvironmentError, err:
3833
    return (False, "Can't stat(2) '%s': %s" % (path, err))
3834

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

    
3838
  if (st.st_uid, st.st_gid) != owner:
3839
    (owner_uid, owner_gid) = owner
3840
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
3841

    
3842
  return (True, st)
3843

    
3844

    
3845
def _VerifyRestrictedCmdDirectory(path, _owner=None):
3846
  """Verifies restricted command directory.
3847

3848
  @type path: string
3849
  @param path: Path to check
3850
  @rtype: tuple; (boolean, string or None)
3851
  @return: The tuple's first element is the status; if C{False}, the second
3852
    element is an error message string, otherwise it's C{None}
3853

3854
  """
3855
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
3856

    
3857
  if not status:
3858
    return (False, value)
3859

    
3860
  if not stat.S_ISDIR(value.st_mode):
3861
    return (False, "Path '%s' is not a directory" % path)
3862

    
3863
  return (True, None)
3864

    
3865

    
3866
def _VerifyRestrictedCmd(path, cmd, _owner=None):
3867
  """Verifies a whole restricted command and returns its executable filename.
3868

3869
  @type path: string
3870
  @param path: Directory containing restricted commands
3871
  @type cmd: string
3872
  @param cmd: Command name
3873
  @rtype: tuple; (boolean, string)
3874
  @return: The tuple's first element is the status; if C{False}, the second
3875
    element is an error message string, otherwise the second element is the
3876
    absolute path to the executable
3877

3878
  """
3879
  executable = utils.PathJoin(path, cmd)
3880

    
3881
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
3882

    
3883
  if not status:
3884
    return (False, msg)
3885

    
3886
  if not utils.IsExecutable(executable):
3887
    return (False, "access(2) thinks '%s' can't be executed" % executable)
3888

    
3889
  return (True, executable)
3890

    
3891

    
3892
def _PrepareRestrictedCmd(path, cmd,
3893
                          _verify_dir=_VerifyRestrictedCmdDirectory,
3894
                          _verify_name=_VerifyRestrictedCmdName,
3895
                          _verify_cmd=_VerifyRestrictedCmd):
3896
  """Performs a number of tests on a restricted command.
3897

3898
  @type path: string
3899
  @param path: Directory containing restricted commands
3900
  @type cmd: string
3901
  @param cmd: Command name
3902
  @return: Same as L{_VerifyRestrictedCmd}
3903

3904
  """
3905
  # Verify the directory first
3906
  (status, msg) = _verify_dir(path)
3907
  if status:
3908
    # Check command if everything was alright
3909
    (status, msg) = _verify_name(cmd)
3910

    
3911
  if not status:
3912
    return (False, msg)
3913

    
3914
  # Check actual executable
3915
  return _verify_cmd(path, cmd)
3916

    
3917

    
3918
def RunRestrictedCmd(cmd,
3919
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
3920
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
3921
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
3922
                     _sleep_fn=time.sleep,
3923
                     _prepare_fn=_PrepareRestrictedCmd,
3924
                     _runcmd_fn=utils.RunCmd,
3925
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
3926
  """Executes a restricted command after performing strict tests.
3927

3928
  @type cmd: string
3929
  @param cmd: Command name
3930
  @rtype: string
3931
  @return: Command output
3932
  @raise RPCFail: In case of an error
3933

3934
  """
3935
  logging.info("Preparing to run restricted command '%s'", cmd)
3936

    
3937
  if not _enabled:
3938
    _Fail("Restricted commands disabled at configure time")
3939

    
3940
  lock = None
3941
  try:
3942
    cmdresult = None
3943
    try:
3944
      lock = utils.FileLock.Open(_lock_file)
3945
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
3946

    
3947
      (status, value) = _prepare_fn(_path, cmd)
3948

    
3949
      if status:
3950
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
3951
                               postfork_fn=lambda _: lock.Unlock())
3952
      else:
3953
        logging.error(value)
3954
    except Exception: # pylint: disable=W0703
3955
      # Keep original error in log
3956
      logging.exception("Caught exception")
3957

    
3958
    if cmdresult is None:
3959
      logging.info("Sleeping for %0.1f seconds before returning",
3960
                   _RCMD_INVALID_DELAY)
3961
      _sleep_fn(_RCMD_INVALID_DELAY)
3962

    
3963
      # Do not include original error message in returned error
3964
      _Fail("Executing command '%s' failed" % cmd)
3965
    elif cmdresult.failed or cmdresult.fail_reason:
3966
      _Fail("Restricted command '%s' failed: %s; output: %s",
3967
            cmd, cmdresult.fail_reason, cmdresult.output)
3968
    else:
3969
      return cmdresult.output
3970
  finally:
3971
    if lock is not None:
3972
      # Release lock at last
3973
      lock.Close()
3974
      lock = None
3975

    
3976

    
3977
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
3978
  """Creates or removes the watcher pause file.
3979

3980
  @type until: None or number
3981
  @param until: Unix timestamp saying until when the watcher shouldn't run
3982

3983
  """
3984
  if until is None:
3985
    logging.info("Received request to no longer pause watcher")
3986
    utils.RemoveFile(_filename)
3987
  else:
3988
    logging.info("Received request to pause watcher until %s", until)
3989

    
3990
    if not ht.TNumber(until):
3991
      _Fail("Duration must be numeric")
3992

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

    
3995

    
3996
class HooksRunner(object):
3997
  """Hook runner.
3998

3999
  This class is instantiated on the node side (ganeti-noded) and not
4000
  on the master side.
4001

4002
  """
4003
  def __init__(self, hooks_base_dir=None):
4004
    """Constructor for hooks runner.
4005

4006
    @type hooks_base_dir: str or None
4007
    @param hooks_base_dir: if not None, this overrides the
4008
        L{pathutils.HOOKS_BASE_DIR} (useful for unittests)
4009

4010
    """
4011
    if hooks_base_dir is None:
4012
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
4013
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
4014
    # constant
4015
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
4016

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

4020
    """
4021
    assert len(node_list) == 1
4022
    node = node_list[0]
4023
    _, myself = ssconf.GetMasterAndMyself()
4024
    assert node == myself
4025

    
4026
    results = self.RunHooks(hpath, phase, env)
4027

    
4028
    # Return values in the form expected by HooksMaster
4029
    return {node: (None, False, results)}
4030

    
4031
  def RunHooks(self, hpath, phase, env):
4032
    """Run the scripts in the hooks directory.
4033

4034
    @type hpath: str
4035
    @param hpath: the path to the hooks directory which
4036
        holds the scripts
4037
    @type phase: str
4038
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
4039
        L{constants.HOOKS_PHASE_POST}
4040
    @type env: dict
4041
    @param env: dictionary with the environment for the hook
4042
    @rtype: list
4043
    @return: list of 3-element tuples:
4044
      - script path
4045
      - script result, either L{constants.HKR_SUCCESS} or
4046
        L{constants.HKR_FAIL}
4047
      - output of the script
4048

4049
    @raise errors.ProgrammerError: for invalid input
4050
        parameters
4051

4052
    """
4053
    if phase == constants.HOOKS_PHASE_PRE:
4054
      suffix = "pre"
4055
    elif phase == constants.HOOKS_PHASE_POST:
4056
      suffix = "post"
4057
    else:
4058
      _Fail("Unknown hooks phase '%s'", phase)
4059

    
4060
    subdir = "%s-%s.d" % (hpath, suffix)
4061
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
4062

    
4063
    results = []
4064

    
4065
    if not os.path.isdir(dir_name):
4066
      # for non-existing/non-dirs, we simply exit instead of logging a
4067
      # warning at every operation
4068
      return results
4069

    
4070
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
4071

    
4072
    for (relname, relstatus, runresult) in runparts_results:
4073
      if relstatus == constants.RUNPARTS_SKIP:
4074
        rrval = constants.HKR_SKIP
4075
        output = ""
4076
      elif relstatus == constants.RUNPARTS_ERR:
4077
        rrval = constants.HKR_FAIL
4078
        output = "Hook script execution error: %s" % runresult
4079
      elif relstatus == constants.RUNPARTS_RUN:
4080
        if runresult.failed:
4081
          rrval = constants.HKR_FAIL
4082
        else:
4083
          rrval = constants.HKR_SUCCESS
4084
        output = utils.SafeEncode(runresult.output.strip())
4085
      results.append(("%s/%s" % (subdir, relname), rrval, output))
4086

    
4087
    return results
4088

    
4089

    
4090
class IAllocatorRunner(object):
4091
  """IAllocator runner.
4092

4093
  This class is instantiated on the node side (ganeti-noded) and not on
4094
  the master side.
4095

4096
  """
4097
  @staticmethod
4098
  def Run(name, idata):
4099
    """Run an iallocator script.
4100

4101
    @type name: str
4102
    @param name: the iallocator script name
4103
    @type idata: str
4104
    @param idata: the allocator input data
4105

4106
    @rtype: tuple
4107
    @return: two element tuple of:
4108
       - status
4109
       - either error message or stdout of allocator (for success)
4110

4111
    """
4112
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
4113
                                  os.path.isfile)
4114
    if alloc_script is None:
4115
      _Fail("iallocator module '%s' not found in the search path", name)
4116

    
4117
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
4118
    try:
4119
      os.write(fd, idata)
4120
      os.close(fd)
4121
      result = utils.RunCmd([alloc_script, fin_name])
4122
      if result.failed:
4123
        _Fail("iallocator module '%s' failed: %s, output '%s'",
4124
              name, result.fail_reason, result.output)
4125
    finally:
4126
      os.unlink(fin_name)
4127

    
4128
    return result.stdout
4129

    
4130

    
4131
class DevCacheManager(object):
4132
  """Simple class for managing a cache of block device information.
4133

4134
  """
4135
  _DEV_PREFIX = "/dev/"
4136
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4137

    
4138
  @classmethod
4139
  def _ConvertPath(cls, dev_path):
4140
    """Converts a /dev/name path to the cache file name.
4141

4142
    This replaces slashes with underscores and strips the /dev
4143
    prefix. It then returns the full path to the cache file.
4144

4145
    @type dev_path: str
4146
    @param dev_path: the C{/dev/} path name
4147
    @rtype: str
4148
    @return: the converted path name
4149

4150
    """
4151
    if dev_path.startswith(cls._DEV_PREFIX):
4152
      dev_path = dev_path[len(cls._DEV_PREFIX):]
4153
    dev_path = dev_path.replace("/", "_")
4154
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4155
    return fpath
4156

    
4157
  @classmethod
4158
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4159
    """Updates the cache information for a given device.
4160

4161
    @type dev_path: str
4162
    @param dev_path: the pathname of the device
4163
    @type owner: str
4164
    @param owner: the owner (instance name) of the device
4165
    @type on_primary: bool
4166
    @param on_primary: whether this is the primary
4167
        node nor not
4168
    @type iv_name: str
4169
    @param iv_name: the instance-visible name of the
4170
        device, as in objects.Disk.iv_name
4171

4172
    @rtype: None
4173

4174
    """
4175
    if dev_path is None:
4176
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
4177
      return
4178
    fpath = cls._ConvertPath(dev_path)
4179
    if on_primary:
4180
      state = "primary"
4181
    else:
4182
      state = "secondary"
4183
    if iv_name is None:
4184
      iv_name = "not_visible"
4185
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4186
    try:
4187
      utils.WriteFile(fpath, data=fdata)
4188
    except EnvironmentError, err:
4189
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4190

    
4191
  @classmethod
4192
  def RemoveCache(cls, dev_path):
4193
    """Remove data for a dev_path.
4194

4195
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
4196
    path name and logging.
4197

4198
    @type dev_path: str
4199
    @param dev_path: the pathname of the device
4200

4201
    @rtype: None
4202

4203
    """
4204
    if dev_path is None:
4205
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
4206
      return
4207
    fpath = cls._ConvertPath(dev_path)
4208
    try:
4209
      utils.RemoveFile(fpath)
4210
    except EnvironmentError, err:
4211
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)