Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 6ef8077e

History | View | Annotate | Download (127.6 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 _GetHvInfo(name):
596
  """Retrieves node information from a hypervisor.
597

598
  The information returned depends on the hypervisor. Common items:
599

600
    - vg_size is the size of the configured volume group in MiB
601
    - vg_free is the free size of the volume group in MiB
602
    - memory_dom0 is the memory allocated for domain0 in MiB
603
    - memory_free is the currently available (free) ram in MiB
604
    - memory_total is the total number of ram in MiB
605
    - hv_version: the hypervisor version, if available
606

607
  """
608
  return hypervisor.GetHypervisor(name).GetNodeInfo()
609

    
610

    
611
def _GetNamedNodeInfo(names, fn):
612
  """Calls C{fn} for all names in C{names} and returns a dictionary.
613

614
  @rtype: None or dict
615

616
  """
617
  if names is None:
618
    return None
619
  else:
620
    return map(fn, names)
621

    
622

    
623
def GetNodeInfo(storage_units, hv_names, excl_stor):
624
  """Gives back a hash with different information about the node.
625

626
  @type storage_units: list of pairs (string, string)
627
  @param storage_units: List of pairs (storage unit, identifier) to ask for disk
628
                        space information. In case of lvm-vg, the identifier is
629
                        the VG name.
630
  @type hv_names: list of string
631
  @param hv_names: Names of the hypervisors to ask for node information
632
  @type excl_stor: boolean
633
  @param excl_stor: Whether exclusive_storage is active
634
  @rtype: tuple; (string, None/dict, None/dict)
635
  @return: Tuple containing boot ID, volume group information and hypervisor
636
    information
637

638
  """
639
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
640
  storage_info = _GetNamedNodeInfo(
641
    storage_units,
642
    (lambda storage_unit: _ApplyStorageInfoFunction(storage_unit[0],
643
                                                    storage_unit[1],
644
                                                    excl_stor)))
645
  hv_info = _GetNamedNodeInfo(hv_names, _GetHvInfo)
646

    
647
  return (bootid, storage_info, hv_info)
648

    
649

    
650
# FIXME: implement storage reporting for all missing storage types.
651
_STORAGE_TYPE_INFO_FN = {
652
  constants.ST_BLOCK: None,
653
  constants.ST_DISKLESS: None,
654
  constants.ST_EXT: None,
655
  constants.ST_FILE: None,
656
  constants.ST_LVM_VG: _GetVgInfo,
657
  constants.ST_RADOS: None,
658
}
659

    
660

    
661
def _ApplyStorageInfoFunction(storage_type, storage_key, *args):
662
  """Looks up and applies the correct function to calculate free and total
663
  storage for the given storage type.
664

665
  @type storage_type: string
666
  @param storage_type: the storage type for which the storage shall be reported.
667
  @type storage_key: string
668
  @param storage_key: identifier of a storage unit, e.g. the volume group name
669
    of an LVM storage unit
670
  @type args: any
671
  @param args: various parameters that can be used for storage reporting. These
672
    parameters and their semantics vary from storage type to storage type and
673
    are just propagated in this function.
674
  @return: the results of the application of the storage space function (see
675
    _STORAGE_TYPE_INFO_FN) if storage space reporting is implemented for that
676
    storage type
677
  @raises NotImplementedError: for storage types who don't support space
678
    reporting yet
679
  """
680
  fn = _STORAGE_TYPE_INFO_FN[storage_type]
681
  if fn is not None:
682
    return fn(storage_key, *args)
683
  else:
684
    raise NotImplementedError
685

    
686

    
687
def _CheckExclusivePvs(pvi_list):
688
  """Check that PVs are not shared among LVs
689

690
  @type pvi_list: list of L{objects.LvmPvInfo} objects
691
  @param pvi_list: information about the PVs
692

693
  @rtype: list of tuples (string, list of strings)
694
  @return: offending volumes, as tuples: (pv_name, [lv1_name, lv2_name...])
695

696
  """
697
  res = []
698
  for pvi in pvi_list:
699
    if len(pvi.lv_list) > 1:
700
      res.append((pvi.name, pvi.lv_list))
701
  return res
702

    
703

    
704
def VerifyNode(what, cluster_name):
705
  """Verify the status of the local node.
706

707
  Based on the input L{what} parameter, various checks are done on the
708
  local node.
709

710
  If the I{filelist} key is present, this list of
711
  files is checksummed and the file/checksum pairs are returned.
712

713
  If the I{nodelist} key is present, we check that we have
714
  connectivity via ssh with the target nodes (and check the hostname
715
  report).
716

717
  If the I{node-net-test} key is present, we check that we have
718
  connectivity to the given nodes via both primary IP and, if
719
  applicable, secondary IPs.
720

721
  @type what: C{dict}
722
  @param what: a dictionary of things to check:
723
      - filelist: list of files for which to compute checksums
724
      - nodelist: list of nodes we should check ssh communication with
725
      - node-net-test: list of nodes we should check node daemon port
726
        connectivity with
727
      - hypervisor: list with hypervisors to run the verify for
728
  @rtype: dict
729
  @return: a dictionary with the same keys as the input dict, and
730
      values representing the result of the checks
731

732
  """
733
  result = {}
734
  my_name = netutils.Hostname.GetSysName()
735
  port = netutils.GetDaemonPort(constants.NODED)
736
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
737

    
738
  if constants.NV_HYPERVISOR in what and vm_capable:
739
    result[constants.NV_HYPERVISOR] = tmp = {}
740
    for hv_name in what[constants.NV_HYPERVISOR]:
741
      try:
742
        val = hypervisor.GetHypervisor(hv_name).Verify()
743
      except errors.HypervisorError, err:
744
        val = "Error while checking hypervisor: %s" % str(err)
745
      tmp[hv_name] = val
746

    
747
  if constants.NV_HVPARAMS in what and vm_capable:
748
    result[constants.NV_HVPARAMS] = tmp = []
749
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
750
      try:
751
        logging.info("Validating hv %s, %s", hv_name, hvparms)
752
        hypervisor.GetHypervisor(hv_name).ValidateParameters(hvparms)
753
      except errors.HypervisorError, err:
754
        tmp.append((source, hv_name, str(err)))
755

    
756
  if constants.NV_FILELIST in what:
757
    fingerprints = utils.FingerprintFiles(map(vcluster.LocalizeVirtualPath,
758
                                              what[constants.NV_FILELIST]))
759
    result[constants.NV_FILELIST] = \
760
      dict((vcluster.MakeVirtualPath(key), value)
761
           for (key, value) in fingerprints.items())
762

    
763
  if constants.NV_NODELIST in what:
764
    (nodes, bynode) = what[constants.NV_NODELIST]
765

    
766
    # Add nodes from other groups (different for each node)
767
    try:
768
      nodes.extend(bynode[my_name])
769
    except KeyError:
770
      pass
771

    
772
    # Use a random order
773
    random.shuffle(nodes)
774

    
775
    # Try to contact all nodes
776
    val = {}
777
    for node in nodes:
778
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
779
      if not success:
780
        val[node] = message
781

    
782
    result[constants.NV_NODELIST] = val
783

    
784
  if constants.NV_NODENETTEST in what:
785
    result[constants.NV_NODENETTEST] = tmp = {}
786
    my_pip = my_sip = None
787
    for name, pip, sip in what[constants.NV_NODENETTEST]:
788
      if name == my_name:
789
        my_pip = pip
790
        my_sip = sip
791
        break
792
    if not my_pip:
793
      tmp[my_name] = ("Can't find my own primary/secondary IP"
794
                      " in the node list")
795
    else:
796
      for name, pip, sip in what[constants.NV_NODENETTEST]:
797
        fail = []
798
        if not netutils.TcpPing(pip, port, source=my_pip):
799
          fail.append("primary")
800
        if sip != pip:
801
          if not netutils.TcpPing(sip, port, source=my_sip):
802
            fail.append("secondary")
803
        if fail:
804
          tmp[name] = ("failure using the %s interface(s)" %
805
                       " and ".join(fail))
806

    
807
  if constants.NV_MASTERIP in what:
808
    # FIXME: add checks on incoming data structures (here and in the
809
    # rest of the function)
810
    master_name, master_ip = what[constants.NV_MASTERIP]
811
    if master_name == my_name:
812
      source = constants.IP4_ADDRESS_LOCALHOST
813
    else:
814
      source = None
815
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
816
                                                     source=source)
817

    
818
  if constants.NV_USERSCRIPTS in what:
819
    result[constants.NV_USERSCRIPTS] = \
820
      [script for script in what[constants.NV_USERSCRIPTS]
821
       if not utils.IsExecutable(script)]
822

    
823
  if constants.NV_OOB_PATHS in what:
824
    result[constants.NV_OOB_PATHS] = tmp = []
825
    for path in what[constants.NV_OOB_PATHS]:
826
      try:
827
        st = os.stat(path)
828
      except OSError, err:
829
        tmp.append("error stating out of band helper: %s" % err)
830
      else:
831
        if stat.S_ISREG(st.st_mode):
832
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
833
            tmp.append(None)
834
          else:
835
            tmp.append("out of band helper %s is not executable" % path)
836
        else:
837
          tmp.append("out of band helper %s is not a file" % path)
838

    
839
  if constants.NV_LVLIST in what and vm_capable:
840
    try:
841
      val = GetVolumeList(utils.ListVolumeGroups().keys())
842
    except RPCFail, err:
843
      val = str(err)
844
    result[constants.NV_LVLIST] = val
845

    
846
  if constants.NV_INSTANCELIST in what and vm_capable:
847
    # GetInstanceList can fail
848
    try:
849
      val = GetInstanceList(what[constants.NV_INSTANCELIST])
850
    except RPCFail, err:
851
      val = str(err)
852
    result[constants.NV_INSTANCELIST] = val
853

    
854
  if constants.NV_VGLIST in what and vm_capable:
855
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
856

    
857
  if constants.NV_PVLIST in what and vm_capable:
858
    check_exclusive_pvs = constants.NV_EXCLUSIVEPVS in what
859
    val = bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
860
                                       filter_allocatable=False,
861
                                       include_lvs=check_exclusive_pvs)
862
    if check_exclusive_pvs:
863
      result[constants.NV_EXCLUSIVEPVS] = _CheckExclusivePvs(val)
864
      for pvi in val:
865
        # Avoid sending useless data on the wire
866
        pvi.lv_list = []
867
    result[constants.NV_PVLIST] = map(objects.LvmPvInfo.ToDict, val)
868

    
869
  if constants.NV_VERSION in what:
870
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
871
                                    constants.RELEASE_VERSION)
872

    
873
  if constants.NV_HVINFO in what and vm_capable:
874
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
875
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
876

    
877
  if constants.NV_DRBDVERSION in what and vm_capable:
878
    try:
879
      drbd_version = DRBD8.GetProcInfo().GetVersionString()
880
    except errors.BlockDeviceError, err:
881
      logging.warning("Can't get DRBD version", exc_info=True)
882
      drbd_version = str(err)
883
    result[constants.NV_DRBDVERSION] = drbd_version
884

    
885
  if constants.NV_DRBDLIST in what and vm_capable:
886
    try:
887
      used_minors = drbd.DRBD8.GetUsedDevs()
888
    except errors.BlockDeviceError, err:
889
      logging.warning("Can't get used minors list", exc_info=True)
890
      used_minors = str(err)
891
    result[constants.NV_DRBDLIST] = used_minors
892

    
893
  if constants.NV_DRBDHELPER in what and vm_capable:
894
    status = True
895
    try:
896
      payload = drbd.DRBD8.GetUsermodeHelper()
897
    except errors.BlockDeviceError, err:
898
      logging.error("Can't get DRBD usermode helper: %s", str(err))
899
      status = False
900
      payload = str(err)
901
    result[constants.NV_DRBDHELPER] = (status, payload)
902

    
903
  if constants.NV_NODESETUP in what:
904
    result[constants.NV_NODESETUP] = tmpr = []
905
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
906
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
907
                  " under /sys, missing required directories /sys/block"
908
                  " and /sys/class/net")
909
    if (not os.path.isdir("/proc/sys") or
910
        not os.path.isfile("/proc/sysrq-trigger")):
911
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
912
                  " under /proc, missing required directory /proc/sys and"
913
                  " the file /proc/sysrq-trigger")
914

    
915
  if constants.NV_TIME in what:
916
    result[constants.NV_TIME] = utils.SplitTime(time.time())
917

    
918
  if constants.NV_OSLIST in what and vm_capable:
919
    result[constants.NV_OSLIST] = DiagnoseOS()
920

    
921
  if constants.NV_BRIDGES in what and vm_capable:
922
    result[constants.NV_BRIDGES] = [bridge
923
                                    for bridge in what[constants.NV_BRIDGES]
924
                                    if not utils.BridgeExists(bridge)]
925

    
926
  if what.get(constants.NV_FILE_STORAGE_PATHS) == my_name:
927
    result[constants.NV_FILE_STORAGE_PATHS] = \
928
      bdev.ComputeWrongFileStoragePaths()
929

    
930
  return result
931

    
932

    
933
def GetBlockDevSizes(devices):
934
  """Return the size of the given block devices
935

936
  @type devices: list
937
  @param devices: list of block device nodes to query
938
  @rtype: dict
939
  @return:
940
    dictionary of all block devices under /dev (key). The value is their
941
    size in MiB.
942

943
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
944

945
  """
946
  DEV_PREFIX = "/dev/"
947
  blockdevs = {}
948

    
949
  for devpath in devices:
950
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
951
      continue
952

    
953
    try:
954
      st = os.stat(devpath)
955
    except EnvironmentError, err:
956
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
957
      continue
958

    
959
    if stat.S_ISBLK(st.st_mode):
960
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
961
      if result.failed:
962
        # We don't want to fail, just do not list this device as available
963
        logging.warning("Cannot get size for block device %s", devpath)
964
        continue
965

    
966
      size = int(result.stdout) / (1024 * 1024)
967
      blockdevs[devpath] = size
968
  return blockdevs
969

    
970

    
971
def GetVolumeList(vg_names):
972
  """Compute list of logical volumes and their size.
973

974
  @type vg_names: list
975
  @param vg_names: the volume groups whose LVs we should list, or
976
      empty for all volume groups
977
  @rtype: dict
978
  @return:
979
      dictionary of all partions (key) with value being a tuple of
980
      their size (in MiB), inactive and online status::
981

982
        {'xenvg/test1': ('20.06', True, True)}
983

984
      in case of errors, a string is returned with the error
985
      details.
986

987
  """
988
  lvs = {}
989
  sep = "|"
990
  if not vg_names:
991
    vg_names = []
992
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
993
                         "--separator=%s" % sep,
994
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
995
  if result.failed:
996
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
997

    
998
  for line in result.stdout.splitlines():
999
    line = line.strip()
1000
    match = _LVSLINE_REGEX.match(line)
1001
    if not match:
1002
      logging.error("Invalid line returned from lvs output: '%s'", line)
1003
      continue
1004
    vg_name, name, size, attr = match.groups()
1005
    inactive = attr[4] == "-"
1006
    online = attr[5] == "o"
1007
    virtual = attr[0] == "v"
1008
    if virtual:
1009
      # we don't want to report such volumes as existing, since they
1010
      # don't really hold data
1011
      continue
1012
    lvs[vg_name + "/" + name] = (size, inactive, online)
1013

    
1014
  return lvs
1015

    
1016

    
1017
def ListVolumeGroups():
1018
  """List the volume groups and their size.
1019

1020
  @rtype: dict
1021
  @return: dictionary with keys volume name and values the
1022
      size of the volume
1023

1024
  """
1025
  return utils.ListVolumeGroups()
1026

    
1027

    
1028
def NodeVolumes():
1029
  """List all volumes on this node.
1030

1031
  @rtype: list
1032
  @return:
1033
    A list of dictionaries, each having four keys:
1034
      - name: the logical volume name,
1035
      - size: the size of the logical volume
1036
      - dev: the physical device on which the LV lives
1037
      - vg: the volume group to which it belongs
1038

1039
    In case of errors, we return an empty list and log the
1040
    error.
1041

1042
    Note that since a logical volume can live on multiple physical
1043
    volumes, the resulting list might include a logical volume
1044
    multiple times.
1045

1046
  """
1047
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1048
                         "--separator=|",
1049
                         "--options=lv_name,lv_size,devices,vg_name"])
1050
  if result.failed:
1051
    _Fail("Failed to list logical volumes, lvs output: %s",
1052
          result.output)
1053

    
1054
  def parse_dev(dev):
1055
    return dev.split("(")[0]
1056

    
1057
  def handle_dev(dev):
1058
    return [parse_dev(x) for x in dev.split(",")]
1059

    
1060
  def map_line(line):
1061
    line = [v.strip() for v in line]
1062
    return [{"name": line[0], "size": line[1],
1063
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
1064

    
1065
  all_devs = []
1066
  for line in result.stdout.splitlines():
1067
    if line.count("|") >= 3:
1068
      all_devs.extend(map_line(line.split("|")))
1069
    else:
1070
      logging.warning("Strange line in the output from lvs: '%s'", line)
1071
  return all_devs
1072

    
1073

    
1074
def BridgesExist(bridges_list):
1075
  """Check if a list of bridges exist on the current node.
1076

1077
  @rtype: boolean
1078
  @return: C{True} if all of them exist, C{False} otherwise
1079

1080
  """
1081
  missing = []
1082
  for bridge in bridges_list:
1083
    if not utils.BridgeExists(bridge):
1084
      missing.append(bridge)
1085

    
1086
  if missing:
1087
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
1088

    
1089

    
1090
def GetInstanceList(hypervisor_list):
1091
  """Provides a list of instances.
1092

1093
  @type hypervisor_list: list
1094
  @param hypervisor_list: the list of hypervisors to query information
1095

1096
  @rtype: list
1097
  @return: a list of all running instances on the current node
1098
    - instance1.example.com
1099
    - instance2.example.com
1100

1101
  """
1102
  results = []
1103
  for hname in hypervisor_list:
1104
    try:
1105
      names = hypervisor.GetHypervisor(hname).ListInstances()
1106
      results.extend(names)
1107
    except errors.HypervisorError, err:
1108
      _Fail("Error enumerating instances (hypervisor %s): %s",
1109
            hname, err, exc=True)
1110

    
1111
  return results
1112

    
1113

    
1114
def GetInstanceInfo(instance, hname):
1115
  """Gives back the information about an instance as a dictionary.
1116

1117
  @type instance: string
1118
  @param instance: the instance name
1119
  @type hname: string
1120
  @param hname: the hypervisor type of the instance
1121

1122
  @rtype: dict
1123
  @return: dictionary with the following keys:
1124
      - memory: memory size of instance (int)
1125
      - state: xen state of instance (string)
1126
      - time: cpu time of instance (float)
1127
      - vcpus: the number of vcpus (int)
1128

1129
  """
1130
  output = {}
1131

    
1132
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
1133
  if iinfo is not None:
1134
    output["memory"] = iinfo[2]
1135
    output["vcpus"] = iinfo[3]
1136
    output["state"] = iinfo[4]
1137
    output["time"] = iinfo[5]
1138

    
1139
  return output
1140

    
1141

    
1142
def GetInstanceMigratable(instance):
1143
  """Gives whether an instance can be migrated.
1144

1145
  @type instance: L{objects.Instance}
1146
  @param instance: object representing the instance to be checked.
1147

1148
  @rtype: tuple
1149
  @return: tuple of (result, description) where:
1150
      - result: whether the instance can be migrated or not
1151
      - description: a description of the issue, if relevant
1152

1153
  """
1154
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1155
  iname = instance.name
1156
  if iname not in hyper.ListInstances():
1157
    _Fail("Instance %s is not running", iname)
1158

    
1159
  for idx in range(len(instance.disks)):
1160
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1161
    if not os.path.islink(link_name):
1162
      logging.warning("Instance %s is missing symlink %s for disk %d",
1163
                      iname, link_name, idx)
1164

    
1165

    
1166
def GetAllInstancesInfo(hypervisor_list):
1167
  """Gather data about all instances.
1168

1169
  This is the equivalent of L{GetInstanceInfo}, except that it
1170
  computes data for all instances at once, thus being faster if one
1171
  needs data about more than one instance.
1172

1173
  @type hypervisor_list: list
1174
  @param hypervisor_list: list of hypervisors to query for instance data
1175

1176
  @rtype: dict
1177
  @return: dictionary of instance: data, with data having the following keys:
1178
      - memory: memory size of instance (int)
1179
      - state: xen state of instance (string)
1180
      - time: cpu time of instance (float)
1181
      - vcpus: the number of vcpus
1182

1183
  """
1184
  output = {}
1185

    
1186
  for hname in hypervisor_list:
1187
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
1188
    if iinfo:
1189
      for name, _, memory, vcpus, state, times in iinfo:
1190
        value = {
1191
          "memory": memory,
1192
          "vcpus": vcpus,
1193
          "state": state,
1194
          "time": times,
1195
          }
1196
        if name in output:
1197
          # we only check static parameters, like memory and vcpus,
1198
          # and not state and time which can change between the
1199
          # invocations of the different hypervisors
1200
          for key in "memory", "vcpus":
1201
            if value[key] != output[name][key]:
1202
              _Fail("Instance %s is running twice"
1203
                    " with different parameters", name)
1204
        output[name] = value
1205

    
1206
  return output
1207

    
1208

    
1209
def _InstanceLogName(kind, os_name, instance, component):
1210
  """Compute the OS log filename for a given instance and operation.
1211

1212
  The instance name and os name are passed in as strings since not all
1213
  operations have these as part of an instance object.
1214

1215
  @type kind: string
1216
  @param kind: the operation type (e.g. add, import, etc.)
1217
  @type os_name: string
1218
  @param os_name: the os name
1219
  @type instance: string
1220
  @param instance: the name of the instance being imported/added/etc.
1221
  @type component: string or None
1222
  @param component: the name of the component of the instance being
1223
      transferred
1224

1225
  """
1226
  # TODO: Use tempfile.mkstemp to create unique filename
1227
  if component:
1228
    assert "/" not in component
1229
    c_msg = "-%s" % component
1230
  else:
1231
    c_msg = ""
1232
  base = ("%s-%s-%s%s-%s.log" %
1233
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1234
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1235

    
1236

    
1237
def InstanceOsAdd(instance, reinstall, debug):
1238
  """Add an OS to an instance.
1239

1240
  @type instance: L{objects.Instance}
1241
  @param instance: Instance whose OS is to be installed
1242
  @type reinstall: boolean
1243
  @param reinstall: whether this is an instance reinstall
1244
  @type debug: integer
1245
  @param debug: debug level, passed to the OS scripts
1246
  @rtype: None
1247

1248
  """
1249
  inst_os = OSFromDisk(instance.os)
1250

    
1251
  create_env = OSEnvironment(instance, inst_os, debug)
1252
  if reinstall:
1253
    create_env["INSTANCE_REINSTALL"] = "1"
1254

    
1255
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1256

    
1257
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1258
                        cwd=inst_os.path, output=logfile, reset_env=True)
1259
  if result.failed:
1260
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1261
                  " output: %s", result.cmd, result.fail_reason, logfile,
1262
                  result.output)
1263
    lines = [utils.SafeEncode(val)
1264
             for val in utils.TailFile(logfile, lines=20)]
1265
    _Fail("OS create script failed (%s), last lines in the"
1266
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1267

    
1268

    
1269
def RunRenameInstance(instance, old_name, debug):
1270
  """Run the OS rename script for an instance.
1271

1272
  @type instance: L{objects.Instance}
1273
  @param instance: Instance whose OS is to be installed
1274
  @type old_name: string
1275
  @param old_name: previous instance name
1276
  @type debug: integer
1277
  @param debug: debug level, passed to the OS scripts
1278
  @rtype: boolean
1279
  @return: the success of the operation
1280

1281
  """
1282
  inst_os = OSFromDisk(instance.os)
1283

    
1284
  rename_env = OSEnvironment(instance, inst_os, debug)
1285
  rename_env["OLD_INSTANCE_NAME"] = old_name
1286

    
1287
  logfile = _InstanceLogName("rename", instance.os,
1288
                             "%s-%s" % (old_name, instance.name), None)
1289

    
1290
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1291
                        cwd=inst_os.path, output=logfile, reset_env=True)
1292

    
1293
  if result.failed:
1294
    logging.error("os create command '%s' returned error: %s output: %s",
1295
                  result.cmd, result.fail_reason, result.output)
1296
    lines = [utils.SafeEncode(val)
1297
             for val in utils.TailFile(logfile, lines=20)]
1298
    _Fail("OS rename script failed (%s), last lines in the"
1299
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1300

    
1301

    
1302
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1303
  """Returns symlink path for block device.
1304

1305
  """
1306
  if _dir is None:
1307
    _dir = pathutils.DISK_LINKS_DIR
1308

    
1309
  return utils.PathJoin(_dir,
1310
                        ("%s%s%s" %
1311
                         (instance_name, constants.DISK_SEPARATOR, idx)))
1312

    
1313

    
1314
def _SymlinkBlockDev(instance_name, device_path, idx):
1315
  """Set up symlinks to a instance's block device.
1316

1317
  This is an auxiliary function run when an instance is start (on the primary
1318
  node) or when an instance is migrated (on the target node).
1319

1320

1321
  @param instance_name: the name of the target instance
1322
  @param device_path: path of the physical block device, on the node
1323
  @param idx: the disk index
1324
  @return: absolute path to the disk's symlink
1325

1326
  """
1327
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1328
  try:
1329
    os.symlink(device_path, link_name)
1330
  except OSError, err:
1331
    if err.errno == errno.EEXIST:
1332
      if (not os.path.islink(link_name) or
1333
          os.readlink(link_name) != device_path):
1334
        os.remove(link_name)
1335
        os.symlink(device_path, link_name)
1336
    else:
1337
      raise
1338

    
1339
  return link_name
1340

    
1341

    
1342
def _RemoveBlockDevLinks(instance_name, disks):
1343
  """Remove the block device symlinks belonging to the given instance.
1344

1345
  """
1346
  for idx, _ in enumerate(disks):
1347
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1348
    if os.path.islink(link_name):
1349
      try:
1350
        os.remove(link_name)
1351
      except OSError:
1352
        logging.exception("Can't remove symlink '%s'", link_name)
1353

    
1354

    
1355
def _GatherAndLinkBlockDevs(instance):
1356
  """Set up an instance's block device(s).
1357

1358
  This is run on the primary node at instance startup. The block
1359
  devices must be already assembled.
1360

1361
  @type instance: L{objects.Instance}
1362
  @param instance: the instance whose disks we shoul assemble
1363
  @rtype: list
1364
  @return: list of (disk_object, device_path)
1365

1366
  """
1367
  block_devices = []
1368
  for idx, disk in enumerate(instance.disks):
1369
    device = _RecursiveFindBD(disk)
1370
    if device is None:
1371
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1372
                                    str(disk))
1373
    device.Open()
1374
    try:
1375
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1376
    except OSError, e:
1377
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1378
                                    e.strerror)
1379

    
1380
    block_devices.append((disk, link_name))
1381

    
1382
  return block_devices
1383

    
1384

    
1385
def StartInstance(instance, startup_paused, reason, store_reason=True):
1386
  """Start an instance.
1387

1388
  @type instance: L{objects.Instance}
1389
  @param instance: the instance object
1390
  @type startup_paused: bool
1391
  @param instance: pause instance at startup?
1392
  @type reason: list of reasons
1393
  @param reason: the reason trail for this startup
1394
  @type store_reason: boolean
1395
  @param store_reason: whether to store the shutdown reason trail on file
1396
  @rtype: None
1397

1398
  """
1399
  running_instances = GetInstanceList([instance.hypervisor])
1400

    
1401
  if instance.name in running_instances:
1402
    logging.info("Instance %s already running, not starting", instance.name)
1403
    return
1404

    
1405
  try:
1406
    block_devices = _GatherAndLinkBlockDevs(instance)
1407
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1408
    hyper.StartInstance(instance, block_devices, startup_paused)
1409
    if store_reason:
1410
      _StoreInstReasonTrail(instance.name, reason)
1411
  except errors.BlockDeviceError, err:
1412
    _Fail("Block device error: %s", err, exc=True)
1413
  except errors.HypervisorError, err:
1414
    _RemoveBlockDevLinks(instance.name, instance.disks)
1415
    _Fail("Hypervisor error: %s", err, exc=True)
1416

    
1417

    
1418
def InstanceShutdown(instance, timeout, reason, store_reason=True):
1419
  """Shut an instance down.
1420

1421
  @note: this functions uses polling with a hardcoded timeout.
1422

1423
  @type instance: L{objects.Instance}
1424
  @param instance: the instance object
1425
  @type timeout: integer
1426
  @param timeout: maximum timeout for soft shutdown
1427
  @type reason: list of reasons
1428
  @param reason: the reason trail for this shutdown
1429
  @type store_reason: boolean
1430
  @param store_reason: whether to store the shutdown reason trail on file
1431
  @rtype: None
1432

1433
  """
1434
  hv_name = instance.hypervisor
1435
  hyper = hypervisor.GetHypervisor(hv_name)
1436
  iname = instance.name
1437

    
1438
  if instance.name not in hyper.ListInstances():
1439
    logging.info("Instance %s not running, doing nothing", iname)
1440
    return
1441

    
1442
  class _TryShutdown:
1443
    def __init__(self):
1444
      self.tried_once = False
1445

    
1446
    def __call__(self):
1447
      if iname not in hyper.ListInstances():
1448
        return
1449

    
1450
      try:
1451
        hyper.StopInstance(instance, retry=self.tried_once)
1452
        if store_reason:
1453
          _StoreInstReasonTrail(instance.name, reason)
1454
      except errors.HypervisorError, err:
1455
        if iname not in hyper.ListInstances():
1456
          # if the instance is no longer existing, consider this a
1457
          # success and go to cleanup
1458
          return
1459

    
1460
        _Fail("Failed to stop instance %s: %s", iname, err)
1461

    
1462
      self.tried_once = True
1463

    
1464
      raise utils.RetryAgain()
1465

    
1466
  try:
1467
    utils.Retry(_TryShutdown(), 5, timeout)
1468
  except utils.RetryTimeout:
1469
    # the shutdown did not succeed
1470
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1471

    
1472
    try:
1473
      hyper.StopInstance(instance, force=True)
1474
    except errors.HypervisorError, err:
1475
      if iname in hyper.ListInstances():
1476
        # only raise an error if the instance still exists, otherwise
1477
        # the error could simply be "instance ... unknown"!
1478
        _Fail("Failed to force stop instance %s: %s", iname, err)
1479

    
1480
    time.sleep(1)
1481

    
1482
    if iname in hyper.ListInstances():
1483
      _Fail("Could not shutdown instance %s even by destroy", iname)
1484

    
1485
  try:
1486
    hyper.CleanupInstance(instance.name)
1487
  except errors.HypervisorError, err:
1488
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1489

    
1490
  _RemoveBlockDevLinks(iname, instance.disks)
1491

    
1492

    
1493
def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1494
  """Reboot an instance.
1495

1496
  @type instance: L{objects.Instance}
1497
  @param instance: the instance object to reboot
1498
  @type reboot_type: str
1499
  @param reboot_type: the type of reboot, one the following
1500
    constants:
1501
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1502
        instance OS, do not recreate the VM
1503
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1504
        restart the VM (at the hypervisor level)
1505
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1506
        not accepted here, since that mode is handled differently, in
1507
        cmdlib, and translates into full stop and start of the
1508
        instance (instead of a call_instance_reboot RPC)
1509
  @type shutdown_timeout: integer
1510
  @param shutdown_timeout: maximum timeout for soft shutdown
1511
  @type reason: list of reasons
1512
  @param reason: the reason trail for this reboot
1513
  @rtype: None
1514

1515
  """
1516
  running_instances = GetInstanceList([instance.hypervisor])
1517

    
1518
  if instance.name not in running_instances:
1519
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1520

    
1521
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1522
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1523
    try:
1524
      hyper.RebootInstance(instance)
1525
    except errors.HypervisorError, err:
1526
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1527
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1528
    try:
1529
      InstanceShutdown(instance, shutdown_timeout, reason, store_reason=False)
1530
      result = StartInstance(instance, False, reason, store_reason=False)
1531
      _StoreInstReasonTrail(instance.name, reason)
1532
      return result
1533
    except errors.HypervisorError, err:
1534
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1535
  else:
1536
    _Fail("Invalid reboot_type received: %s", reboot_type)
1537

    
1538

    
1539
def InstanceBalloonMemory(instance, memory):
1540
  """Resize an instance's memory.
1541

1542
  @type instance: L{objects.Instance}
1543
  @param instance: the instance object
1544
  @type memory: int
1545
  @param memory: new memory amount in MB
1546
  @rtype: None
1547

1548
  """
1549
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1550
  running = hyper.ListInstances()
1551
  if instance.name not in running:
1552
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1553
    return
1554
  try:
1555
    hyper.BalloonInstanceMemory(instance, memory)
1556
  except errors.HypervisorError, err:
1557
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1558

    
1559

    
1560
def MigrationInfo(instance):
1561
  """Gather information about an instance to be migrated.
1562

1563
  @type instance: L{objects.Instance}
1564
  @param instance: the instance definition
1565

1566
  """
1567
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1568
  try:
1569
    info = hyper.MigrationInfo(instance)
1570
  except errors.HypervisorError, err:
1571
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1572
  return info
1573

    
1574

    
1575
def AcceptInstance(instance, info, target):
1576
  """Prepare the node to accept an instance.
1577

1578
  @type instance: L{objects.Instance}
1579
  @param instance: the instance definition
1580
  @type info: string/data (opaque)
1581
  @param info: migration information, from the source node
1582
  @type target: string
1583
  @param target: target host (usually ip), on this node
1584

1585
  """
1586
  # TODO: why is this required only for DTS_EXT_MIRROR?
1587
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1588
    # Create the symlinks, as the disks are not active
1589
    # in any way
1590
    try:
1591
      _GatherAndLinkBlockDevs(instance)
1592
    except errors.BlockDeviceError, err:
1593
      _Fail("Block device error: %s", err, exc=True)
1594

    
1595
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1596
  try:
1597
    hyper.AcceptInstance(instance, info, target)
1598
  except errors.HypervisorError, err:
1599
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1600
      _RemoveBlockDevLinks(instance.name, instance.disks)
1601
    _Fail("Failed to accept instance: %s", err, exc=True)
1602

    
1603

    
1604
def FinalizeMigrationDst(instance, info, success):
1605
  """Finalize any preparation to accept an instance.
1606

1607
  @type instance: L{objects.Instance}
1608
  @param instance: the instance definition
1609
  @type info: string/data (opaque)
1610
  @param info: migration information, from the source node
1611
  @type success: boolean
1612
  @param success: whether the migration was a success or a failure
1613

1614
  """
1615
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1616
  try:
1617
    hyper.FinalizeMigrationDst(instance, info, success)
1618
  except errors.HypervisorError, err:
1619
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1620

    
1621

    
1622
def MigrateInstance(instance, target, live):
1623
  """Migrates an instance to another node.
1624

1625
  @type instance: L{objects.Instance}
1626
  @param instance: the instance definition
1627
  @type target: string
1628
  @param target: the target node name
1629
  @type live: boolean
1630
  @param live: whether the migration should be done live or not (the
1631
      interpretation of this parameter is left to the hypervisor)
1632
  @raise RPCFail: if migration fails for some reason
1633

1634
  """
1635
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1636

    
1637
  try:
1638
    hyper.MigrateInstance(instance, target, live)
1639
  except errors.HypervisorError, err:
1640
    _Fail("Failed to migrate instance: %s", err, exc=True)
1641

    
1642

    
1643
def FinalizeMigrationSource(instance, success, live):
1644
  """Finalize the instance migration on the source node.
1645

1646
  @type instance: L{objects.Instance}
1647
  @param instance: the instance definition of the migrated instance
1648
  @type success: bool
1649
  @param success: whether the migration succeeded or not
1650
  @type live: bool
1651
  @param live: whether the user requested a live migration or not
1652
  @raise RPCFail: If the execution fails for some reason
1653

1654
  """
1655
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1656

    
1657
  try:
1658
    hyper.FinalizeMigrationSource(instance, success, live)
1659
  except Exception, err:  # pylint: disable=W0703
1660
    _Fail("Failed to finalize the migration on the source node: %s", err,
1661
          exc=True)
1662

    
1663

    
1664
def GetMigrationStatus(instance):
1665
  """Get the migration status
1666

1667
  @type instance: L{objects.Instance}
1668
  @param instance: the instance that is being migrated
1669
  @rtype: L{objects.MigrationStatus}
1670
  @return: the status of the current migration (one of
1671
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1672
           progress info that can be retrieved from the hypervisor
1673
  @raise RPCFail: If the migration status cannot be retrieved
1674

1675
  """
1676
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1677
  try:
1678
    return hyper.GetMigrationStatus(instance)
1679
  except Exception, err:  # pylint: disable=W0703
1680
    _Fail("Failed to get migration status: %s", err, exc=True)
1681

    
1682

    
1683
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
1684
  """Creates a block device for an instance.
1685

1686
  @type disk: L{objects.Disk}
1687
  @param disk: the object describing the disk we should create
1688
  @type size: int
1689
  @param size: the size of the physical underlying device, in MiB
1690
  @type owner: str
1691
  @param owner: the name of the instance for which disk is created,
1692
      used for device cache data
1693
  @type on_primary: boolean
1694
  @param on_primary:  indicates if it is the primary node or not
1695
  @type info: string
1696
  @param info: string that will be sent to the physical device
1697
      creation, used for example to set (LVM) tags on LVs
1698
  @type excl_stor: boolean
1699
  @param excl_stor: Whether exclusive_storage is active
1700

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

1705
  """
1706
  # TODO: remove the obsolete "size" argument
1707
  # pylint: disable=W0613
1708
  clist = []
1709
  if disk.children:
1710
    for child in disk.children:
1711
      try:
1712
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1713
      except errors.BlockDeviceError, err:
1714
        _Fail("Can't assemble device %s: %s", child, err)
1715
      if on_primary or disk.AssembleOnSecondary():
1716
        # we need the children open in case the device itself has to
1717
        # be assembled
1718
        try:
1719
          # pylint: disable=E1103
1720
          crdev.Open()
1721
        except errors.BlockDeviceError, err:
1722
          _Fail("Can't make child '%s' read-write: %s", child, err)
1723
      clist.append(crdev)
1724

    
1725
  try:
1726
    device = bdev.Create(disk, clist, excl_stor)
1727
  except errors.BlockDeviceError, err:
1728
    _Fail("Can't create block device: %s", err)
1729

    
1730
  if on_primary or disk.AssembleOnSecondary():
1731
    try:
1732
      device.Assemble()
1733
    except errors.BlockDeviceError, err:
1734
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1735
    if on_primary or disk.OpenOnSecondary():
1736
      try:
1737
        device.Open(force=True)
1738
      except errors.BlockDeviceError, err:
1739
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1740
    DevCacheManager.UpdateCache(device.dev_path, owner,
1741
                                on_primary, disk.iv_name)
1742

    
1743
  device.SetInfo(info)
1744

    
1745
  return device.unique_id
1746

    
1747

    
1748
def _WipeDevice(path, offset, size):
1749
  """This function actually wipes the device.
1750

1751
  @param path: The path to the device to wipe
1752
  @param offset: The offset in MiB in the file
1753
  @param size: The size in MiB to write
1754

1755
  """
1756
  # Internal sizes are always in Mebibytes; if the following "dd" command
1757
  # should use a different block size the offset and size given to this
1758
  # function must be adjusted accordingly before being passed to "dd".
1759
  block_size = 1024 * 1024
1760

    
1761
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1762
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
1763
         "count=%d" % size]
1764
  result = utils.RunCmd(cmd)
1765

    
1766
  if result.failed:
1767
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1768
          result.fail_reason, result.output)
1769

    
1770

    
1771
def BlockdevWipe(disk, offset, size):
1772
  """Wipes a block device.
1773

1774
  @type disk: L{objects.Disk}
1775
  @param disk: the disk object we want to wipe
1776
  @type offset: int
1777
  @param offset: The offset in MiB in the file
1778
  @type size: int
1779
  @param size: The size in MiB to write
1780

1781
  """
1782
  try:
1783
    rdev = _RecursiveFindBD(disk)
1784
  except errors.BlockDeviceError:
1785
    rdev = None
1786

    
1787
  if not rdev:
1788
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1789

    
1790
  # Do cross verify some of the parameters
1791
  if offset < 0:
1792
    _Fail("Negative offset")
1793
  if size < 0:
1794
    _Fail("Negative size")
1795
  if offset > rdev.size:
1796
    _Fail("Offset is bigger than device size")
1797
  if (offset + size) > rdev.size:
1798
    _Fail("The provided offset and size to wipe is bigger than device size")
1799

    
1800
  _WipeDevice(rdev.dev_path, offset, size)
1801

    
1802

    
1803
def BlockdevPauseResumeSync(disks, pause):
1804
  """Pause or resume the sync of the block device.
1805

1806
  @type disks: list of L{objects.Disk}
1807
  @param disks: the disks object we want to pause/resume
1808
  @type pause: bool
1809
  @param pause: Wheater to pause or resume
1810

1811
  """
1812
  success = []
1813
  for disk in disks:
1814
    try:
1815
      rdev = _RecursiveFindBD(disk)
1816
    except errors.BlockDeviceError:
1817
      rdev = None
1818

    
1819
    if not rdev:
1820
      success.append((False, ("Cannot change sync for device %s:"
1821
                              " device not found" % disk.iv_name)))
1822
      continue
1823

    
1824
    result = rdev.PauseResumeSync(pause)
1825

    
1826
    if result:
1827
      success.append((result, None))
1828
    else:
1829
      if pause:
1830
        msg = "Pause"
1831
      else:
1832
        msg = "Resume"
1833
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1834

    
1835
  return success
1836

    
1837

    
1838
def BlockdevRemove(disk):
1839
  """Remove a block device.
1840

1841
  @note: This is intended to be called recursively.
1842

1843
  @type disk: L{objects.Disk}
1844
  @param disk: the disk object we should remove
1845
  @rtype: boolean
1846
  @return: the success of the operation
1847

1848
  """
1849
  msgs = []
1850
  try:
1851
    rdev = _RecursiveFindBD(disk)
1852
  except errors.BlockDeviceError, err:
1853
    # probably can't attach
1854
    logging.info("Can't attach to device %s in remove", disk)
1855
    rdev = None
1856
  if rdev is not None:
1857
    r_path = rdev.dev_path
1858
    try:
1859
      rdev.Remove()
1860
    except errors.BlockDeviceError, err:
1861
      msgs.append(str(err))
1862
    if not msgs:
1863
      DevCacheManager.RemoveCache(r_path)
1864

    
1865
  if disk.children:
1866
    for child in disk.children:
1867
      try:
1868
        BlockdevRemove(child)
1869
      except RPCFail, err:
1870
        msgs.append(str(err))
1871

    
1872
  if msgs:
1873
    _Fail("; ".join(msgs))
1874

    
1875

    
1876
def _RecursiveAssembleBD(disk, owner, as_primary):
1877
  """Activate a block device for an instance.
1878

1879
  This is run on the primary and secondary nodes for an instance.
1880

1881
  @note: this function is called recursively.
1882

1883
  @type disk: L{objects.Disk}
1884
  @param disk: the disk we try to assemble
1885
  @type owner: str
1886
  @param owner: the name of the instance which owns the disk
1887
  @type as_primary: boolean
1888
  @param as_primary: if we should make the block device
1889
      read/write
1890

1891
  @return: the assembled device or None (in case no device
1892
      was assembled)
1893
  @raise errors.BlockDeviceError: in case there is an error
1894
      during the activation of the children or the device
1895
      itself
1896

1897
  """
1898
  children = []
1899
  if disk.children:
1900
    mcn = disk.ChildrenNeeded()
1901
    if mcn == -1:
1902
      mcn = 0 # max number of Nones allowed
1903
    else:
1904
      mcn = len(disk.children) - mcn # max number of Nones
1905
    for chld_disk in disk.children:
1906
      try:
1907
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1908
      except errors.BlockDeviceError, err:
1909
        if children.count(None) >= mcn:
1910
          raise
1911
        cdev = None
1912
        logging.error("Error in child activation (but continuing): %s",
1913
                      str(err))
1914
      children.append(cdev)
1915

    
1916
  if as_primary or disk.AssembleOnSecondary():
1917
    r_dev = bdev.Assemble(disk, children)
1918
    result = r_dev
1919
    if as_primary or disk.OpenOnSecondary():
1920
      r_dev.Open()
1921
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1922
                                as_primary, disk.iv_name)
1923

    
1924
  else:
1925
    result = True
1926
  return result
1927

    
1928

    
1929
def BlockdevAssemble(disk, owner, as_primary, idx):
1930
  """Activate a block device for an instance.
1931

1932
  This is a wrapper over _RecursiveAssembleBD.
1933

1934
  @rtype: str or boolean
1935
  @return: a C{/dev/...} path for primary nodes, and
1936
      C{True} for secondary nodes
1937

1938
  """
1939
  try:
1940
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1941
    if isinstance(result, BlockDev):
1942
      # pylint: disable=E1103
1943
      result = result.dev_path
1944
      if as_primary:
1945
        _SymlinkBlockDev(owner, result, idx)
1946
  except errors.BlockDeviceError, err:
1947
    _Fail("Error while assembling disk: %s", err, exc=True)
1948
  except OSError, err:
1949
    _Fail("Error while symlinking disk: %s", err, exc=True)
1950

    
1951
  return result
1952

    
1953

    
1954
def BlockdevShutdown(disk):
1955
  """Shut down a block device.
1956

1957
  First, if the device is assembled (Attach() is successful), then
1958
  the device is shutdown. Then the children of the device are
1959
  shutdown.
1960

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

1965
  @type disk: L{objects.Disk}
1966
  @param disk: the description of the disk we should
1967
      shutdown
1968
  @rtype: None
1969

1970
  """
1971
  msgs = []
1972
  r_dev = _RecursiveFindBD(disk)
1973
  if r_dev is not None:
1974
    r_path = r_dev.dev_path
1975
    try:
1976
      r_dev.Shutdown()
1977
      DevCacheManager.RemoveCache(r_path)
1978
    except errors.BlockDeviceError, err:
1979
      msgs.append(str(err))
1980

    
1981
  if disk.children:
1982
    for child in disk.children:
1983
      try:
1984
        BlockdevShutdown(child)
1985
      except RPCFail, err:
1986
        msgs.append(str(err))
1987

    
1988
  if msgs:
1989
    _Fail("; ".join(msgs))
1990

    
1991

    
1992
def BlockdevAddchildren(parent_cdev, new_cdevs):
1993
  """Extend a mirrored block device.
1994

1995
  @type parent_cdev: L{objects.Disk}
1996
  @param parent_cdev: the disk to which we should add children
1997
  @type new_cdevs: list of L{objects.Disk}
1998
  @param new_cdevs: the list of children which we should add
1999
  @rtype: None
2000

2001
  """
2002
  parent_bdev = _RecursiveFindBD(parent_cdev)
2003
  if parent_bdev is None:
2004
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
2005
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
2006
  if new_bdevs.count(None) > 0:
2007
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
2008
  parent_bdev.AddChildren(new_bdevs)
2009

    
2010

    
2011
def BlockdevRemovechildren(parent_cdev, new_cdevs):
2012
  """Shrink a mirrored block device.
2013

2014
  @type parent_cdev: L{objects.Disk}
2015
  @param parent_cdev: the disk from which we should remove children
2016
  @type new_cdevs: list of L{objects.Disk}
2017
  @param new_cdevs: the list of children which we should remove
2018
  @rtype: None
2019

2020
  """
2021
  parent_bdev = _RecursiveFindBD(parent_cdev)
2022
  if parent_bdev is None:
2023
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
2024
  devs = []
2025
  for disk in new_cdevs:
2026
    rpath = disk.StaticDevPath()
2027
    if rpath is None:
2028
      bd = _RecursiveFindBD(disk)
2029
      if bd is None:
2030
        _Fail("Can't find device %s while removing children", disk)
2031
      else:
2032
        devs.append(bd.dev_path)
2033
    else:
2034
      if not utils.IsNormAbsPath(rpath):
2035
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
2036
      devs.append(rpath)
2037
  parent_bdev.RemoveChildren(devs)
2038

    
2039

    
2040
def BlockdevGetmirrorstatus(disks):
2041
  """Get the mirroring status of a list of devices.
2042

2043
  @type disks: list of L{objects.Disk}
2044
  @param disks: the list of disks which we should query
2045
  @rtype: disk
2046
  @return: List of L{objects.BlockDevStatus}, one for each disk
2047
  @raise errors.BlockDeviceError: if any of the disks cannot be
2048
      found
2049

2050
  """
2051
  stats = []
2052
  for dsk in disks:
2053
    rbd = _RecursiveFindBD(dsk)
2054
    if rbd is None:
2055
      _Fail("Can't find device %s", dsk)
2056

    
2057
    stats.append(rbd.CombinedSyncStatus())
2058

    
2059
  return stats
2060

    
2061

    
2062
def BlockdevGetmirrorstatusMulti(disks):
2063
  """Get the mirroring status of a list of devices.
2064

2065
  @type disks: list of L{objects.Disk}
2066
  @param disks: the list of disks which we should query
2067
  @rtype: disk
2068
  @return: List of tuples, (bool, status), one for each disk; bool denotes
2069
    success/failure, status is L{objects.BlockDevStatus} on success, string
2070
    otherwise
2071

2072
  """
2073
  result = []
2074
  for disk in disks:
2075
    try:
2076
      rbd = _RecursiveFindBD(disk)
2077
      if rbd is None:
2078
        result.append((False, "Can't find device %s" % disk))
2079
        continue
2080

    
2081
      status = rbd.CombinedSyncStatus()
2082
    except errors.BlockDeviceError, err:
2083
      logging.exception("Error while getting disk status")
2084
      result.append((False, str(err)))
2085
    else:
2086
      result.append((True, status))
2087

    
2088
  assert len(disks) == len(result)
2089

    
2090
  return result
2091

    
2092

    
2093
def _RecursiveFindBD(disk):
2094
  """Check if a device is activated.
2095

2096
  If so, return information about the real device.
2097

2098
  @type disk: L{objects.Disk}
2099
  @param disk: the disk object we need to find
2100

2101
  @return: None if the device can't be found,
2102
      otherwise the device instance
2103

2104
  """
2105
  children = []
2106
  if disk.children:
2107
    for chdisk in disk.children:
2108
      children.append(_RecursiveFindBD(chdisk))
2109

    
2110
  return bdev.FindDevice(disk, children)
2111

    
2112

    
2113
def _OpenRealBD(disk):
2114
  """Opens the underlying block device of a disk.
2115

2116
  @type disk: L{objects.Disk}
2117
  @param disk: the disk object we want to open
2118

2119
  """
2120
  real_disk = _RecursiveFindBD(disk)
2121
  if real_disk is None:
2122
    _Fail("Block device '%s' is not set up", disk)
2123

    
2124
  real_disk.Open()
2125

    
2126
  return real_disk
2127

    
2128

    
2129
def BlockdevFind(disk):
2130
  """Check if a device is activated.
2131

2132
  If it is, return information about the real device.
2133

2134
  @type disk: L{objects.Disk}
2135
  @param disk: the disk to find
2136
  @rtype: None or objects.BlockDevStatus
2137
  @return: None if the disk cannot be found, otherwise a the current
2138
           information
2139

2140
  """
2141
  try:
2142
    rbd = _RecursiveFindBD(disk)
2143
  except errors.BlockDeviceError, err:
2144
    _Fail("Failed to find device: %s", err, exc=True)
2145

    
2146
  if rbd is None:
2147
    return None
2148

    
2149
  return rbd.GetSyncStatus()
2150

    
2151

    
2152
def BlockdevGetdimensions(disks):
2153
  """Computes the size of the given disks.
2154

2155
  If a disk is not found, returns None instead.
2156

2157
  @type disks: list of L{objects.Disk}
2158
  @param disks: the list of disk to compute the size for
2159
  @rtype: list
2160
  @return: list with elements None if the disk cannot be found,
2161
      otherwise the pair (size, spindles), where spindles is None if the
2162
      device doesn't support that
2163

2164
  """
2165
  result = []
2166
  for cf in disks:
2167
    try:
2168
      rbd = _RecursiveFindBD(cf)
2169
    except errors.BlockDeviceError:
2170
      result.append(None)
2171
      continue
2172
    if rbd is None:
2173
      result.append(None)
2174
    else:
2175
      result.append(rbd.GetActualDimensions())
2176
  return result
2177

    
2178

    
2179
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2180
  """Export a block device to a remote node.
2181

2182
  @type disk: L{objects.Disk}
2183
  @param disk: the description of the disk to export
2184
  @type dest_node: str
2185
  @param dest_node: the destination node to export to
2186
  @type dest_path: str
2187
  @param dest_path: the destination path on the target node
2188
  @type cluster_name: str
2189
  @param cluster_name: the cluster name, needed for SSH hostalias
2190
  @rtype: None
2191

2192
  """
2193
  real_disk = _OpenRealBD(disk)
2194

    
2195
  # the block size on the read dd is 1MiB to match our units
2196
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2197
                               "dd if=%s bs=1048576 count=%s",
2198
                               real_disk.dev_path, str(disk.size))
2199

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

    
2209
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2210
                                                   constants.SSH_LOGIN_USER,
2211
                                                   destcmd)
2212

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

    
2216
  result = utils.RunCmd(["bash", "-c", command])
2217

    
2218
  if result.failed:
2219
    _Fail("Disk copy command '%s' returned error: %s"
2220
          " output: %s", command, result.fail_reason, result.output)
2221

    
2222

    
2223
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2224
  """Write a file to the filesystem.
2225

2226
  This allows the master to overwrite(!) a file. It will only perform
2227
  the operation if the file belongs to a list of configuration files.
2228

2229
  @type file_name: str
2230
  @param file_name: the target file name
2231
  @type data: str
2232
  @param data: the new contents of the file
2233
  @type mode: int
2234
  @param mode: the mode to give the file (can be None)
2235
  @type uid: string
2236
  @param uid: the owner of the file
2237
  @type gid: string
2238
  @param gid: the group of the file
2239
  @type atime: float
2240
  @param atime: the atime to set on the file (can be None)
2241
  @type mtime: float
2242
  @param mtime: the mtime to set on the file (can be None)
2243
  @rtype: None
2244

2245
  """
2246
  file_name = vcluster.LocalizeVirtualPath(file_name)
2247

    
2248
  if not os.path.isabs(file_name):
2249
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2250

    
2251
  if file_name not in _ALLOWED_UPLOAD_FILES:
2252
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2253
          file_name)
2254

    
2255
  raw_data = _Decompress(data)
2256

    
2257
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2258
    _Fail("Invalid username/groupname type")
2259

    
2260
  getents = runtime.GetEnts()
2261
  uid = getents.LookupUser(uid)
2262
  gid = getents.LookupGroup(gid)
2263

    
2264
  utils.SafeWriteFile(file_name, None,
2265
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2266
                      atime=atime, mtime=mtime)
2267

    
2268

    
2269
def RunOob(oob_program, command, node, timeout):
2270
  """Executes oob_program with given command on given node.
2271

2272
  @param oob_program: The path to the executable oob_program
2273
  @param command: The command to invoke on oob_program
2274
  @param node: The node given as an argument to the program
2275
  @param timeout: Timeout after which we kill the oob program
2276

2277
  @return: stdout
2278
  @raise RPCFail: If execution fails for some reason
2279

2280
  """
2281
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2282

    
2283
  if result.failed:
2284
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2285
          result.fail_reason, result.output)
2286

    
2287
  return result.stdout
2288

    
2289

    
2290
def _OSOndiskAPIVersion(os_dir):
2291
  """Compute and return the API version of a given OS.
2292

2293
  This function will try to read the API version of the OS residing in
2294
  the 'os_dir' directory.
2295

2296
  @type os_dir: str
2297
  @param os_dir: the directory in which we should look for the OS
2298
  @rtype: tuple
2299
  @return: tuple (status, data) with status denoting the validity and
2300
      data holding either the vaid versions or an error message
2301

2302
  """
2303
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2304

    
2305
  try:
2306
    st = os.stat(api_file)
2307
  except EnvironmentError, err:
2308
    return False, ("Required file '%s' not found under path %s: %s" %
2309
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2310

    
2311
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2312
    return False, ("File '%s' in %s is not a regular file" %
2313
                   (constants.OS_API_FILE, os_dir))
2314

    
2315
  try:
2316
    api_versions = utils.ReadFile(api_file).splitlines()
2317
  except EnvironmentError, err:
2318
    return False, ("Error while reading the API version file at %s: %s" %
2319
                   (api_file, utils.ErrnoOrStr(err)))
2320

    
2321
  try:
2322
    api_versions = [int(version.strip()) for version in api_versions]
2323
  except (TypeError, ValueError), err:
2324
    return False, ("API version(s) can't be converted to integer: %s" %
2325
                   str(err))
2326

    
2327
  return True, api_versions
2328

    
2329

    
2330
def DiagnoseOS(top_dirs=None):
2331
  """Compute the validity for all OSes.
2332

2333
  @type top_dirs: list
2334
  @param top_dirs: the list of directories in which to
2335
      search (if not given defaults to
2336
      L{pathutils.OS_SEARCH_PATH})
2337
  @rtype: list of L{objects.OS}
2338
  @return: a list of tuples (name, path, status, diagnose, variants,
2339
      parameters, api_version) for all (potential) OSes under all
2340
      search paths, where:
2341
          - name is the (potential) OS name
2342
          - path is the full path to the OS
2343
          - status True/False is the validity of the OS
2344
          - diagnose is the error message for an invalid OS, otherwise empty
2345
          - variants is a list of supported OS variants, if any
2346
          - parameters is a list of (name, help) parameters, if any
2347
          - api_version is a list of support OS API versions
2348

2349
  """
2350
  if top_dirs is None:
2351
    top_dirs = pathutils.OS_SEARCH_PATH
2352

    
2353
  result = []
2354
  for dir_name in top_dirs:
2355
    if os.path.isdir(dir_name):
2356
      try:
2357
        f_names = utils.ListVisibleFiles(dir_name)
2358
      except EnvironmentError, err:
2359
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2360
        break
2361
      for name in f_names:
2362
        os_path = utils.PathJoin(dir_name, name)
2363
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2364
        if status:
2365
          diagnose = ""
2366
          variants = os_inst.supported_variants
2367
          parameters = os_inst.supported_parameters
2368
          api_versions = os_inst.api_versions
2369
        else:
2370
          diagnose = os_inst
2371
          variants = parameters = api_versions = []
2372
        result.append((name, os_path, status, diagnose, variants,
2373
                       parameters, api_versions))
2374

    
2375
  return result
2376

    
2377

    
2378
def _TryOSFromDisk(name, base_dir=None):
2379
  """Create an OS instance from disk.
2380

2381
  This function will return an OS instance if the given name is a
2382
  valid OS name.
2383

2384
  @type base_dir: string
2385
  @keyword base_dir: Base directory containing OS installations.
2386
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2387
  @rtype: tuple
2388
  @return: success and either the OS instance if we find a valid one,
2389
      or error message
2390

2391
  """
2392
  if base_dir is None:
2393
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2394
  else:
2395
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2396

    
2397
  if os_dir is None:
2398
    return False, "Directory for OS %s not found in search path" % name
2399

    
2400
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2401
  if not status:
2402
    # push the error up
2403
    return status, api_versions
2404

    
2405
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2406
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2407
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2408

    
2409
  # OS Files dictionary, we will populate it with the absolute path
2410
  # names; if the value is True, then it is a required file, otherwise
2411
  # an optional one
2412
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2413

    
2414
  if max(api_versions) >= constants.OS_API_V15:
2415
    os_files[constants.OS_VARIANTS_FILE] = False
2416

    
2417
  if max(api_versions) >= constants.OS_API_V20:
2418
    os_files[constants.OS_PARAMETERS_FILE] = True
2419
  else:
2420
    del os_files[constants.OS_SCRIPT_VERIFY]
2421

    
2422
  for (filename, required) in os_files.items():
2423
    os_files[filename] = utils.PathJoin(os_dir, filename)
2424

    
2425
    try:
2426
      st = os.stat(os_files[filename])
2427
    except EnvironmentError, err:
2428
      if err.errno == errno.ENOENT and not required:
2429
        del os_files[filename]
2430
        continue
2431
      return False, ("File '%s' under path '%s' is missing (%s)" %
2432
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2433

    
2434
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2435
      return False, ("File '%s' under path '%s' is not a regular file" %
2436
                     (filename, os_dir))
2437

    
2438
    if filename in constants.OS_SCRIPTS:
2439
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2440
        return False, ("File '%s' under path '%s' is not executable" %
2441
                       (filename, os_dir))
2442

    
2443
  variants = []
2444
  if constants.OS_VARIANTS_FILE in os_files:
2445
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2446
    try:
2447
      variants = \
2448
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2449
    except EnvironmentError, err:
2450
      # we accept missing files, but not other errors
2451
      if err.errno != errno.ENOENT:
2452
        return False, ("Error while reading the OS variants file at %s: %s" %
2453
                       (variants_file, utils.ErrnoOrStr(err)))
2454

    
2455
  parameters = []
2456
  if constants.OS_PARAMETERS_FILE in os_files:
2457
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2458
    try:
2459
      parameters = utils.ReadFile(parameters_file).splitlines()
2460
    except EnvironmentError, err:
2461
      return False, ("Error while reading the OS parameters file at %s: %s" %
2462
                     (parameters_file, utils.ErrnoOrStr(err)))
2463
    parameters = [v.split(None, 1) for v in parameters]
2464

    
2465
  os_obj = objects.OS(name=name, path=os_dir,
2466
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2467
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2468
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2469
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2470
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2471
                                                 None),
2472
                      supported_variants=variants,
2473
                      supported_parameters=parameters,
2474
                      api_versions=api_versions)
2475
  return True, os_obj
2476

    
2477

    
2478
def OSFromDisk(name, base_dir=None):
2479
  """Create an OS instance from disk.
2480

2481
  This function will return an OS instance if the given name is a
2482
  valid OS name. Otherwise, it will raise an appropriate
2483
  L{RPCFail} exception, detailing why this is not a valid OS.
2484

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

2488
  @type base_dir: string
2489
  @keyword base_dir: Base directory containing OS installations.
2490
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2491
  @rtype: L{objects.OS}
2492
  @return: the OS instance if we find a valid one
2493
  @raise RPCFail: if we don't find a valid OS
2494

2495
  """
2496
  name_only = objects.OS.GetName(name)
2497
  status, payload = _TryOSFromDisk(name_only, base_dir)
2498

    
2499
  if not status:
2500
    _Fail(payload)
2501

    
2502
  return payload
2503

    
2504

    
2505
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2506
  """Calculate the basic environment for an os script.
2507

2508
  @type os_name: str
2509
  @param os_name: full operating system name (including variant)
2510
  @type inst_os: L{objects.OS}
2511
  @param inst_os: operating system for which the environment is being built
2512
  @type os_params: dict
2513
  @param os_params: the OS parameters
2514
  @type debug: integer
2515
  @param debug: debug level (0 or 1, for OS Api 10)
2516
  @rtype: dict
2517
  @return: dict of environment variables
2518
  @raise errors.BlockDeviceError: if the block device
2519
      cannot be found
2520

2521
  """
2522
  result = {}
2523
  api_version = \
2524
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2525
  result["OS_API_VERSION"] = "%d" % api_version
2526
  result["OS_NAME"] = inst_os.name
2527
  result["DEBUG_LEVEL"] = "%d" % debug
2528

    
2529
  # OS variants
2530
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2531
    variant = objects.OS.GetVariant(os_name)
2532
    if not variant:
2533
      variant = inst_os.supported_variants[0]
2534
  else:
2535
    variant = ""
2536
  result["OS_VARIANT"] = variant
2537

    
2538
  # OS params
2539
  for pname, pvalue in os_params.items():
2540
    result["OSP_%s" % pname.upper()] = pvalue
2541

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

    
2547
  return result
2548

    
2549

    
2550
def OSEnvironment(instance, inst_os, debug=0):
2551
  """Calculate the environment for an os script.
2552

2553
  @type instance: L{objects.Instance}
2554
  @param instance: target instance for the os script run
2555
  @type inst_os: L{objects.OS}
2556
  @param inst_os: operating system for which the environment is being built
2557
  @type debug: integer
2558
  @param debug: debug level (0 or 1, for OS Api 10)
2559
  @rtype: dict
2560
  @return: dict of environment variables
2561
  @raise errors.BlockDeviceError: if the block device
2562
      cannot be found
2563

2564
  """
2565
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2566

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

    
2570
  result["HYPERVISOR"] = instance.hypervisor
2571
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2572
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2573
  result["INSTANCE_SECONDARY_NODES"] = \
2574
      ("%s" % " ".join(instance.secondary_nodes))
2575

    
2576
  # Disks
2577
  for idx, disk in enumerate(instance.disks):
2578
    real_disk = _OpenRealBD(disk)
2579
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2580
    result["DISK_%d_ACCESS" % idx] = disk.mode
2581
    if constants.HV_DISK_TYPE in instance.hvparams:
2582
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2583
        instance.hvparams[constants.HV_DISK_TYPE]
2584
    if disk.dev_type in constants.LDS_BLOCK:
2585
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2586
    elif disk.dev_type == constants.LD_FILE:
2587
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2588
        "file:%s" % disk.physical_id[0]
2589

    
2590
  # NICs
2591
  for idx, nic in enumerate(instance.nics):
2592
    result["NIC_%d_MAC" % idx] = nic.mac
2593
    if nic.ip:
2594
      result["NIC_%d_IP" % idx] = nic.ip
2595
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2596
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2597
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2598
    if nic.nicparams[constants.NIC_LINK]:
2599
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2600
    if nic.netinfo:
2601
      nobj = objects.Network.FromDict(nic.netinfo)
2602
      result.update(nobj.HooksDict("NIC_%d_" % idx))
2603
    if constants.HV_NIC_TYPE in instance.hvparams:
2604
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2605
        instance.hvparams[constants.HV_NIC_TYPE]
2606

    
2607
  # HV/BE params
2608
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2609
    for key, value in source.items():
2610
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2611

    
2612
  return result
2613

    
2614

    
2615
def DiagnoseExtStorage(top_dirs=None):
2616
  """Compute the validity for all ExtStorage Providers.
2617

2618
  @type top_dirs: list
2619
  @param top_dirs: the list of directories in which to
2620
      search (if not given defaults to
2621
      L{pathutils.ES_SEARCH_PATH})
2622
  @rtype: list of L{objects.ExtStorage}
2623
  @return: a list of tuples (name, path, status, diagnose, parameters)
2624
      for all (potential) ExtStorage Providers under all
2625
      search paths, where:
2626
          - name is the (potential) ExtStorage Provider
2627
          - path is the full path to the ExtStorage Provider
2628
          - status True/False is the validity of the ExtStorage Provider
2629
          - diagnose is the error message for an invalid ExtStorage Provider,
2630
            otherwise empty
2631
          - parameters is a list of (name, help) parameters, if any
2632

2633
  """
2634
  if top_dirs is None:
2635
    top_dirs = pathutils.ES_SEARCH_PATH
2636

    
2637
  result = []
2638
  for dir_name in top_dirs:
2639
    if os.path.isdir(dir_name):
2640
      try:
2641
        f_names = utils.ListVisibleFiles(dir_name)
2642
      except EnvironmentError, err:
2643
        logging.exception("Can't list the ExtStorage directory %s: %s",
2644
                          dir_name, err)
2645
        break
2646
      for name in f_names:
2647
        es_path = utils.PathJoin(dir_name, name)
2648
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2649
        if status:
2650
          diagnose = ""
2651
          parameters = es_inst.supported_parameters
2652
        else:
2653
          diagnose = es_inst
2654
          parameters = []
2655
        result.append((name, es_path, status, diagnose, parameters))
2656

    
2657
  return result
2658

    
2659

    
2660
def BlockdevGrow(disk, amount, dryrun, backingstore):
2661
  """Grow a stack of block devices.
2662

2663
  This function is called recursively, with the childrens being the
2664
  first ones to resize.
2665

2666
  @type disk: L{objects.Disk}
2667
  @param disk: the disk to be grown
2668
  @type amount: integer
2669
  @param amount: the amount (in mebibytes) to grow with
2670
  @type dryrun: boolean
2671
  @param dryrun: whether to execute the operation in simulation mode
2672
      only, without actually increasing the size
2673
  @param backingstore: whether to execute the operation on backing storage
2674
      only, or on "logical" storage only; e.g. DRBD is logical storage,
2675
      whereas LVM, file, RBD are backing storage
2676
  @rtype: (status, result)
2677
  @return: a tuple with the status of the operation (True/False), and
2678
      the errors message if status is False
2679

2680
  """
2681
  r_dev = _RecursiveFindBD(disk)
2682
  if r_dev is None:
2683
    _Fail("Cannot find block device %s", disk)
2684

    
2685
  try:
2686
    r_dev.Grow(amount, dryrun, backingstore)
2687
  except errors.BlockDeviceError, err:
2688
    _Fail("Failed to grow block device: %s", err, exc=True)
2689

    
2690

    
2691
def BlockdevSnapshot(disk):
2692
  """Create a snapshot copy of a block device.
2693

2694
  This function is called recursively, and the snapshot is actually created
2695
  just for the leaf lvm backend device.
2696

2697
  @type disk: L{objects.Disk}
2698
  @param disk: the disk to be snapshotted
2699
  @rtype: string
2700
  @return: snapshot disk ID as (vg, lv)
2701

2702
  """
2703
  if disk.dev_type == constants.LD_DRBD8:
2704
    if not disk.children:
2705
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2706
            disk.unique_id)
2707
    return BlockdevSnapshot(disk.children[0])
2708
  elif disk.dev_type == constants.LD_LV:
2709
    r_dev = _RecursiveFindBD(disk)
2710
    if r_dev is not None:
2711
      # FIXME: choose a saner value for the snapshot size
2712
      # let's stay on the safe side and ask for the full size, for now
2713
      return r_dev.Snapshot(disk.size)
2714
    else:
2715
      _Fail("Cannot find block device %s", disk)
2716
  else:
2717
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2718
          disk.unique_id, disk.dev_type)
2719

    
2720

    
2721
def BlockdevSetInfo(disk, info):
2722
  """Sets 'metadata' information on block devices.
2723

2724
  This function sets 'info' metadata on block devices. Initial
2725
  information is set at device creation; this function should be used
2726
  for example after renames.
2727

2728
  @type disk: L{objects.Disk}
2729
  @param disk: the disk to be grown
2730
  @type info: string
2731
  @param info: new 'info' metadata
2732
  @rtype: (status, result)
2733
  @return: a tuple with the status of the operation (True/False), and
2734
      the errors message if status is False
2735

2736
  """
2737
  r_dev = _RecursiveFindBD(disk)
2738
  if r_dev is None:
2739
    _Fail("Cannot find block device %s", disk)
2740

    
2741
  try:
2742
    r_dev.SetInfo(info)
2743
  except errors.BlockDeviceError, err:
2744
    _Fail("Failed to set information on block device: %s", err, exc=True)
2745

    
2746

    
2747
def FinalizeExport(instance, snap_disks):
2748
  """Write out the export configuration information.
2749

2750
  @type instance: L{objects.Instance}
2751
  @param instance: the instance which we export, used for
2752
      saving configuration
2753
  @type snap_disks: list of L{objects.Disk}
2754
  @param snap_disks: list of snapshot block devices, which
2755
      will be used to get the actual name of the dump file
2756

2757
  @rtype: None
2758

2759
  """
2760
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
2761
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
2762

    
2763
  config = objects.SerializableConfigParser()
2764

    
2765
  config.add_section(constants.INISECT_EXP)
2766
  config.set(constants.INISECT_EXP, "version", "0")
2767
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2768
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2769
  config.set(constants.INISECT_EXP, "os", instance.os)
2770
  config.set(constants.INISECT_EXP, "compression", "none")
2771

    
2772
  config.add_section(constants.INISECT_INS)
2773
  config.set(constants.INISECT_INS, "name", instance.name)
2774
  config.set(constants.INISECT_INS, "maxmem", "%d" %
2775
             instance.beparams[constants.BE_MAXMEM])
2776
  config.set(constants.INISECT_INS, "minmem", "%d" %
2777
             instance.beparams[constants.BE_MINMEM])
2778
  # "memory" is deprecated, but useful for exporting to old ganeti versions
2779
  config.set(constants.INISECT_INS, "memory", "%d" %
2780
             instance.beparams[constants.BE_MAXMEM])
2781
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2782
             instance.beparams[constants.BE_VCPUS])
2783
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2784
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2785
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2786

    
2787
  nic_total = 0
2788
  for nic_count, nic in enumerate(instance.nics):
2789
    nic_total += 1
2790
    config.set(constants.INISECT_INS, "nic%d_mac" %
2791
               nic_count, "%s" % nic.mac)
2792
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2793
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
2794
               "%s" % nic.network)
2795
    for param in constants.NICS_PARAMETER_TYPES:
2796
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2797
                 "%s" % nic.nicparams.get(param, None))
2798
  # TODO: redundant: on load can read nics until it doesn't exist
2799
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2800

    
2801
  disk_total = 0
2802
  for disk_count, disk in enumerate(snap_disks):
2803
    if disk:
2804
      disk_total += 1
2805
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2806
                 ("%s" % disk.iv_name))
2807
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2808
                 ("%s" % disk.physical_id[1]))
2809
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2810
                 ("%d" % disk.size))
2811

    
2812
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2813

    
2814
  # New-style hypervisor/backend parameters
2815

    
2816
  config.add_section(constants.INISECT_HYP)
2817
  for name, value in instance.hvparams.items():
2818
    if name not in constants.HVC_GLOBALS:
2819
      config.set(constants.INISECT_HYP, name, str(value))
2820

    
2821
  config.add_section(constants.INISECT_BEP)
2822
  for name, value in instance.beparams.items():
2823
    config.set(constants.INISECT_BEP, name, str(value))
2824

    
2825
  config.add_section(constants.INISECT_OSP)
2826
  for name, value in instance.osparams.items():
2827
    config.set(constants.INISECT_OSP, name, str(value))
2828

    
2829
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2830
                  data=config.Dumps())
2831
  shutil.rmtree(finaldestdir, ignore_errors=True)
2832
  shutil.move(destdir, finaldestdir)
2833

    
2834

    
2835
def ExportInfo(dest):
2836
  """Get export configuration information.
2837

2838
  @type dest: str
2839
  @param dest: directory containing the export
2840

2841
  @rtype: L{objects.SerializableConfigParser}
2842
  @return: a serializable config file containing the
2843
      export info
2844

2845
  """
2846
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2847

    
2848
  config = objects.SerializableConfigParser()
2849
  config.read(cff)
2850

    
2851
  if (not config.has_section(constants.INISECT_EXP) or
2852
      not config.has_section(constants.INISECT_INS)):
2853
    _Fail("Export info file doesn't have the required fields")
2854

    
2855
  return config.Dumps()
2856

    
2857

    
2858
def ListExports():
2859
  """Return a list of exports currently available on this machine.
2860

2861
  @rtype: list
2862
  @return: list of the exports
2863

2864
  """
2865
  if os.path.isdir(pathutils.EXPORT_DIR):
2866
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
2867
  else:
2868
    _Fail("No exports directory")
2869

    
2870

    
2871
def RemoveExport(export):
2872
  """Remove an existing export from the node.
2873

2874
  @type export: str
2875
  @param export: the name of the export to remove
2876
  @rtype: None
2877

2878
  """
2879
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
2880

    
2881
  try:
2882
    shutil.rmtree(target)
2883
  except EnvironmentError, err:
2884
    _Fail("Error while removing the export: %s", err, exc=True)
2885

    
2886

    
2887
def BlockdevRename(devlist):
2888
  """Rename a list of block devices.
2889

2890
  @type devlist: list of tuples
2891
  @param devlist: list of tuples of the form  (disk,
2892
      new_logical_id, new_physical_id); disk is an
2893
      L{objects.Disk} object describing the current disk,
2894
      and new logical_id/physical_id is the name we
2895
      rename it to
2896
  @rtype: boolean
2897
  @return: True if all renames succeeded, False otherwise
2898

2899
  """
2900
  msgs = []
2901
  result = True
2902
  for disk, unique_id in devlist:
2903
    dev = _RecursiveFindBD(disk)
2904
    if dev is None:
2905
      msgs.append("Can't find device %s in rename" % str(disk))
2906
      result = False
2907
      continue
2908
    try:
2909
      old_rpath = dev.dev_path
2910
      dev.Rename(unique_id)
2911
      new_rpath = dev.dev_path
2912
      if old_rpath != new_rpath:
2913
        DevCacheManager.RemoveCache(old_rpath)
2914
        # FIXME: we should add the new cache information here, like:
2915
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2916
        # but we don't have the owner here - maybe parse from existing
2917
        # cache? for now, we only lose lvm data when we rename, which
2918
        # is less critical than DRBD or MD
2919
    except errors.BlockDeviceError, err:
2920
      msgs.append("Can't rename device '%s' to '%s': %s" %
2921
                  (dev, unique_id, err))
2922
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2923
      result = False
2924
  if not result:
2925
    _Fail("; ".join(msgs))
2926

    
2927

    
2928
def _TransformFileStorageDir(fs_dir):
2929
  """Checks whether given file_storage_dir is valid.
2930

2931
  Checks wheter the given fs_dir is within the cluster-wide default
2932
  file_storage_dir or the shared_file_storage_dir, which are stored in
2933
  SimpleStore. Only paths under those directories are allowed.
2934

2935
  @type fs_dir: str
2936
  @param fs_dir: the path to check
2937

2938
  @return: the normalized path if valid, None otherwise
2939

2940
  """
2941
  if not (constants.ENABLE_FILE_STORAGE or
2942
          constants.ENABLE_SHARED_FILE_STORAGE):
2943
    _Fail("File storage disabled at configure time")
2944

    
2945
  bdev.CheckFileStoragePath(fs_dir)
2946

    
2947
  return os.path.normpath(fs_dir)
2948

    
2949

    
2950
def CreateFileStorageDir(file_storage_dir):
2951
  """Create file storage directory.
2952

2953
  @type file_storage_dir: str
2954
  @param file_storage_dir: directory to create
2955

2956
  @rtype: tuple
2957
  @return: tuple with first element a boolean indicating wheter dir
2958
      creation was successful or not
2959

2960
  """
2961
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2962
  if os.path.exists(file_storage_dir):
2963
    if not os.path.isdir(file_storage_dir):
2964
      _Fail("Specified storage dir '%s' is not a directory",
2965
            file_storage_dir)
2966
  else:
2967
    try:
2968
      os.makedirs(file_storage_dir, 0750)
2969
    except OSError, err:
2970
      _Fail("Cannot create file storage directory '%s': %s",
2971
            file_storage_dir, err, exc=True)
2972

    
2973

    
2974
def RemoveFileStorageDir(file_storage_dir):
2975
  """Remove file storage directory.
2976

2977
  Remove it only if it's empty. If not log an error and return.
2978

2979
  @type file_storage_dir: str
2980
  @param file_storage_dir: the directory we should cleanup
2981
  @rtype: tuple (success,)
2982
  @return: tuple of one element, C{success}, denoting
2983
      whether the operation was successful
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 directory '%s' is not a directory",
2990
            file_storage_dir)
2991
    # deletes dir only if empty, otherwise we want to fail the rpc call
2992
    try:
2993
      os.rmdir(file_storage_dir)
2994
    except OSError, err:
2995
      _Fail("Cannot remove file storage directory '%s': %s",
2996
            file_storage_dir, err)
2997

    
2998

    
2999
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
3000
  """Rename the file storage directory.
3001

3002
  @type old_file_storage_dir: str
3003
  @param old_file_storage_dir: the current path
3004
  @type new_file_storage_dir: str
3005
  @param new_file_storage_dir: the name we should rename to
3006
  @rtype: tuple (success,)
3007
  @return: tuple of one element, C{success}, denoting
3008
      whether the operation was successful
3009

3010
  """
3011
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
3012
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
3013
  if not os.path.exists(new_file_storage_dir):
3014
    if os.path.isdir(old_file_storage_dir):
3015
      try:
3016
        os.rename(old_file_storage_dir, new_file_storage_dir)
3017
      except OSError, err:
3018
        _Fail("Cannot rename '%s' to '%s': %s",
3019
              old_file_storage_dir, new_file_storage_dir, err)
3020
    else:
3021
      _Fail("Specified storage dir '%s' is not a directory",
3022
            old_file_storage_dir)
3023
  else:
3024
    if os.path.exists(old_file_storage_dir):
3025
      _Fail("Cannot rename '%s' to '%s': both locations exist",
3026
            old_file_storage_dir, new_file_storage_dir)
3027

    
3028

    
3029
def _EnsureJobQueueFile(file_name):
3030
  """Checks whether the given filename is in the queue directory.
3031

3032
  @type file_name: str
3033
  @param file_name: the file name we should check
3034
  @rtype: None
3035
  @raises RPCFail: if the file is not valid
3036

3037
  """
3038
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
3039
    _Fail("Passed job queue file '%s' does not belong to"
3040
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
3041

    
3042

    
3043
def JobQueueUpdate(file_name, content):
3044
  """Updates a file in the queue directory.
3045

3046
  This is just a wrapper over L{utils.io.WriteFile}, with proper
3047
  checking.
3048

3049
  @type file_name: str
3050
  @param file_name: the job file name
3051
  @type content: str
3052
  @param content: the new job contents
3053
  @rtype: boolean
3054
  @return: the success of the operation
3055

3056
  """
3057
  file_name = vcluster.LocalizeVirtualPath(file_name)
3058

    
3059
  _EnsureJobQueueFile(file_name)
3060
  getents = runtime.GetEnts()
3061

    
3062
  # Write and replace the file atomically
3063
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3064
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3065

    
3066

    
3067
def JobQueueRename(old, new):
3068
  """Renames a job queue file.
3069

3070
  This is just a wrapper over os.rename with proper checking.
3071

3072
  @type old: str
3073
  @param old: the old (actual) file name
3074
  @type new: str
3075
  @param new: the desired file name
3076
  @rtype: tuple
3077
  @return: the success of the operation and payload
3078

3079
  """
3080
  old = vcluster.LocalizeVirtualPath(old)
3081
  new = vcluster.LocalizeVirtualPath(new)
3082

    
3083
  _EnsureJobQueueFile(old)
3084
  _EnsureJobQueueFile(new)
3085

    
3086
  getents = runtime.GetEnts()
3087

    
3088
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3089
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3090

    
3091

    
3092
def BlockdevClose(instance_name, disks):
3093
  """Closes the given block devices.
3094

3095
  This means they will be switched to secondary mode (in case of
3096
  DRBD).
3097

3098
  @param instance_name: if the argument is not empty, the symlinks
3099
      of this instance will be removed
3100
  @type disks: list of L{objects.Disk}
3101
  @param disks: the list of disks to be closed
3102
  @rtype: tuple (success, message)
3103
  @return: a tuple of success and message, where success
3104
      indicates the succes of the operation, and message
3105
      which will contain the error details in case we
3106
      failed
3107

3108
  """
3109
  bdevs = []
3110
  for cf in disks:
3111
    rd = _RecursiveFindBD(cf)
3112
    if rd is None:
3113
      _Fail("Can't find device %s", cf)
3114
    bdevs.append(rd)
3115

    
3116
  msg = []
3117
  for rd in bdevs:
3118
    try:
3119
      rd.Close()
3120
    except errors.BlockDeviceError, err:
3121
      msg.append(str(err))
3122
  if msg:
3123
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3124
  else:
3125
    if instance_name:
3126
      _RemoveBlockDevLinks(instance_name, disks)
3127

    
3128

    
3129
def ValidateHVParams(hvname, hvparams):
3130
  """Validates the given hypervisor parameters.
3131

3132
  @type hvname: string
3133
  @param hvname: the hypervisor name
3134
  @type hvparams: dict
3135
  @param hvparams: the hypervisor parameters to be validated
3136
  @rtype: None
3137

3138
  """
3139
  try:
3140
    hv_type = hypervisor.GetHypervisor(hvname)
3141
    hv_type.ValidateParameters(hvparams)
3142
  except errors.HypervisorError, err:
3143
    _Fail(str(err), log=False)
3144

    
3145

    
3146
def _CheckOSPList(os_obj, parameters):
3147
  """Check whether a list of parameters is supported by the OS.
3148

3149
  @type os_obj: L{objects.OS}
3150
  @param os_obj: OS object to check
3151
  @type parameters: list
3152
  @param parameters: the list of parameters to check
3153

3154
  """
3155
  supported = [v[0] for v in os_obj.supported_parameters]
3156
  delta = frozenset(parameters).difference(supported)
3157
  if delta:
3158
    _Fail("The following parameters are not supported"
3159
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3160

    
3161

    
3162
def ValidateOS(required, osname, checks, osparams):
3163
  """Validate the given OS' parameters.
3164

3165
  @type required: boolean
3166
  @param required: whether absence of the OS should translate into
3167
      failure or not
3168
  @type osname: string
3169
  @param osname: the OS to be validated
3170
  @type checks: list
3171
  @param checks: list of the checks to run (currently only 'parameters')
3172
  @type osparams: dict
3173
  @param osparams: dictionary with OS parameters
3174
  @rtype: boolean
3175
  @return: True if the validation passed, or False if the OS was not
3176
      found and L{required} was false
3177

3178
  """
3179
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3180
    _Fail("Unknown checks required for OS %s: %s", osname,
3181
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3182

    
3183
  name_only = objects.OS.GetName(osname)
3184
  status, tbv = _TryOSFromDisk(name_only, None)
3185

    
3186
  if not status:
3187
    if required:
3188
      _Fail(tbv)
3189
    else:
3190
      return False
3191

    
3192
  if max(tbv.api_versions) < constants.OS_API_V20:
3193
    return True
3194

    
3195
  if constants.OS_VALIDATE_PARAMETERS in checks:
3196
    _CheckOSPList(tbv, osparams.keys())
3197

    
3198
  validate_env = OSCoreEnv(osname, tbv, osparams)
3199
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3200
                        cwd=tbv.path, reset_env=True)
3201
  if result.failed:
3202
    logging.error("os validate command '%s' returned error: %s output: %s",
3203
                  result.cmd, result.fail_reason, result.output)
3204
    _Fail("OS validation script failed (%s), output: %s",
3205
          result.fail_reason, result.output, log=False)
3206

    
3207
  return True
3208

    
3209

    
3210
def DemoteFromMC():
3211
  """Demotes the current node from master candidate role.
3212

3213
  """
3214
  # try to ensure we're not the master by mistake
3215
  master, myself = ssconf.GetMasterAndMyself()
3216
  if master == myself:
3217
    _Fail("ssconf status shows I'm the master node, will not demote")
3218

    
3219
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3220
  if not result.failed:
3221
    _Fail("The master daemon is running, will not demote")
3222

    
3223
  try:
3224
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3225
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3226
  except EnvironmentError, err:
3227
    if err.errno != errno.ENOENT:
3228
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3229

    
3230
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3231

    
3232

    
3233
def _GetX509Filenames(cryptodir, name):
3234
  """Returns the full paths for the private key and certificate.
3235

3236
  """
3237
  return (utils.PathJoin(cryptodir, name),
3238
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3239
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3240

    
3241

    
3242
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3243
  """Creates a new X509 certificate for SSL/TLS.
3244

3245
  @type validity: int
3246
  @param validity: Validity in seconds
3247
  @rtype: tuple; (string, string)
3248
  @return: Certificate name and public part
3249

3250
  """
3251
  (key_pem, cert_pem) = \
3252
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3253
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3254

    
3255
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3256
                              prefix="x509-%s-" % utils.TimestampForFilename())
3257
  try:
3258
    name = os.path.basename(cert_dir)
3259
    assert len(name) > 5
3260

    
3261
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3262

    
3263
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3264
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3265

    
3266
    # Never return private key as it shouldn't leave the node
3267
    return (name, cert_pem)
3268
  except Exception:
3269
    shutil.rmtree(cert_dir, ignore_errors=True)
3270
    raise
3271

    
3272

    
3273
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3274
  """Removes a X509 certificate.
3275

3276
  @type name: string
3277
  @param name: Certificate name
3278

3279
  """
3280
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3281

    
3282
  utils.RemoveFile(key_file)
3283
  utils.RemoveFile(cert_file)
3284

    
3285
  try:
3286
    os.rmdir(cert_dir)
3287
  except EnvironmentError, err:
3288
    _Fail("Cannot remove certificate directory '%s': %s",
3289
          cert_dir, err)
3290

    
3291

    
3292
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3293
  """Returns the command for the requested input/output.
3294

3295
  @type instance: L{objects.Instance}
3296
  @param instance: The instance object
3297
  @param mode: Import/export mode
3298
  @param ieio: Input/output type
3299
  @param ieargs: Input/output arguments
3300

3301
  """
3302
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3303

    
3304
  env = None
3305
  prefix = None
3306
  suffix = None
3307
  exp_size = None
3308

    
3309
  if ieio == constants.IEIO_FILE:
3310
    (filename, ) = ieargs
3311

    
3312
    if not utils.IsNormAbsPath(filename):
3313
      _Fail("Path '%s' is not normalized or absolute", filename)
3314

    
3315
    real_filename = os.path.realpath(filename)
3316
    directory = os.path.dirname(real_filename)
3317

    
3318
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3319
      _Fail("File '%s' is not under exports directory '%s': %s",
3320
            filename, pathutils.EXPORT_DIR, real_filename)
3321

    
3322
    # Create directory
3323
    utils.Makedirs(directory, mode=0750)
3324

    
3325
    quoted_filename = utils.ShellQuote(filename)
3326

    
3327
    if mode == constants.IEM_IMPORT:
3328
      suffix = "> %s" % quoted_filename
3329
    elif mode == constants.IEM_EXPORT:
3330
      suffix = "< %s" % quoted_filename
3331

    
3332
      # Retrieve file size
3333
      try:
3334
        st = os.stat(filename)
3335
      except EnvironmentError, err:
3336
        logging.error("Can't stat(2) %s: %s", filename, err)
3337
      else:
3338
        exp_size = utils.BytesToMebibyte(st.st_size)
3339

    
3340
  elif ieio == constants.IEIO_RAW_DISK:
3341
    (disk, ) = ieargs
3342

    
3343
    real_disk = _OpenRealBD(disk)
3344

    
3345
    if mode == constants.IEM_IMPORT:
3346
      # we set here a smaller block size as, due to transport buffering, more
3347
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3348
      # is not already there or we pass a wrong path; we use notrunc to no
3349
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3350
      # much memory; this means that at best, we flush every 64k, which will
3351
      # not be very fast
3352
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3353
                                    " bs=%s oflag=dsync"),
3354
                                    real_disk.dev_path,
3355
                                    str(64 * 1024))
3356

    
3357
    elif mode == constants.IEM_EXPORT:
3358
      # the block size on the read dd is 1MiB to match our units
3359
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3360
                                   real_disk.dev_path,
3361
                                   str(1024 * 1024), # 1 MB
3362
                                   str(disk.size))
3363
      exp_size = disk.size
3364

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

    
3368
    assert isinstance(disk_index, (int, long))
3369

    
3370
    real_disk = _OpenRealBD(disk)
3371

    
3372
    inst_os = OSFromDisk(instance.os)
3373
    env = OSEnvironment(instance, inst_os)
3374

    
3375
    if mode == constants.IEM_IMPORT:
3376
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3377
      env["IMPORT_INDEX"] = str(disk_index)
3378
      script = inst_os.import_script
3379

    
3380
    elif mode == constants.IEM_EXPORT:
3381
      env["EXPORT_DEVICE"] = real_disk.dev_path
3382
      env["EXPORT_INDEX"] = str(disk_index)
3383
      script = inst_os.export_script
3384

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

    
3388
    if mode == constants.IEM_IMPORT:
3389
      suffix = "| %s" % script_cmd
3390

    
3391
    elif mode == constants.IEM_EXPORT:
3392
      prefix = "%s |" % script_cmd
3393

    
3394
    # Let script predict size
3395
    exp_size = constants.IE_CUSTOM_SIZE
3396

    
3397
  else:
3398
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3399

    
3400
  return (env, prefix, suffix, exp_size)
3401

    
3402

    
3403
def _CreateImportExportStatusDir(prefix):
3404
  """Creates status directory for import/export.
3405

3406
  """
3407
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3408
                          prefix=("%s-%s-" %
3409
                                  (prefix, utils.TimestampForFilename())))
3410

    
3411

    
3412
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3413
                            ieio, ieioargs):
3414
  """Starts an import or export daemon.
3415

3416
  @param mode: Import/output mode
3417
  @type opts: L{objects.ImportExportOptions}
3418
  @param opts: Daemon options
3419
  @type host: string
3420
  @param host: Remote host for export (None for import)
3421
  @type port: int
3422
  @param port: Remote port for export (None for import)
3423
  @type instance: L{objects.Instance}
3424
  @param instance: Instance object
3425
  @type component: string
3426
  @param component: which part of the instance is transferred now,
3427
      e.g. 'disk/0'
3428
  @param ieio: Input/output type
3429
  @param ieioargs: Input/output arguments
3430

3431
  """
3432
  if mode == constants.IEM_IMPORT:
3433
    prefix = "import"
3434

    
3435
    if not (host is None and port is None):
3436
      _Fail("Can not specify host or port on import")
3437

    
3438
  elif mode == constants.IEM_EXPORT:
3439
    prefix = "export"
3440

    
3441
    if host is None or port is None:
3442
      _Fail("Host and port must be specified for an export")
3443

    
3444
  else:
3445
    _Fail("Invalid mode %r", mode)
3446

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

    
3450
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3451
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3452

    
3453
  if opts.key_name is None:
3454
    # Use server.pem
3455
    key_path = pathutils.NODED_CERT_FILE
3456
    cert_path = pathutils.NODED_CERT_FILE
3457
    assert opts.ca_pem is None
3458
  else:
3459
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3460
                                                 opts.key_name)
3461
    assert opts.ca_pem is not None
3462

    
3463
  for i in [key_path, cert_path]:
3464
    if not os.path.exists(i):
3465
      _Fail("File '%s' does not exist" % i)
3466

    
3467
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3468
  try:
3469
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3470
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3471
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3472

    
3473
    if opts.ca_pem is None:
3474
      # Use server.pem
3475
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3476
    else:
3477
      ca = opts.ca_pem
3478

    
3479
    # Write CA file
3480
    utils.WriteFile(ca_file, data=ca, mode=0400)
3481

    
3482
    cmd = [
3483
      pathutils.IMPORT_EXPORT_DAEMON,
3484
      status_file, mode,
3485
      "--key=%s" % key_path,
3486
      "--cert=%s" % cert_path,
3487
      "--ca=%s" % ca_file,
3488
      ]
3489

    
3490
    if host:
3491
      cmd.append("--host=%s" % host)
3492

    
3493
    if port:
3494
      cmd.append("--port=%s" % port)
3495

    
3496
    if opts.ipv6:
3497
      cmd.append("--ipv6")
3498
    else:
3499
      cmd.append("--ipv4")
3500

    
3501
    if opts.compress:
3502
      cmd.append("--compress=%s" % opts.compress)
3503

    
3504
    if opts.magic:
3505
      cmd.append("--magic=%s" % opts.magic)
3506

    
3507
    if exp_size is not None:
3508
      cmd.append("--expected-size=%s" % exp_size)
3509

    
3510
    if cmd_prefix:
3511
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3512

    
3513
    if cmd_suffix:
3514
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3515

    
3516
    if mode == constants.IEM_EXPORT:
3517
      # Retry connection a few times when connecting to remote peer
3518
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3519
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3520
    elif opts.connect_timeout is not None:
3521
      assert mode == constants.IEM_IMPORT
3522
      # Overall timeout for establishing connection while listening
3523
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3524

    
3525
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3526

    
3527
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3528
    # support for receiving a file descriptor for output
3529
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3530
                      output=logfile)
3531

    
3532
    # The import/export name is simply the status directory name
3533
    return os.path.basename(status_dir)
3534

    
3535
  except Exception:
3536
    shutil.rmtree(status_dir, ignore_errors=True)
3537
    raise
3538

    
3539

    
3540
def GetImportExportStatus(names):
3541
  """Returns import/export daemon status.
3542

3543
  @type names: sequence
3544
  @param names: List of names
3545
  @rtype: List of dicts
3546
  @return: Returns a list of the state of each named import/export or None if a
3547
           status couldn't be read
3548

3549
  """
3550
  result = []
3551

    
3552
  for name in names:
3553
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3554
                                 _IES_STATUS_FILE)
3555

    
3556
    try:
3557
      data = utils.ReadFile(status_file)
3558
    except EnvironmentError, err:
3559
      if err.errno != errno.ENOENT:
3560
        raise
3561
      data = None
3562

    
3563
    if not data:
3564
      result.append(None)
3565
      continue
3566

    
3567
    result.append(serializer.LoadJson(data))
3568

    
3569
  return result
3570

    
3571

    
3572
def AbortImportExport(name):
3573
  """Sends SIGTERM to a running import/export daemon.
3574

3575
  """
3576
  logging.info("Abort import/export %s", name)
3577

    
3578
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3579
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3580

    
3581
  if pid:
3582
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3583
                 name, pid)
3584
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3585

    
3586

    
3587
def CleanupImportExport(name):
3588
  """Cleanup after an import or export.
3589

3590
  If the import/export daemon is still running it's killed. Afterwards the
3591
  whole status directory is removed.
3592

3593
  """
3594
  logging.info("Finalizing import/export %s", name)
3595

    
3596
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3597

    
3598
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3599

    
3600
  if pid:
3601
    logging.info("Import/export %s is still running with PID %s",
3602
                 name, pid)
3603
    utils.KillProcess(pid, waitpid=False)
3604

    
3605
  shutil.rmtree(status_dir, ignore_errors=True)
3606

    
3607

    
3608
def _FindDisks(nodes_ip, disks):
3609
  """Sets the physical ID on disks and returns the block devices.
3610

3611
  """
3612
  # set the correct physical ID
3613
  my_name = netutils.Hostname.GetSysName()
3614
  for cf in disks:
3615
    cf.SetPhysicalID(my_name, nodes_ip)
3616

    
3617
  bdevs = []
3618

    
3619
  for cf in disks:
3620
    rd = _RecursiveFindBD(cf)
3621
    if rd is None:
3622
      _Fail("Can't find device %s", cf)
3623
    bdevs.append(rd)
3624
  return bdevs
3625

    
3626

    
3627
def DrbdDisconnectNet(nodes_ip, disks):
3628
  """Disconnects the network on a list of drbd devices.
3629

3630
  """
3631
  bdevs = _FindDisks(nodes_ip, disks)
3632

    
3633
  # disconnect disks
3634
  for rd in bdevs:
3635
    try:
3636
      rd.DisconnectNet()
3637
    except errors.BlockDeviceError, err:
3638
      _Fail("Can't change network configuration to standalone mode: %s",
3639
            err, exc=True)
3640

    
3641

    
3642
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3643
  """Attaches the network on a list of drbd devices.
3644

3645
  """
3646
  bdevs = _FindDisks(nodes_ip, disks)
3647

    
3648
  if multimaster:
3649
    for idx, rd in enumerate(bdevs):
3650
      try:
3651
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3652
      except EnvironmentError, err:
3653
        _Fail("Can't create symlink: %s", err)
3654
  # reconnect disks, switch to new master configuration and if
3655
  # needed primary mode
3656
  for rd in bdevs:
3657
    try:
3658
      rd.AttachNet(multimaster)
3659
    except errors.BlockDeviceError, err:
3660
      _Fail("Can't change network configuration: %s", err)
3661

    
3662
  # wait until the disks are connected; we need to retry the re-attach
3663
  # if the device becomes standalone, as this might happen if the one
3664
  # node disconnects and reconnects in a different mode before the
3665
  # other node reconnects; in this case, one or both of the nodes will
3666
  # decide it has wrong configuration and switch to standalone
3667

    
3668
  def _Attach():
3669
    all_connected = True
3670

    
3671
    for rd in bdevs:
3672
      stats = rd.GetProcStatus()
3673

    
3674
      all_connected = (all_connected and
3675
                       (stats.is_connected or stats.is_in_resync))
3676

    
3677
      if stats.is_standalone:
3678
        # peer had different config info and this node became
3679
        # standalone, even though this should not happen with the
3680
        # new staged way of changing disk configs
3681
        try:
3682
          rd.AttachNet(multimaster)
3683
        except errors.BlockDeviceError, err:
3684
          _Fail("Can't change network configuration: %s", err)
3685

    
3686
    if not all_connected:
3687
      raise utils.RetryAgain()
3688

    
3689
  try:
3690
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3691
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3692
  except utils.RetryTimeout:
3693
    _Fail("Timeout in disk reconnecting")
3694

    
3695
  if multimaster:
3696
    # change to primary mode
3697
    for rd in bdevs:
3698
      try:
3699
        rd.Open()
3700
      except errors.BlockDeviceError, err:
3701
        _Fail("Can't change to primary mode: %s", err)
3702

    
3703

    
3704
def DrbdWaitSync(nodes_ip, disks):
3705
  """Wait until DRBDs have synchronized.
3706

3707
  """
3708
  def _helper(rd):
3709
    stats = rd.GetProcStatus()
3710
    if not (stats.is_connected or stats.is_in_resync):
3711
      raise utils.RetryAgain()
3712
    return stats
3713

    
3714
  bdevs = _FindDisks(nodes_ip, disks)
3715

    
3716
  min_resync = 100
3717
  alldone = True
3718
  for rd in bdevs:
3719
    try:
3720
      # poll each second for 15 seconds
3721
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3722
    except utils.RetryTimeout:
3723
      stats = rd.GetProcStatus()
3724
      # last check
3725
      if not (stats.is_connected or stats.is_in_resync):
3726
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3727
    alldone = alldone and (not stats.is_in_resync)
3728
    if stats.sync_percent is not None:
3729
      min_resync = min(min_resync, stats.sync_percent)
3730

    
3731
  return (alldone, min_resync)
3732

    
3733

    
3734
def GetDrbdUsermodeHelper():
3735
  """Returns DRBD usermode helper currently configured.
3736

3737
  """
3738
  try:
3739
    return drbd.DRBD8.GetUsermodeHelper()
3740
  except errors.BlockDeviceError, err:
3741
    _Fail(str(err))
3742

    
3743

    
3744
def PowercycleNode(hypervisor_type):
3745
  """Hard-powercycle the node.
3746

3747
  Because we need to return first, and schedule the powercycle in the
3748
  background, we won't be able to report failures nicely.
3749

3750
  """
3751
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3752
  try:
3753
    pid = os.fork()
3754
  except OSError:
3755
    # if we can't fork, we'll pretend that we're in the child process
3756
    pid = 0
3757
  if pid > 0:
3758
    return "Reboot scheduled in 5 seconds"
3759
  # ensure the child is running on ram
3760
  try:
3761
    utils.Mlockall()
3762
  except Exception: # pylint: disable=W0703
3763
    pass
3764
  time.sleep(5)
3765
  hyper.PowercycleNode()
3766

    
3767

    
3768
def _VerifyRestrictedCmdName(cmd):
3769
  """Verifies a restricted command name.
3770

3771
  @type cmd: string
3772
  @param cmd: Command name
3773
  @rtype: tuple; (boolean, string or None)
3774
  @return: The tuple's first element is the status; if C{False}, the second
3775
    element is an error message string, otherwise it's C{None}
3776

3777
  """
3778
  if not cmd.strip():
3779
    return (False, "Missing command name")
3780

    
3781
  if os.path.basename(cmd) != cmd:
3782
    return (False, "Invalid command name")
3783

    
3784
  if not constants.EXT_PLUGIN_MASK.match(cmd):
3785
    return (False, "Command name contains forbidden characters")
3786

    
3787
  return (True, None)
3788

    
3789

    
3790
def _CommonRestrictedCmdCheck(path, owner):
3791
  """Common checks for restricted command file system directories and files.
3792

3793
  @type path: string
3794
  @param path: Path to check
3795
  @param owner: C{None} or tuple containing UID and GID
3796
  @rtype: tuple; (boolean, string or C{os.stat} result)
3797
  @return: The tuple's first element is the status; if C{False}, the second
3798
    element is an error message string, otherwise it's the result of C{os.stat}
3799

3800
  """
3801
  if owner is None:
3802
    # Default to root as owner
3803
    owner = (0, 0)
3804

    
3805
  try:
3806
    st = os.stat(path)
3807
  except EnvironmentError, err:
3808
    return (False, "Can't stat(2) '%s': %s" % (path, err))
3809

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

    
3813
  if (st.st_uid, st.st_gid) != owner:
3814
    (owner_uid, owner_gid) = owner
3815
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
3816

    
3817
  return (True, st)
3818

    
3819

    
3820
def _VerifyRestrictedCmdDirectory(path, _owner=None):
3821
  """Verifies restricted command directory.
3822

3823
  @type path: string
3824
  @param path: Path to check
3825
  @rtype: tuple; (boolean, string or None)
3826
  @return: The tuple's first element is the status; if C{False}, the second
3827
    element is an error message string, otherwise it's C{None}
3828

3829
  """
3830
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
3831

    
3832
  if not status:
3833
    return (False, value)
3834

    
3835
  if not stat.S_ISDIR(value.st_mode):
3836
    return (False, "Path '%s' is not a directory" % path)
3837

    
3838
  return (True, None)
3839

    
3840

    
3841
def _VerifyRestrictedCmd(path, cmd, _owner=None):
3842
  """Verifies a whole restricted command and returns its executable filename.
3843

3844
  @type path: string
3845
  @param path: Directory containing restricted commands
3846
  @type cmd: string
3847
  @param cmd: Command name
3848
  @rtype: tuple; (boolean, string)
3849
  @return: The tuple's first element is the status; if C{False}, the second
3850
    element is an error message string, otherwise the second element is the
3851
    absolute path to the executable
3852

3853
  """
3854
  executable = utils.PathJoin(path, cmd)
3855

    
3856
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
3857

    
3858
  if not status:
3859
    return (False, msg)
3860

    
3861
  if not utils.IsExecutable(executable):
3862
    return (False, "access(2) thinks '%s' can't be executed" % executable)
3863

    
3864
  return (True, executable)
3865

    
3866

    
3867
def _PrepareRestrictedCmd(path, cmd,
3868
                          _verify_dir=_VerifyRestrictedCmdDirectory,
3869
                          _verify_name=_VerifyRestrictedCmdName,
3870
                          _verify_cmd=_VerifyRestrictedCmd):
3871
  """Performs a number of tests on a restricted command.
3872

3873
  @type path: string
3874
  @param path: Directory containing restricted commands
3875
  @type cmd: string
3876
  @param cmd: Command name
3877
  @return: Same as L{_VerifyRestrictedCmd}
3878

3879
  """
3880
  # Verify the directory first
3881
  (status, msg) = _verify_dir(path)
3882
  if status:
3883
    # Check command if everything was alright
3884
    (status, msg) = _verify_name(cmd)
3885

    
3886
  if not status:
3887
    return (False, msg)
3888

    
3889
  # Check actual executable
3890
  return _verify_cmd(path, cmd)
3891

    
3892

    
3893
def RunRestrictedCmd(cmd,
3894
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
3895
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
3896
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
3897
                     _sleep_fn=time.sleep,
3898
                     _prepare_fn=_PrepareRestrictedCmd,
3899
                     _runcmd_fn=utils.RunCmd,
3900
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
3901
  """Executes a restricted command after performing strict tests.
3902

3903
  @type cmd: string
3904
  @param cmd: Command name
3905
  @rtype: string
3906
  @return: Command output
3907
  @raise RPCFail: In case of an error
3908

3909
  """
3910
  logging.info("Preparing to run restricted command '%s'", cmd)
3911

    
3912
  if not _enabled:
3913
    _Fail("Restricted commands disabled at configure time")
3914

    
3915
  lock = None
3916
  try:
3917
    cmdresult = None
3918
    try:
3919
      lock = utils.FileLock.Open(_lock_file)
3920
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
3921

    
3922
      (status, value) = _prepare_fn(_path, cmd)
3923

    
3924
      if status:
3925
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
3926
                               postfork_fn=lambda _: lock.Unlock())
3927
      else:
3928
        logging.error(value)
3929
    except Exception: # pylint: disable=W0703
3930
      # Keep original error in log
3931
      logging.exception("Caught exception")
3932

    
3933
    if cmdresult is None:
3934
      logging.info("Sleeping for %0.1f seconds before returning",
3935
                   _RCMD_INVALID_DELAY)
3936
      _sleep_fn(_RCMD_INVALID_DELAY)
3937

    
3938
      # Do not include original error message in returned error
3939
      _Fail("Executing command '%s' failed" % cmd)
3940
    elif cmdresult.failed or cmdresult.fail_reason:
3941
      _Fail("Restricted command '%s' failed: %s; output: %s",
3942
            cmd, cmdresult.fail_reason, cmdresult.output)
3943
    else:
3944
      return cmdresult.output
3945
  finally:
3946
    if lock is not None:
3947
      # Release lock at last
3948
      lock.Close()
3949
      lock = None
3950

    
3951

    
3952
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
3953
  """Creates or removes the watcher pause file.
3954

3955
  @type until: None or number
3956
  @param until: Unix timestamp saying until when the watcher shouldn't run
3957

3958
  """
3959
  if until is None:
3960
    logging.info("Received request to no longer pause watcher")
3961
    utils.RemoveFile(_filename)
3962
  else:
3963
    logging.info("Received request to pause watcher until %s", until)
3964

    
3965
    if not ht.TNumber(until):
3966
      _Fail("Duration must be numeric")
3967

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

    
3970

    
3971
class HooksRunner(object):
3972
  """Hook runner.
3973

3974
  This class is instantiated on the node side (ganeti-noded) and not
3975
  on the master side.
3976

3977
  """
3978
  def __init__(self, hooks_base_dir=None):
3979
    """Constructor for hooks runner.
3980

3981
    @type hooks_base_dir: str or None
3982
    @param hooks_base_dir: if not None, this overrides the
3983
        L{pathutils.HOOKS_BASE_DIR} (useful for unittests)
3984

3985
    """
3986
    if hooks_base_dir is None:
3987
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
3988
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3989
    # constant
3990
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
3991

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

3995
    """
3996
    assert len(node_list) == 1
3997
    node = node_list[0]
3998
    _, myself = ssconf.GetMasterAndMyself()
3999
    assert node == myself
4000

    
4001
    results = self.RunHooks(hpath, phase, env)
4002

    
4003
    # Return values in the form expected by HooksMaster
4004
    return {node: (None, False, results)}
4005

    
4006
  def RunHooks(self, hpath, phase, env):
4007
    """Run the scripts in the hooks directory.
4008

4009
    @type hpath: str
4010
    @param hpath: the path to the hooks directory which
4011
        holds the scripts
4012
    @type phase: str
4013
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
4014
        L{constants.HOOKS_PHASE_POST}
4015
    @type env: dict
4016
    @param env: dictionary with the environment for the hook
4017
    @rtype: list
4018
    @return: list of 3-element tuples:
4019
      - script path
4020
      - script result, either L{constants.HKR_SUCCESS} or
4021
        L{constants.HKR_FAIL}
4022
      - output of the script
4023

4024
    @raise errors.ProgrammerError: for invalid input
4025
        parameters
4026

4027
    """
4028
    if phase == constants.HOOKS_PHASE_PRE:
4029
      suffix = "pre"
4030
    elif phase == constants.HOOKS_PHASE_POST:
4031
      suffix = "post"
4032
    else:
4033
      _Fail("Unknown hooks phase '%s'", phase)
4034

    
4035
    subdir = "%s-%s.d" % (hpath, suffix)
4036
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
4037

    
4038
    results = []
4039

    
4040
    if not os.path.isdir(dir_name):
4041
      # for non-existing/non-dirs, we simply exit instead of logging a
4042
      # warning at every operation
4043
      return results
4044

    
4045
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
4046

    
4047
    for (relname, relstatus, runresult) in runparts_results:
4048
      if relstatus == constants.RUNPARTS_SKIP:
4049
        rrval = constants.HKR_SKIP
4050
        output = ""
4051
      elif relstatus == constants.RUNPARTS_ERR:
4052
        rrval = constants.HKR_FAIL
4053
        output = "Hook script execution error: %s" % runresult
4054
      elif relstatus == constants.RUNPARTS_RUN:
4055
        if runresult.failed:
4056
          rrval = constants.HKR_FAIL
4057
        else:
4058
          rrval = constants.HKR_SUCCESS
4059
        output = utils.SafeEncode(runresult.output.strip())
4060
      results.append(("%s/%s" % (subdir, relname), rrval, output))
4061

    
4062
    return results
4063

    
4064

    
4065
class IAllocatorRunner(object):
4066
  """IAllocator runner.
4067

4068
  This class is instantiated on the node side (ganeti-noded) and not on
4069
  the master side.
4070

4071
  """
4072
  @staticmethod
4073
  def Run(name, idata):
4074
    """Run an iallocator script.
4075

4076
    @type name: str
4077
    @param name: the iallocator script name
4078
    @type idata: str
4079
    @param idata: the allocator input data
4080

4081
    @rtype: tuple
4082
    @return: two element tuple of:
4083
       - status
4084
       - either error message or stdout of allocator (for success)
4085

4086
    """
4087
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
4088
                                  os.path.isfile)
4089
    if alloc_script is None:
4090
      _Fail("iallocator module '%s' not found in the search path", name)
4091

    
4092
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
4093
    try:
4094
      os.write(fd, idata)
4095
      os.close(fd)
4096
      result = utils.RunCmd([alloc_script, fin_name])
4097
      if result.failed:
4098
        _Fail("iallocator module '%s' failed: %s, output '%s'",
4099
              name, result.fail_reason, result.output)
4100
    finally:
4101
      os.unlink(fin_name)
4102

    
4103
    return result.stdout
4104

    
4105

    
4106
class DevCacheManager(object):
4107
  """Simple class for managing a cache of block device information.
4108

4109
  """
4110
  _DEV_PREFIX = "/dev/"
4111
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4112

    
4113
  @classmethod
4114
  def _ConvertPath(cls, dev_path):
4115
    """Converts a /dev/name path to the cache file name.
4116

4117
    This replaces slashes with underscores and strips the /dev
4118
    prefix. It then returns the full path to the cache file.
4119

4120
    @type dev_path: str
4121
    @param dev_path: the C{/dev/} path name
4122
    @rtype: str
4123
    @return: the converted path name
4124

4125
    """
4126
    if dev_path.startswith(cls._DEV_PREFIX):
4127
      dev_path = dev_path[len(cls._DEV_PREFIX):]
4128
    dev_path = dev_path.replace("/", "_")
4129
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4130
    return fpath
4131

    
4132
  @classmethod
4133
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4134
    """Updates the cache information for a given device.
4135

4136
    @type dev_path: str
4137
    @param dev_path: the pathname of the device
4138
    @type owner: str
4139
    @param owner: the owner (instance name) of the device
4140
    @type on_primary: bool
4141
    @param on_primary: whether this is the primary
4142
        node nor not
4143
    @type iv_name: str
4144
    @param iv_name: the instance-visible name of the
4145
        device, as in objects.Disk.iv_name
4146

4147
    @rtype: None
4148

4149
    """
4150
    if dev_path is None:
4151
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
4152
      return
4153
    fpath = cls._ConvertPath(dev_path)
4154
    if on_primary:
4155
      state = "primary"
4156
    else:
4157
      state = "secondary"
4158
    if iv_name is None:
4159
      iv_name = "not_visible"
4160
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4161
    try:
4162
      utils.WriteFile(fpath, data=fdata)
4163
    except EnvironmentError, err:
4164
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4165

    
4166
  @classmethod
4167
  def RemoveCache(cls, dev_path):
4168
    """Remove data for a dev_path.
4169

4170
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
4171
    path name and logging.
4172

4173
    @type dev_path: str
4174
    @param dev_path: the pathname of the device
4175

4176
    @rtype: None
4177

4178
    """
4179
    if dev_path is None:
4180
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
4181
      return
4182
    fpath = cls._ConvertPath(dev_path)
4183
    try:
4184
      utils.RemoveFile(fpath)
4185
    except EnvironmentError, err:
4186
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)