Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ c6ae283b

History | View | Annotate | Download (133.2 kB)

1
#
2
#
3

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

    
21

    
22
"""Functions used by the node daemon
23

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

29
"""
30

    
31
# pylint: disable=E1103
32

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

    
37

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

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

    
72

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

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

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

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

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

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

    
107

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

111
  Its argument is the error message.
112

113
  """
114

    
115

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

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

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

    
127

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

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

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

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

    
143

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

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

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

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

    
166

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

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

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

    
176

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

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

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

    
189

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

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

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

    
209

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

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

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

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

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

    
239

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

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

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

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

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

    
266
  return frozenset(allowed_files)
267

    
268

    
269
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
270

    
271

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

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

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

    
282

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

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

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

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

    
307

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

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

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

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

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

    
339
      return result
340
    return wrapper
341
  return decorator
342

    
343

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

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

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

    
364
  return env
365

    
366

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

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

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

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

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

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

    
395

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

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

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

    
412

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

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

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

423
  """
424

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

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

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

    
440

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

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

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

    
457

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

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

463
  @rtype: None
464

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

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

    
475

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

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

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

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

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

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

    
506

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

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

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

    
528

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

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

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

539
  @param modify_ssh_setup: boolean
540

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

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

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

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

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

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

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

    
574

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

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

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

    
594

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

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

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

    
618

    
619
def _GetHvInfo(name, hvparams, get_hv_fn=hypervisor.GetHypervisor):
620
  """Retrieves node information from a hypervisor.
621

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

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

631
  @type hvparams: dict of string
632
  @param hvparams: the hypervisor's hvparams
633

634
  """
635
  return get_hv_fn(name).GetNodeInfo(hvparams=hvparams)
636

    
637

    
638
def _GetHvInfoAll(hv_specs, get_hv_fn=hypervisor.GetHypervisor):
639
  """Retrieves node information for all hypervisors.
640

641
  See C{_GetHvInfo} for information on the output.
642

643
  @type hv_specs: list of pairs (string, dict of strings)
644
  @param hv_specs: list of pairs of a hypervisor's name and its hvparams
645

646
  """
647
  if hv_specs is None:
648
    return None
649

    
650
  result = []
651
  for hvname, hvparams in hv_specs:
652
    result.append(_GetHvInfo(hvname, hvparams, get_hv_fn))
653
  return result
654

    
655

    
656
def _GetNamedNodeInfo(names, fn):
657
  """Calls C{fn} for all names in C{names} and returns a dictionary.
658

659
  @rtype: None or dict
660

661
  """
662
  if names is None:
663
    return None
664
  else:
665
    return map(fn, names)
666

    
667

    
668
def GetNodeInfo(storage_units, hv_specs, excl_stor):
669
  """Gives back a hash with different information about the node.
670

671
  @type storage_units: list of pairs (string, string)
672
  @param storage_units: List of pairs (storage unit, identifier) to ask for disk
673
                        space information. In case of lvm-vg, the identifier is
674
                        the VG name.
675
  @type hv_specs: list of pairs (string, dict of strings)
676
  @param hv_specs: list of pairs of a hypervisor's name and its hvparams
677
  @type excl_stor: boolean
678
  @param excl_stor: Whether exclusive_storage is active
679
  @rtype: tuple; (string, None/dict, None/dict)
680
  @return: Tuple containing boot ID, volume group information and hypervisor
681
    information
682

683
  """
684
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
685
  storage_info = _GetNamedNodeInfo(
686
    storage_units,
687
    (lambda storage_unit: _ApplyStorageInfoFunction(storage_unit[0],
688
                                                    storage_unit[1],
689
                                                    excl_stor)))
690
  hv_info = _GetHvInfoAll(hv_specs)
691
  return (bootid, storage_info, hv_info)
692

    
693

    
694
# FIXME: implement storage reporting for all missing storage types.
695
_STORAGE_TYPE_INFO_FN = {
696
  constants.ST_BLOCK: None,
697
  constants.ST_DISKLESS: None,
698
  constants.ST_EXT: None,
699
  constants.ST_FILE: None,
700
  constants.ST_LVM_PV: _GetVgSpindlesInfo,
701
  constants.ST_LVM_VG: _GetVgInfo,
702
  constants.ST_RADOS: None,
703
}
704

    
705

    
706
def _ApplyStorageInfoFunction(storage_type, storage_key, *args):
707
  """Looks up and applies the correct function to calculate free and total
708
  storage for the given storage type.
709

710
  @type storage_type: string
711
  @param storage_type: the storage type for which the storage shall be reported.
712
  @type storage_key: string
713
  @param storage_key: identifier of a storage unit, e.g. the volume group name
714
    of an LVM storage unit
715
  @type args: any
716
  @param args: various parameters that can be used for storage reporting. These
717
    parameters and their semantics vary from storage type to storage type and
718
    are just propagated in this function.
719
  @return: the results of the application of the storage space function (see
720
    _STORAGE_TYPE_INFO_FN) if storage space reporting is implemented for that
721
    storage type
722
  @raises NotImplementedError: for storage types who don't support space
723
    reporting yet
724
  """
725
  fn = _STORAGE_TYPE_INFO_FN[storage_type]
726
  if fn is not None:
727
    return fn(storage_key, *args)
728
  else:
729
    raise NotImplementedError
730

    
731

    
732
def _CheckExclusivePvs(pvi_list):
733
  """Check that PVs are not shared among LVs
734

735
  @type pvi_list: list of L{objects.LvmPvInfo} objects
736
  @param pvi_list: information about the PVs
737

738
  @rtype: list of tuples (string, list of strings)
739
  @return: offending volumes, as tuples: (pv_name, [lv1_name, lv2_name...])
740

741
  """
742
  res = []
743
  for pvi in pvi_list:
744
    if len(pvi.lv_list) > 1:
745
      res.append((pvi.name, pvi.lv_list))
746
  return res
747

    
748

    
749
def _VerifyHypervisors(what, vm_capable, result, all_hvparams,
750
                       get_hv_fn=hypervisor.GetHypervisor):
751
  """Verifies the hypervisor. Appends the results to the 'results' list.
752

753
  @type what: C{dict}
754
  @param what: a dictionary of things to check
755
  @type vm_capable: boolean
756
  @param vm_capable: whether or not this node is vm capable
757
  @type result: dict
758
  @param result: dictionary of verification results; results of the
759
    verifications in this function will be added here
760
  @type all_hvparams: dict of dict of string
761
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
762
  @type get_hv_fn: function
763
  @param get_hv_fn: function to retrieve the hypervisor, to improve testability
764

765
  """
766
  if not vm_capable:
767
    return
768

    
769
  if constants.NV_HYPERVISOR in what:
770
    result[constants.NV_HYPERVISOR] = {}
771
    for hv_name in what[constants.NV_HYPERVISOR]:
772
      hvparams = all_hvparams[hv_name]
773
      try:
774
        val = get_hv_fn(hv_name).Verify(hvparams=hvparams)
775
      except errors.HypervisorError, err:
776
        val = "Error while checking hypervisor: %s" % str(err)
777
      result[constants.NV_HYPERVISOR][hv_name] = val
778

    
779

    
780
def _VerifyHvparams(what, vm_capable, result,
781
                    get_hv_fn=hypervisor.GetHypervisor):
782
  """Verifies the hvparams. Appends the results to the 'results' list.
783

784
  @type what: C{dict}
785
  @param what: a dictionary of things to check
786
  @type vm_capable: boolean
787
  @param vm_capable: whether or not this node is vm capable
788
  @type result: dict
789
  @param result: dictionary of verification results; results of the
790
    verifications in this function will be added here
791
  @type get_hv_fn: function
792
  @param get_hv_fn: function to retrieve the hypervisor, to improve testability
793

794
  """
795
  if not vm_capable:
796
    return
797

    
798
  if constants.NV_HVPARAMS in what:
799
    result[constants.NV_HVPARAMS] = []
800
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
801
      try:
802
        logging.info("Validating hv %s, %s", hv_name, hvparms)
803
        get_hv_fn(hv_name).ValidateParameters(hvparms)
804
      except errors.HypervisorError, err:
805
        result[constants.NV_HVPARAMS].append((source, hv_name, str(err)))
806

    
807

    
808
def _VerifyInstanceList(what, vm_capable, result, all_hvparams):
809
  """Verifies the instance list.
810

811
  @type what: C{dict}
812
  @param what: a dictionary of things to check
813
  @type vm_capable: boolean
814
  @param vm_capable: whether or not this node is vm capable
815
  @type result: dict
816
  @param result: dictionary of verification results; results of the
817
    verifications in this function will be added here
818
  @type all_hvparams: dict of dict of string
819
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
820

821
  """
822
  if constants.NV_INSTANCELIST in what and vm_capable:
823
    # GetInstanceList can fail
824
    try:
825
      val = GetInstanceList(what[constants.NV_INSTANCELIST],
826
                            all_hvparams=all_hvparams)
827
    except RPCFail, err:
828
      val = str(err)
829
    result[constants.NV_INSTANCELIST] = val
830

    
831

    
832
def _VerifyNodeInfo(what, vm_capable, result, all_hvparams):
833
  """Verifies the node info.
834

835
  @type what: C{dict}
836
  @param what: a dictionary of things to check
837
  @type vm_capable: boolean
838
  @param vm_capable: whether or not this node is vm capable
839
  @type result: dict
840
  @param result: dictionary of verification results; results of the
841
    verifications in this function will be added here
842
  @type all_hvparams: dict of dict of string
843
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
844

845
  """
846
  if constants.NV_HVINFO in what and vm_capable:
847
    hvname = what[constants.NV_HVINFO]
848
    hyper = hypervisor.GetHypervisor(hvname)
849
    hvparams = all_hvparams[hvname]
850
    result[constants.NV_HVINFO] = hyper.GetNodeInfo(hvparams=hvparams)
851

    
852

    
853
def VerifyNode(what, cluster_name, all_hvparams):
854
  """Verify the status of the local node.
855

856
  Based on the input L{what} parameter, various checks are done on the
857
  local node.
858

859
  If the I{filelist} key is present, this list of
860
  files is checksummed and the file/checksum pairs are returned.
861

862
  If the I{nodelist} key is present, we check that we have
863
  connectivity via ssh with the target nodes (and check the hostname
864
  report).
865

866
  If the I{node-net-test} key is present, we check that we have
867
  connectivity to the given nodes via both primary IP and, if
868
  applicable, secondary IPs.
869

870
  @type what: C{dict}
871
  @param what: a dictionary of things to check:
872
      - filelist: list of files for which to compute checksums
873
      - nodelist: list of nodes we should check ssh communication with
874
      - node-net-test: list of nodes we should check node daemon port
875
        connectivity with
876
      - hypervisor: list with hypervisors to run the verify for
877
  @type cluster_name: string
878
  @param cluster_name: the cluster's name
879
  @type all_hvparams: dict of dict of strings
880
  @param all_hvparams: a dictionary mapping hypervisor names to hvparams
881
  @rtype: dict
882
  @return: a dictionary with the same keys as the input dict, and
883
      values representing the result of the checks
884

885
  """
886
  result = {}
887
  my_name = netutils.Hostname.GetSysName()
888
  port = netutils.GetDaemonPort(constants.NODED)
889
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
890

    
891
  _VerifyHypervisors(what, vm_capable, result, all_hvparams)
892
  _VerifyHvparams(what, vm_capable, result)
893

    
894
  if constants.NV_FILELIST in what:
895
    fingerprints = utils.FingerprintFiles(map(vcluster.LocalizeVirtualPath,
896
                                              what[constants.NV_FILELIST]))
897
    result[constants.NV_FILELIST] = \
898
      dict((vcluster.MakeVirtualPath(key), value)
899
           for (key, value) in fingerprints.items())
900

    
901
  if constants.NV_NODELIST in what:
902
    (nodes, bynode) = what[constants.NV_NODELIST]
903

    
904
    # Add nodes from other groups (different for each node)
905
    try:
906
      nodes.extend(bynode[my_name])
907
    except KeyError:
908
      pass
909

    
910
    # Use a random order
911
    random.shuffle(nodes)
912

    
913
    # Try to contact all nodes
914
    val = {}
915
    for node in nodes:
916
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
917
      if not success:
918
        val[node] = message
919

    
920
    result[constants.NV_NODELIST] = val
921

    
922
  if constants.NV_NODENETTEST in what:
923
    result[constants.NV_NODENETTEST] = tmp = {}
924
    my_pip = my_sip = None
925
    for name, pip, sip in what[constants.NV_NODENETTEST]:
926
      if name == my_name:
927
        my_pip = pip
928
        my_sip = sip
929
        break
930
    if not my_pip:
931
      tmp[my_name] = ("Can't find my own primary/secondary IP"
932
                      " in the node list")
933
    else:
934
      for name, pip, sip in what[constants.NV_NODENETTEST]:
935
        fail = []
936
        if not netutils.TcpPing(pip, port, source=my_pip):
937
          fail.append("primary")
938
        if sip != pip:
939
          if not netutils.TcpPing(sip, port, source=my_sip):
940
            fail.append("secondary")
941
        if fail:
942
          tmp[name] = ("failure using the %s interface(s)" %
943
                       " and ".join(fail))
944

    
945
  if constants.NV_MASTERIP in what:
946
    # FIXME: add checks on incoming data structures (here and in the
947
    # rest of the function)
948
    master_name, master_ip = what[constants.NV_MASTERIP]
949
    if master_name == my_name:
950
      source = constants.IP4_ADDRESS_LOCALHOST
951
    else:
952
      source = None
953
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
954
                                                     source=source)
955

    
956
  if constants.NV_USERSCRIPTS in what:
957
    result[constants.NV_USERSCRIPTS] = \
958
      [script for script in what[constants.NV_USERSCRIPTS]
959
       if not utils.IsExecutable(script)]
960

    
961
  if constants.NV_OOB_PATHS in what:
962
    result[constants.NV_OOB_PATHS] = tmp = []
963
    for path in what[constants.NV_OOB_PATHS]:
964
      try:
965
        st = os.stat(path)
966
      except OSError, err:
967
        tmp.append("error stating out of band helper: %s" % err)
968
      else:
969
        if stat.S_ISREG(st.st_mode):
970
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
971
            tmp.append(None)
972
          else:
973
            tmp.append("out of band helper %s is not executable" % path)
974
        else:
975
          tmp.append("out of band helper %s is not a file" % path)
976

    
977
  if constants.NV_LVLIST in what and vm_capable:
978
    try:
979
      val = GetVolumeList(utils.ListVolumeGroups().keys())
980
    except RPCFail, err:
981
      val = str(err)
982
    result[constants.NV_LVLIST] = val
983

    
984
  _VerifyInstanceList(what, vm_capable, result, all_hvparams)
985

    
986
  if constants.NV_VGLIST in what and vm_capable:
987
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
988

    
989
  if constants.NV_PVLIST in what and vm_capable:
990
    check_exclusive_pvs = constants.NV_EXCLUSIVEPVS in what
991
    val = bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
992
                                       filter_allocatable=False,
993
                                       include_lvs=check_exclusive_pvs)
994
    if check_exclusive_pvs:
995
      result[constants.NV_EXCLUSIVEPVS] = _CheckExclusivePvs(val)
996
      for pvi in val:
997
        # Avoid sending useless data on the wire
998
        pvi.lv_list = []
999
    result[constants.NV_PVLIST] = map(objects.LvmPvInfo.ToDict, val)
1000

    
1001
  if constants.NV_VERSION in what:
1002
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
1003
                                    constants.RELEASE_VERSION)
1004

    
1005
  _VerifyNodeInfo(what, vm_capable, result, all_hvparams)
1006

    
1007
  if constants.NV_DRBDVERSION in what and vm_capable:
1008
    try:
1009
      drbd_version = DRBD8.GetProcInfo().GetVersionString()
1010
    except errors.BlockDeviceError, err:
1011
      logging.warning("Can't get DRBD version", exc_info=True)
1012
      drbd_version = str(err)
1013
    result[constants.NV_DRBDVERSION] = drbd_version
1014

    
1015
  if constants.NV_DRBDLIST in what and vm_capable:
1016
    try:
1017
      used_minors = drbd.DRBD8.GetUsedDevs()
1018
    except errors.BlockDeviceError, err:
1019
      logging.warning("Can't get used minors list", exc_info=True)
1020
      used_minors = str(err)
1021
    result[constants.NV_DRBDLIST] = used_minors
1022

    
1023
  if constants.NV_DRBDHELPER in what and vm_capable:
1024
    status = True
1025
    try:
1026
      payload = drbd.DRBD8.GetUsermodeHelper()
1027
    except errors.BlockDeviceError, err:
1028
      logging.error("Can't get DRBD usermode helper: %s", str(err))
1029
      status = False
1030
      payload = str(err)
1031
    result[constants.NV_DRBDHELPER] = (status, payload)
1032

    
1033
  if constants.NV_NODESETUP in what:
1034
    result[constants.NV_NODESETUP] = tmpr = []
1035
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
1036
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
1037
                  " under /sys, missing required directories /sys/block"
1038
                  " and /sys/class/net")
1039
    if (not os.path.isdir("/proc/sys") or
1040
        not os.path.isfile("/proc/sysrq-trigger")):
1041
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
1042
                  " under /proc, missing required directory /proc/sys and"
1043
                  " the file /proc/sysrq-trigger")
1044

    
1045
  if constants.NV_TIME in what:
1046
    result[constants.NV_TIME] = utils.SplitTime(time.time())
1047

    
1048
  if constants.NV_OSLIST in what and vm_capable:
1049
    result[constants.NV_OSLIST] = DiagnoseOS()
1050

    
1051
  if constants.NV_BRIDGES in what and vm_capable:
1052
    result[constants.NV_BRIDGES] = [bridge
1053
                                    for bridge in what[constants.NV_BRIDGES]
1054
                                    if not utils.BridgeExists(bridge)]
1055

    
1056
  if what.get(constants.NV_FILE_STORAGE_PATHS) == my_name:
1057
    result[constants.NV_FILE_STORAGE_PATHS] = \
1058
      bdev.ComputeWrongFileStoragePaths()
1059

    
1060
  return result
1061

    
1062

    
1063
def GetBlockDevSizes(devices):
1064
  """Return the size of the given block devices
1065

1066
  @type devices: list
1067
  @param devices: list of block device nodes to query
1068
  @rtype: dict
1069
  @return:
1070
    dictionary of all block devices under /dev (key). The value is their
1071
    size in MiB.
1072

1073
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
1074

1075
  """
1076
  DEV_PREFIX = "/dev/"
1077
  blockdevs = {}
1078

    
1079
  for devpath in devices:
1080
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
1081
      continue
1082

    
1083
    try:
1084
      st = os.stat(devpath)
1085
    except EnvironmentError, err:
1086
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
1087
      continue
1088

    
1089
    if stat.S_ISBLK(st.st_mode):
1090
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
1091
      if result.failed:
1092
        # We don't want to fail, just do not list this device as available
1093
        logging.warning("Cannot get size for block device %s", devpath)
1094
        continue
1095

    
1096
      size = int(result.stdout) / (1024 * 1024)
1097
      blockdevs[devpath] = size
1098
  return blockdevs
1099

    
1100

    
1101
def GetVolumeList(vg_names):
1102
  """Compute list of logical volumes and their size.
1103

1104
  @type vg_names: list
1105
  @param vg_names: the volume groups whose LVs we should list, or
1106
      empty for all volume groups
1107
  @rtype: dict
1108
  @return:
1109
      dictionary of all partions (key) with value being a tuple of
1110
      their size (in MiB), inactive and online status::
1111

1112
        {'xenvg/test1': ('20.06', True, True)}
1113

1114
      in case of errors, a string is returned with the error
1115
      details.
1116

1117
  """
1118
  lvs = {}
1119
  sep = "|"
1120
  if not vg_names:
1121
    vg_names = []
1122
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1123
                         "--separator=%s" % sep,
1124
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
1125
  if result.failed:
1126
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
1127

    
1128
  for line in result.stdout.splitlines():
1129
    line = line.strip()
1130
    match = _LVSLINE_REGEX.match(line)
1131
    if not match:
1132
      logging.error("Invalid line returned from lvs output: '%s'", line)
1133
      continue
1134
    vg_name, name, size, attr = match.groups()
1135
    inactive = attr[4] == "-"
1136
    online = attr[5] == "o"
1137
    virtual = attr[0] == "v"
1138
    if virtual:
1139
      # we don't want to report such volumes as existing, since they
1140
      # don't really hold data
1141
      continue
1142
    lvs[vg_name + "/" + name] = (size, inactive, online)
1143

    
1144
  return lvs
1145

    
1146

    
1147
def ListVolumeGroups():
1148
  """List the volume groups and their size.
1149

1150
  @rtype: dict
1151
  @return: dictionary with keys volume name and values the
1152
      size of the volume
1153

1154
  """
1155
  return utils.ListVolumeGroups()
1156

    
1157

    
1158
def NodeVolumes():
1159
  """List all volumes on this node.
1160

1161
  @rtype: list
1162
  @return:
1163
    A list of dictionaries, each having four keys:
1164
      - name: the logical volume name,
1165
      - size: the size of the logical volume
1166
      - dev: the physical device on which the LV lives
1167
      - vg: the volume group to which it belongs
1168

1169
    In case of errors, we return an empty list and log the
1170
    error.
1171

1172
    Note that since a logical volume can live on multiple physical
1173
    volumes, the resulting list might include a logical volume
1174
    multiple times.
1175

1176
  """
1177
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1178
                         "--separator=|",
1179
                         "--options=lv_name,lv_size,devices,vg_name"])
1180
  if result.failed:
1181
    _Fail("Failed to list logical volumes, lvs output: %s",
1182
          result.output)
1183

    
1184
  def parse_dev(dev):
1185
    return dev.split("(")[0]
1186

    
1187
  def handle_dev(dev):
1188
    return [parse_dev(x) for x in dev.split(",")]
1189

    
1190
  def map_line(line):
1191
    line = [v.strip() for v in line]
1192
    return [{"name": line[0], "size": line[1],
1193
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
1194

    
1195
  all_devs = []
1196
  for line in result.stdout.splitlines():
1197
    if line.count("|") >= 3:
1198
      all_devs.extend(map_line(line.split("|")))
1199
    else:
1200
      logging.warning("Strange line in the output from lvs: '%s'", line)
1201
  return all_devs
1202

    
1203

    
1204
def BridgesExist(bridges_list):
1205
  """Check if a list of bridges exist on the current node.
1206

1207
  @rtype: boolean
1208
  @return: C{True} if all of them exist, C{False} otherwise
1209

1210
  """
1211
  missing = []
1212
  for bridge in bridges_list:
1213
    if not utils.BridgeExists(bridge):
1214
      missing.append(bridge)
1215

    
1216
  if missing:
1217
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
1218

    
1219

    
1220
def GetInstanceListForHypervisor(hname, hvparams=None,
1221
                                 get_hv_fn=hypervisor.GetHypervisor):
1222
  """Provides a list of instances of the given hypervisor.
1223

1224
  @type hname: string
1225
  @param hname: name of the hypervisor
1226
  @type hvparams: dict of strings
1227
  @param hvparams: hypervisor parameters for the given hypervisor
1228
  @type get_hv_fn: function
1229
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1230
    name; optional parameter to increase testability
1231

1232
  @rtype: list
1233
  @return: a list of all running instances on the current node
1234
    - instance1.example.com
1235
    - instance2.example.com
1236

1237
  """
1238
  results = []
1239
  try:
1240
    hv = get_hv_fn(hname)
1241
    names = hv.ListInstances(hvparams=hvparams)
1242
    results.extend(names)
1243
  except errors.HypervisorError, err:
1244
    _Fail("Error enumerating instances (hypervisor %s): %s",
1245
          hname, err, exc=True)
1246
  return results
1247

    
1248

    
1249
def GetInstanceList(hypervisor_list, all_hvparams=None,
1250
                    get_hv_fn=hypervisor.GetHypervisor):
1251
  """Provides a list of instances.
1252

1253
  @type hypervisor_list: list
1254
  @param hypervisor_list: the list of hypervisors to query information
1255
  @type all_hvparams: dict of dict of strings
1256
  @param all_hvparams: a dictionary mapping hypervisor types to respective
1257
    cluster-wide hypervisor parameters
1258
  @type get_hv_fn: function
1259
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1260
    name; optional parameter to increase testability
1261

1262
  @rtype: list
1263
  @return: a list of all running instances on the current node
1264
    - instance1.example.com
1265
    - instance2.example.com
1266

1267
  """
1268
  results = []
1269
  for hname in hypervisor_list:
1270
    hvparams = all_hvparams[hname]
1271
    results.extend(GetInstanceListForHypervisor(hname, hvparams=hvparams,
1272
                                                get_hv_fn=get_hv_fn))
1273
  return results
1274

    
1275

    
1276
def GetInstanceInfo(instance, hname):
1277
  """Gives back the information about an instance as a dictionary.
1278

1279
  @type instance: string
1280
  @param instance: the instance name
1281
  @type hname: string
1282
  @param hname: the hypervisor type of the instance
1283

1284
  @rtype: dict
1285
  @return: dictionary with the following keys:
1286
      - memory: memory size of instance (int)
1287
      - state: xen state of instance (string)
1288
      - time: cpu time of instance (float)
1289
      - vcpus: the number of vcpus (int)
1290

1291
  """
1292
  output = {}
1293

    
1294
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
1295
  if iinfo is not None:
1296
    output["memory"] = iinfo[2]
1297
    output["vcpus"] = iinfo[3]
1298
    output["state"] = iinfo[4]
1299
    output["time"] = iinfo[5]
1300

    
1301
  return output
1302

    
1303

    
1304
def GetInstanceMigratable(instance):
1305
  """Computes whether an instance can be migrated.
1306

1307
  @type instance: L{objects.Instance}
1308
  @param instance: object representing the instance to be checked.
1309

1310
  @rtype: tuple
1311
  @return: tuple of (result, description) where:
1312
      - result: whether the instance can be migrated or not
1313
      - description: a description of the issue, if relevant
1314

1315
  """
1316
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1317
  iname = instance.name
1318
  if iname not in hyper.ListInstances(instance.hvparams):
1319
    _Fail("Instance %s is not running", iname)
1320

    
1321
  for idx in range(len(instance.disks)):
1322
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1323
    if not os.path.islink(link_name):
1324
      logging.warning("Instance %s is missing symlink %s for disk %d",
1325
                      iname, link_name, idx)
1326

    
1327

    
1328
def GetAllInstancesInfo(hypervisor_list):
1329
  """Gather data about all instances.
1330

1331
  This is the equivalent of L{GetInstanceInfo}, except that it
1332
  computes data for all instances at once, thus being faster if one
1333
  needs data about more than one instance.
1334

1335
  @type hypervisor_list: list
1336
  @param hypervisor_list: list of hypervisors to query for instance data
1337

1338
  @rtype: dict
1339
  @return: dictionary of instance: data, with data having the following keys:
1340
      - memory: memory size of instance (int)
1341
      - state: xen state of instance (string)
1342
      - time: cpu time of instance (float)
1343
      - vcpus: the number of vcpus
1344

1345
  """
1346
  output = {}
1347

    
1348
  for hname in hypervisor_list:
1349
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
1350
    if iinfo:
1351
      for name, _, memory, vcpus, state, times in iinfo:
1352
        value = {
1353
          "memory": memory,
1354
          "vcpus": vcpus,
1355
          "state": state,
1356
          "time": times,
1357
          }
1358
        if name in output:
1359
          # we only check static parameters, like memory and vcpus,
1360
          # and not state and time which can change between the
1361
          # invocations of the different hypervisors
1362
          for key in "memory", "vcpus":
1363
            if value[key] != output[name][key]:
1364
              _Fail("Instance %s is running twice"
1365
                    " with different parameters", name)
1366
        output[name] = value
1367

    
1368
  return output
1369

    
1370

    
1371
def _InstanceLogName(kind, os_name, instance, component):
1372
  """Compute the OS log filename for a given instance and operation.
1373

1374
  The instance name and os name are passed in as strings since not all
1375
  operations have these as part of an instance object.
1376

1377
  @type kind: string
1378
  @param kind: the operation type (e.g. add, import, etc.)
1379
  @type os_name: string
1380
  @param os_name: the os name
1381
  @type instance: string
1382
  @param instance: the name of the instance being imported/added/etc.
1383
  @type component: string or None
1384
  @param component: the name of the component of the instance being
1385
      transferred
1386

1387
  """
1388
  # TODO: Use tempfile.mkstemp to create unique filename
1389
  if component:
1390
    assert "/" not in component
1391
    c_msg = "-%s" % component
1392
  else:
1393
    c_msg = ""
1394
  base = ("%s-%s-%s%s-%s.log" %
1395
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1396
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1397

    
1398

    
1399
def InstanceOsAdd(instance, reinstall, debug):
1400
  """Add an OS to an instance.
1401

1402
  @type instance: L{objects.Instance}
1403
  @param instance: Instance whose OS is to be installed
1404
  @type reinstall: boolean
1405
  @param reinstall: whether this is an instance reinstall
1406
  @type debug: integer
1407
  @param debug: debug level, passed to the OS scripts
1408
  @rtype: None
1409

1410
  """
1411
  inst_os = OSFromDisk(instance.os)
1412

    
1413
  create_env = OSEnvironment(instance, inst_os, debug)
1414
  if reinstall:
1415
    create_env["INSTANCE_REINSTALL"] = "1"
1416

    
1417
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1418

    
1419
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1420
                        cwd=inst_os.path, output=logfile, reset_env=True)
1421
  if result.failed:
1422
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1423
                  " output: %s", result.cmd, result.fail_reason, logfile,
1424
                  result.output)
1425
    lines = [utils.SafeEncode(val)
1426
             for val in utils.TailFile(logfile, lines=20)]
1427
    _Fail("OS create script failed (%s), last lines in the"
1428
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1429

    
1430

    
1431
def RunRenameInstance(instance, old_name, debug):
1432
  """Run the OS rename script for an instance.
1433

1434
  @type instance: L{objects.Instance}
1435
  @param instance: Instance whose OS is to be installed
1436
  @type old_name: string
1437
  @param old_name: previous instance name
1438
  @type debug: integer
1439
  @param debug: debug level, passed to the OS scripts
1440
  @rtype: boolean
1441
  @return: the success of the operation
1442

1443
  """
1444
  inst_os = OSFromDisk(instance.os)
1445

    
1446
  rename_env = OSEnvironment(instance, inst_os, debug)
1447
  rename_env["OLD_INSTANCE_NAME"] = old_name
1448

    
1449
  logfile = _InstanceLogName("rename", instance.os,
1450
                             "%s-%s" % (old_name, instance.name), None)
1451

    
1452
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1453
                        cwd=inst_os.path, output=logfile, reset_env=True)
1454

    
1455
  if result.failed:
1456
    logging.error("os create command '%s' returned error: %s output: %s",
1457
                  result.cmd, result.fail_reason, result.output)
1458
    lines = [utils.SafeEncode(val)
1459
             for val in utils.TailFile(logfile, lines=20)]
1460
    _Fail("OS rename script failed (%s), last lines in the"
1461
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1462

    
1463

    
1464
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1465
  """Returns symlink path for block device.
1466

1467
  """
1468
  if _dir is None:
1469
    _dir = pathutils.DISK_LINKS_DIR
1470

    
1471
  return utils.PathJoin(_dir,
1472
                        ("%s%s%s" %
1473
                         (instance_name, constants.DISK_SEPARATOR, idx)))
1474

    
1475

    
1476
def _SymlinkBlockDev(instance_name, device_path, idx):
1477
  """Set up symlinks to a instance's block device.
1478

1479
  This is an auxiliary function run when an instance is start (on the primary
1480
  node) or when an instance is migrated (on the target node).
1481

1482

1483
  @param instance_name: the name of the target instance
1484
  @param device_path: path of the physical block device, on the node
1485
  @param idx: the disk index
1486
  @return: absolute path to the disk's symlink
1487

1488
  """
1489
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1490
  try:
1491
    os.symlink(device_path, link_name)
1492
  except OSError, err:
1493
    if err.errno == errno.EEXIST:
1494
      if (not os.path.islink(link_name) or
1495
          os.readlink(link_name) != device_path):
1496
        os.remove(link_name)
1497
        os.symlink(device_path, link_name)
1498
    else:
1499
      raise
1500

    
1501
  return link_name
1502

    
1503

    
1504
def _RemoveBlockDevLinks(instance_name, disks):
1505
  """Remove the block device symlinks belonging to the given instance.
1506

1507
  """
1508
  for idx, _ in enumerate(disks):
1509
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1510
    if os.path.islink(link_name):
1511
      try:
1512
        os.remove(link_name)
1513
      except OSError:
1514
        logging.exception("Can't remove symlink '%s'", link_name)
1515

    
1516

    
1517
def _GatherAndLinkBlockDevs(instance):
1518
  """Set up an instance's block device(s).
1519

1520
  This is run on the primary node at instance startup. The block
1521
  devices must be already assembled.
1522

1523
  @type instance: L{objects.Instance}
1524
  @param instance: the instance whose disks we shoul assemble
1525
  @rtype: list
1526
  @return: list of (disk_object, device_path)
1527

1528
  """
1529
  block_devices = []
1530
  for idx, disk in enumerate(instance.disks):
1531
    device = _RecursiveFindBD(disk)
1532
    if device is None:
1533
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1534
                                    str(disk))
1535
    device.Open()
1536
    try:
1537
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1538
    except OSError, e:
1539
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1540
                                    e.strerror)
1541

    
1542
    block_devices.append((disk, link_name))
1543

    
1544
  return block_devices
1545

    
1546

    
1547
def StartInstance(instance, startup_paused, reason, store_reason=True):
1548
  """Start an instance.
1549

1550
  @type instance: L{objects.Instance}
1551
  @param instance: the instance object
1552
  @type startup_paused: bool
1553
  @param instance: pause instance at startup?
1554
  @type reason: list of reasons
1555
  @param reason: the reason trail for this startup
1556
  @type store_reason: boolean
1557
  @param store_reason: whether to store the shutdown reason trail on file
1558
  @rtype: None
1559

1560
  """
1561
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1562
                                                   instance.hvparams)
1563

    
1564
  if instance.name in running_instances:
1565
    logging.info("Instance %s already running, not starting", instance.name)
1566
    return
1567

    
1568
  try:
1569
    block_devices = _GatherAndLinkBlockDevs(instance)
1570
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1571
    hyper.StartInstance(instance, block_devices, startup_paused)
1572
    if store_reason:
1573
      _StoreInstReasonTrail(instance.name, reason)
1574
  except errors.BlockDeviceError, err:
1575
    _Fail("Block device error: %s", err, exc=True)
1576
  except errors.HypervisorError, err:
1577
    _RemoveBlockDevLinks(instance.name, instance.disks)
1578
    _Fail("Hypervisor error: %s", err, exc=True)
1579

    
1580

    
1581
def InstanceShutdown(instance, timeout, reason, store_reason=True):
1582
  """Shut an instance down.
1583

1584
  @note: this functions uses polling with a hardcoded timeout.
1585

1586
  @type instance: L{objects.Instance}
1587
  @param instance: the instance object
1588
  @type timeout: integer
1589
  @param timeout: maximum timeout for soft shutdown
1590
  @type reason: list of reasons
1591
  @param reason: the reason trail for this shutdown
1592
  @type store_reason: boolean
1593
  @param store_reason: whether to store the shutdown reason trail on file
1594
  @rtype: None
1595

1596
  """
1597
  hv_name = instance.hypervisor
1598
  hyper = hypervisor.GetHypervisor(hv_name)
1599
  iname = instance.name
1600

    
1601
  if instance.name not in hyper.ListInstances(instance.hvparams):
1602
    logging.info("Instance %s not running, doing nothing", iname)
1603
    return
1604

    
1605
  class _TryShutdown:
1606
    def __init__(self):
1607
      self.tried_once = False
1608

    
1609
    def __call__(self):
1610
      if iname not in hyper.ListInstances(instance.hvparams):
1611
        return
1612

    
1613
      try:
1614
        hyper.StopInstance(instance, retry=self.tried_once)
1615
        if store_reason:
1616
          _StoreInstReasonTrail(instance.name, reason)
1617
      except errors.HypervisorError, err:
1618
        if iname not in hyper.ListInstances(instance.hvparams):
1619
          # if the instance is no longer existing, consider this a
1620
          # success and go to cleanup
1621
          return
1622

    
1623
        _Fail("Failed to stop instance %s: %s", iname, err)
1624

    
1625
      self.tried_once = True
1626

    
1627
      raise utils.RetryAgain()
1628

    
1629
  try:
1630
    utils.Retry(_TryShutdown(), 5, timeout)
1631
  except utils.RetryTimeout:
1632
    # the shutdown did not succeed
1633
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1634

    
1635
    try:
1636
      hyper.StopInstance(instance, force=True)
1637
    except errors.HypervisorError, err:
1638
      if iname in hyper.ListInstances(instance.hvparams):
1639
        # only raise an error if the instance still exists, otherwise
1640
        # the error could simply be "instance ... unknown"!
1641
        _Fail("Failed to force stop instance %s: %s", iname, err)
1642

    
1643
    time.sleep(1)
1644

    
1645
    if iname in hyper.ListInstances(instance.hvparams):
1646
      _Fail("Could not shutdown instance %s even by destroy", iname)
1647

    
1648
  try:
1649
    hyper.CleanupInstance(instance.name)
1650
  except errors.HypervisorError, err:
1651
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1652

    
1653
  _RemoveBlockDevLinks(iname, instance.disks)
1654

    
1655

    
1656
def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1657
  """Reboot an instance.
1658

1659
  @type instance: L{objects.Instance}
1660
  @param instance: the instance object to reboot
1661
  @type reboot_type: str
1662
  @param reboot_type: the type of reboot, one the following
1663
    constants:
1664
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1665
        instance OS, do not recreate the VM
1666
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1667
        restart the VM (at the hypervisor level)
1668
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1669
        not accepted here, since that mode is handled differently, in
1670
        cmdlib, and translates into full stop and start of the
1671
        instance (instead of a call_instance_reboot RPC)
1672
  @type shutdown_timeout: integer
1673
  @param shutdown_timeout: maximum timeout for soft shutdown
1674
  @type reason: list of reasons
1675
  @param reason: the reason trail for this reboot
1676
  @rtype: None
1677

1678
  """
1679
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1680
                                                   instance.hvparams)
1681

    
1682
  if instance.name not in running_instances:
1683
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1684

    
1685
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1686
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1687
    try:
1688
      hyper.RebootInstance(instance)
1689
    except errors.HypervisorError, err:
1690
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1691
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1692
    try:
1693
      InstanceShutdown(instance, shutdown_timeout, reason, store_reason=False)
1694
      result = StartInstance(instance, False, reason, store_reason=False)
1695
      _StoreInstReasonTrail(instance.name, reason)
1696
      return result
1697
    except errors.HypervisorError, err:
1698
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1699
  else:
1700
    _Fail("Invalid reboot_type received: %s", reboot_type)
1701

    
1702

    
1703
def InstanceBalloonMemory(instance, memory):
1704
  """Resize an instance's memory.
1705

1706
  @type instance: L{objects.Instance}
1707
  @param instance: the instance object
1708
  @type memory: int
1709
  @param memory: new memory amount in MB
1710
  @rtype: None
1711

1712
  """
1713
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1714
  running = hyper.ListInstances(instance.hvparams)
1715
  if instance.name not in running:
1716
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1717
    return
1718
  try:
1719
    hyper.BalloonInstanceMemory(instance, memory)
1720
  except errors.HypervisorError, err:
1721
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1722

    
1723

    
1724
def MigrationInfo(instance):
1725
  """Gather information about an instance to be migrated.
1726

1727
  @type instance: L{objects.Instance}
1728
  @param instance: the instance definition
1729

1730
  """
1731
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1732
  try:
1733
    info = hyper.MigrationInfo(instance)
1734
  except errors.HypervisorError, err:
1735
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1736
  return info
1737

    
1738

    
1739
def AcceptInstance(instance, info, target):
1740
  """Prepare the node to accept an instance.
1741

1742
  @type instance: L{objects.Instance}
1743
  @param instance: the instance definition
1744
  @type info: string/data (opaque)
1745
  @param info: migration information, from the source node
1746
  @type target: string
1747
  @param target: target host (usually ip), on this node
1748

1749
  """
1750
  # TODO: why is this required only for DTS_EXT_MIRROR?
1751
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1752
    # Create the symlinks, as the disks are not active
1753
    # in any way
1754
    try:
1755
      _GatherAndLinkBlockDevs(instance)
1756
    except errors.BlockDeviceError, err:
1757
      _Fail("Block device error: %s", err, exc=True)
1758

    
1759
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1760
  try:
1761
    hyper.AcceptInstance(instance, info, target)
1762
  except errors.HypervisorError, err:
1763
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1764
      _RemoveBlockDevLinks(instance.name, instance.disks)
1765
    _Fail("Failed to accept instance: %s", err, exc=True)
1766

    
1767

    
1768
def FinalizeMigrationDst(instance, info, success):
1769
  """Finalize any preparation to accept an instance.
1770

1771
  @type instance: L{objects.Instance}
1772
  @param instance: the instance definition
1773
  @type info: string/data (opaque)
1774
  @param info: migration information, from the source node
1775
  @type success: boolean
1776
  @param success: whether the migration was a success or a failure
1777

1778
  """
1779
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1780
  try:
1781
    hyper.FinalizeMigrationDst(instance, info, success)
1782
  except errors.HypervisorError, err:
1783
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1784

    
1785

    
1786
def MigrateInstance(instance, target, live):
1787
  """Migrates an instance to another node.
1788

1789
  @type instance: L{objects.Instance}
1790
  @param instance: the instance definition
1791
  @type target: string
1792
  @param target: the target node name
1793
  @type live: boolean
1794
  @param live: whether the migration should be done live or not (the
1795
      interpretation of this parameter is left to the hypervisor)
1796
  @raise RPCFail: if migration fails for some reason
1797

1798
  """
1799
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1800

    
1801
  try:
1802
    hyper.MigrateInstance(instance, target, live)
1803
  except errors.HypervisorError, err:
1804
    _Fail("Failed to migrate instance: %s", err, exc=True)
1805

    
1806

    
1807
def FinalizeMigrationSource(instance, success, live):
1808
  """Finalize the instance migration on the source node.
1809

1810
  @type instance: L{objects.Instance}
1811
  @param instance: the instance definition of the migrated instance
1812
  @type success: bool
1813
  @param success: whether the migration succeeded or not
1814
  @type live: bool
1815
  @param live: whether the user requested a live migration or not
1816
  @raise RPCFail: If the execution fails for some reason
1817

1818
  """
1819
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1820

    
1821
  try:
1822
    hyper.FinalizeMigrationSource(instance, success, live)
1823
  except Exception, err:  # pylint: disable=W0703
1824
    _Fail("Failed to finalize the migration on the source node: %s", err,
1825
          exc=True)
1826

    
1827

    
1828
def GetMigrationStatus(instance):
1829
  """Get the migration status
1830

1831
  @type instance: L{objects.Instance}
1832
  @param instance: the instance that is being migrated
1833
  @rtype: L{objects.MigrationStatus}
1834
  @return: the status of the current migration (one of
1835
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1836
           progress info that can be retrieved from the hypervisor
1837
  @raise RPCFail: If the migration status cannot be retrieved
1838

1839
  """
1840
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1841
  try:
1842
    return hyper.GetMigrationStatus(instance)
1843
  except Exception, err:  # pylint: disable=W0703
1844
    _Fail("Failed to get migration status: %s", err, exc=True)
1845

    
1846

    
1847
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
1848
  """Creates a block device for an instance.
1849

1850
  @type disk: L{objects.Disk}
1851
  @param disk: the object describing the disk we should create
1852
  @type size: int
1853
  @param size: the size of the physical underlying device, in MiB
1854
  @type owner: str
1855
  @param owner: the name of the instance for which disk is created,
1856
      used for device cache data
1857
  @type on_primary: boolean
1858
  @param on_primary:  indicates if it is the primary node or not
1859
  @type info: string
1860
  @param info: string that will be sent to the physical device
1861
      creation, used for example to set (LVM) tags on LVs
1862
  @type excl_stor: boolean
1863
  @param excl_stor: Whether exclusive_storage is active
1864

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

1869
  """
1870
  # TODO: remove the obsolete "size" argument
1871
  # pylint: disable=W0613
1872
  clist = []
1873
  if disk.children:
1874
    for child in disk.children:
1875
      try:
1876
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1877
      except errors.BlockDeviceError, err:
1878
        _Fail("Can't assemble device %s: %s", child, err)
1879
      if on_primary or disk.AssembleOnSecondary():
1880
        # we need the children open in case the device itself has to
1881
        # be assembled
1882
        try:
1883
          # pylint: disable=E1103
1884
          crdev.Open()
1885
        except errors.BlockDeviceError, err:
1886
          _Fail("Can't make child '%s' read-write: %s", child, err)
1887
      clist.append(crdev)
1888

    
1889
  try:
1890
    device = bdev.Create(disk, clist, excl_stor)
1891
  except errors.BlockDeviceError, err:
1892
    _Fail("Can't create block device: %s", err)
1893

    
1894
  if on_primary or disk.AssembleOnSecondary():
1895
    try:
1896
      device.Assemble()
1897
    except errors.BlockDeviceError, err:
1898
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1899
    if on_primary or disk.OpenOnSecondary():
1900
      try:
1901
        device.Open(force=True)
1902
      except errors.BlockDeviceError, err:
1903
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1904
    DevCacheManager.UpdateCache(device.dev_path, owner,
1905
                                on_primary, disk.iv_name)
1906

    
1907
  device.SetInfo(info)
1908

    
1909
  return device.unique_id
1910

    
1911

    
1912
def _WipeDevice(path, offset, size):
1913
  """This function actually wipes the device.
1914

1915
  @param path: The path to the device to wipe
1916
  @param offset: The offset in MiB in the file
1917
  @param size: The size in MiB to write
1918

1919
  """
1920
  # Internal sizes are always in Mebibytes; if the following "dd" command
1921
  # should use a different block size the offset and size given to this
1922
  # function must be adjusted accordingly before being passed to "dd".
1923
  block_size = 1024 * 1024
1924

    
1925
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1926
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
1927
         "count=%d" % size]
1928
  result = utils.RunCmd(cmd)
1929

    
1930
  if result.failed:
1931
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1932
          result.fail_reason, result.output)
1933

    
1934

    
1935
def BlockdevWipe(disk, offset, size):
1936
  """Wipes a block device.
1937

1938
  @type disk: L{objects.Disk}
1939
  @param disk: the disk object we want to wipe
1940
  @type offset: int
1941
  @param offset: The offset in MiB in the file
1942
  @type size: int
1943
  @param size: The size in MiB to write
1944

1945
  """
1946
  try:
1947
    rdev = _RecursiveFindBD(disk)
1948
  except errors.BlockDeviceError:
1949
    rdev = None
1950

    
1951
  if not rdev:
1952
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1953

    
1954
  # Do cross verify some of the parameters
1955
  if offset < 0:
1956
    _Fail("Negative offset")
1957
  if size < 0:
1958
    _Fail("Negative size")
1959
  if offset > rdev.size:
1960
    _Fail("Offset is bigger than device size")
1961
  if (offset + size) > rdev.size:
1962
    _Fail("The provided offset and size to wipe is bigger than device size")
1963

    
1964
  _WipeDevice(rdev.dev_path, offset, size)
1965

    
1966

    
1967
def BlockdevPauseResumeSync(disks, pause):
1968
  """Pause or resume the sync of the block device.
1969

1970
  @type disks: list of L{objects.Disk}
1971
  @param disks: the disks object we want to pause/resume
1972
  @type pause: bool
1973
  @param pause: Wheater to pause or resume
1974

1975
  """
1976
  success = []
1977
  for disk in disks:
1978
    try:
1979
      rdev = _RecursiveFindBD(disk)
1980
    except errors.BlockDeviceError:
1981
      rdev = None
1982

    
1983
    if not rdev:
1984
      success.append((False, ("Cannot change sync for device %s:"
1985
                              " device not found" % disk.iv_name)))
1986
      continue
1987

    
1988
    result = rdev.PauseResumeSync(pause)
1989

    
1990
    if result:
1991
      success.append((result, None))
1992
    else:
1993
      if pause:
1994
        msg = "Pause"
1995
      else:
1996
        msg = "Resume"
1997
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1998

    
1999
  return success
2000

    
2001

    
2002
def BlockdevRemove(disk):
2003
  """Remove a block device.
2004

2005
  @note: This is intended to be called recursively.
2006

2007
  @type disk: L{objects.Disk}
2008
  @param disk: the disk object we should remove
2009
  @rtype: boolean
2010
  @return: the success of the operation
2011

2012
  """
2013
  msgs = []
2014
  try:
2015
    rdev = _RecursiveFindBD(disk)
2016
  except errors.BlockDeviceError, err:
2017
    # probably can't attach
2018
    logging.info("Can't attach to device %s in remove", disk)
2019
    rdev = None
2020
  if rdev is not None:
2021
    r_path = rdev.dev_path
2022
    try:
2023
      rdev.Remove()
2024
    except errors.BlockDeviceError, err:
2025
      msgs.append(str(err))
2026
    if not msgs:
2027
      DevCacheManager.RemoveCache(r_path)
2028

    
2029
  if disk.children:
2030
    for child in disk.children:
2031
      try:
2032
        BlockdevRemove(child)
2033
      except RPCFail, err:
2034
        msgs.append(str(err))
2035

    
2036
  if msgs:
2037
    _Fail("; ".join(msgs))
2038

    
2039

    
2040
def _RecursiveAssembleBD(disk, owner, as_primary):
2041
  """Activate a block device for an instance.
2042

2043
  This is run on the primary and secondary nodes for an instance.
2044

2045
  @note: this function is called recursively.
2046

2047
  @type disk: L{objects.Disk}
2048
  @param disk: the disk we try to assemble
2049
  @type owner: str
2050
  @param owner: the name of the instance which owns the disk
2051
  @type as_primary: boolean
2052
  @param as_primary: if we should make the block device
2053
      read/write
2054

2055
  @return: the assembled device or None (in case no device
2056
      was assembled)
2057
  @raise errors.BlockDeviceError: in case there is an error
2058
      during the activation of the children or the device
2059
      itself
2060

2061
  """
2062
  children = []
2063
  if disk.children:
2064
    mcn = disk.ChildrenNeeded()
2065
    if mcn == -1:
2066
      mcn = 0 # max number of Nones allowed
2067
    else:
2068
      mcn = len(disk.children) - mcn # max number of Nones
2069
    for chld_disk in disk.children:
2070
      try:
2071
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
2072
      except errors.BlockDeviceError, err:
2073
        if children.count(None) >= mcn:
2074
          raise
2075
        cdev = None
2076
        logging.error("Error in child activation (but continuing): %s",
2077
                      str(err))
2078
      children.append(cdev)
2079

    
2080
  if as_primary or disk.AssembleOnSecondary():
2081
    r_dev = bdev.Assemble(disk, children)
2082
    result = r_dev
2083
    if as_primary or disk.OpenOnSecondary():
2084
      r_dev.Open()
2085
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
2086
                                as_primary, disk.iv_name)
2087

    
2088
  else:
2089
    result = True
2090
  return result
2091

    
2092

    
2093
def BlockdevAssemble(disk, owner, as_primary, idx):
2094
  """Activate a block device for an instance.
2095

2096
  This is a wrapper over _RecursiveAssembleBD.
2097

2098
  @rtype: str or boolean
2099
  @return: a C{/dev/...} path for primary nodes, and
2100
      C{True} for secondary nodes
2101

2102
  """
2103
  try:
2104
    result = _RecursiveAssembleBD(disk, owner, as_primary)
2105
    if isinstance(result, BlockDev):
2106
      # pylint: disable=E1103
2107
      result = result.dev_path
2108
      if as_primary:
2109
        _SymlinkBlockDev(owner, result, idx)
2110
  except errors.BlockDeviceError, err:
2111
    _Fail("Error while assembling disk: %s", err, exc=True)
2112
  except OSError, err:
2113
    _Fail("Error while symlinking disk: %s", err, exc=True)
2114

    
2115
  return result
2116

    
2117

    
2118
def BlockdevShutdown(disk):
2119
  """Shut down a block device.
2120

2121
  First, if the device is assembled (Attach() is successful), then
2122
  the device is shutdown. Then the children of the device are
2123
  shutdown.
2124

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

2129
  @type disk: L{objects.Disk}
2130
  @param disk: the description of the disk we should
2131
      shutdown
2132
  @rtype: None
2133

2134
  """
2135
  msgs = []
2136
  r_dev = _RecursiveFindBD(disk)
2137
  if r_dev is not None:
2138
    r_path = r_dev.dev_path
2139
    try:
2140
      r_dev.Shutdown()
2141
      DevCacheManager.RemoveCache(r_path)
2142
    except errors.BlockDeviceError, err:
2143
      msgs.append(str(err))
2144

    
2145
  if disk.children:
2146
    for child in disk.children:
2147
      try:
2148
        BlockdevShutdown(child)
2149
      except RPCFail, err:
2150
        msgs.append(str(err))
2151

    
2152
  if msgs:
2153
    _Fail("; ".join(msgs))
2154

    
2155

    
2156
def BlockdevAddchildren(parent_cdev, new_cdevs):
2157
  """Extend a mirrored block device.
2158

2159
  @type parent_cdev: L{objects.Disk}
2160
  @param parent_cdev: the disk to which we should add children
2161
  @type new_cdevs: list of L{objects.Disk}
2162
  @param new_cdevs: the list of children which we should add
2163
  @rtype: None
2164

2165
  """
2166
  parent_bdev = _RecursiveFindBD(parent_cdev)
2167
  if parent_bdev is None:
2168
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
2169
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
2170
  if new_bdevs.count(None) > 0:
2171
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
2172
  parent_bdev.AddChildren(new_bdevs)
2173

    
2174

    
2175
def BlockdevRemovechildren(parent_cdev, new_cdevs):
2176
  """Shrink a mirrored block device.
2177

2178
  @type parent_cdev: L{objects.Disk}
2179
  @param parent_cdev: the disk from which we should remove children
2180
  @type new_cdevs: list of L{objects.Disk}
2181
  @param new_cdevs: the list of children which we should remove
2182
  @rtype: None
2183

2184
  """
2185
  parent_bdev = _RecursiveFindBD(parent_cdev)
2186
  if parent_bdev is None:
2187
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
2188
  devs = []
2189
  for disk in new_cdevs:
2190
    rpath = disk.StaticDevPath()
2191
    if rpath is None:
2192
      bd = _RecursiveFindBD(disk)
2193
      if bd is None:
2194
        _Fail("Can't find device %s while removing children", disk)
2195
      else:
2196
        devs.append(bd.dev_path)
2197
    else:
2198
      if not utils.IsNormAbsPath(rpath):
2199
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
2200
      devs.append(rpath)
2201
  parent_bdev.RemoveChildren(devs)
2202

    
2203

    
2204
def BlockdevGetmirrorstatus(disks):
2205
  """Get the mirroring status of a list of devices.
2206

2207
  @type disks: list of L{objects.Disk}
2208
  @param disks: the list of disks which we should query
2209
  @rtype: disk
2210
  @return: List of L{objects.BlockDevStatus}, one for each disk
2211
  @raise errors.BlockDeviceError: if any of the disks cannot be
2212
      found
2213

2214
  """
2215
  stats = []
2216
  for dsk in disks:
2217
    rbd = _RecursiveFindBD(dsk)
2218
    if rbd is None:
2219
      _Fail("Can't find device %s", dsk)
2220

    
2221
    stats.append(rbd.CombinedSyncStatus())
2222

    
2223
  return stats
2224

    
2225

    
2226
def BlockdevGetmirrorstatusMulti(disks):
2227
  """Get the mirroring status of a list of devices.
2228

2229
  @type disks: list of L{objects.Disk}
2230
  @param disks: the list of disks which we should query
2231
  @rtype: disk
2232
  @return: List of tuples, (bool, status), one for each disk; bool denotes
2233
    success/failure, status is L{objects.BlockDevStatus} on success, string
2234
    otherwise
2235

2236
  """
2237
  result = []
2238
  for disk in disks:
2239
    try:
2240
      rbd = _RecursiveFindBD(disk)
2241
      if rbd is None:
2242
        result.append((False, "Can't find device %s" % disk))
2243
        continue
2244

    
2245
      status = rbd.CombinedSyncStatus()
2246
    except errors.BlockDeviceError, err:
2247
      logging.exception("Error while getting disk status")
2248
      result.append((False, str(err)))
2249
    else:
2250
      result.append((True, status))
2251

    
2252
  assert len(disks) == len(result)
2253

    
2254
  return result
2255

    
2256

    
2257
def _RecursiveFindBD(disk):
2258
  """Check if a device is activated.
2259

2260
  If so, return information about the real device.
2261

2262
  @type disk: L{objects.Disk}
2263
  @param disk: the disk object we need to find
2264

2265
  @return: None if the device can't be found,
2266
      otherwise the device instance
2267

2268
  """
2269
  children = []
2270
  if disk.children:
2271
    for chdisk in disk.children:
2272
      children.append(_RecursiveFindBD(chdisk))
2273

    
2274
  return bdev.FindDevice(disk, children)
2275

    
2276

    
2277
def _OpenRealBD(disk):
2278
  """Opens the underlying block device of a disk.
2279

2280
  @type disk: L{objects.Disk}
2281
  @param disk: the disk object we want to open
2282

2283
  """
2284
  real_disk = _RecursiveFindBD(disk)
2285
  if real_disk is None:
2286
    _Fail("Block device '%s' is not set up", disk)
2287

    
2288
  real_disk.Open()
2289

    
2290
  return real_disk
2291

    
2292

    
2293
def BlockdevFind(disk):
2294
  """Check if a device is activated.
2295

2296
  If it is, return information about the real device.
2297

2298
  @type disk: L{objects.Disk}
2299
  @param disk: the disk to find
2300
  @rtype: None or objects.BlockDevStatus
2301
  @return: None if the disk cannot be found, otherwise a the current
2302
           information
2303

2304
  """
2305
  try:
2306
    rbd = _RecursiveFindBD(disk)
2307
  except errors.BlockDeviceError, err:
2308
    _Fail("Failed to find device: %s", err, exc=True)
2309

    
2310
  if rbd is None:
2311
    return None
2312

    
2313
  return rbd.GetSyncStatus()
2314

    
2315

    
2316
def BlockdevGetdimensions(disks):
2317
  """Computes the size of the given disks.
2318

2319
  If a disk is not found, returns None instead.
2320

2321
  @type disks: list of L{objects.Disk}
2322
  @param disks: the list of disk to compute the size for
2323
  @rtype: list
2324
  @return: list with elements None if the disk cannot be found,
2325
      otherwise the pair (size, spindles), where spindles is None if the
2326
      device doesn't support that
2327

2328
  """
2329
  result = []
2330
  for cf in disks:
2331
    try:
2332
      rbd = _RecursiveFindBD(cf)
2333
    except errors.BlockDeviceError:
2334
      result.append(None)
2335
      continue
2336
    if rbd is None:
2337
      result.append(None)
2338
    else:
2339
      result.append(rbd.GetActualDimensions())
2340
  return result
2341

    
2342

    
2343
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2344
  """Export a block device to a remote node.
2345

2346
  @type disk: L{objects.Disk}
2347
  @param disk: the description of the disk to export
2348
  @type dest_node: str
2349
  @param dest_node: the destination node to export to
2350
  @type dest_path: str
2351
  @param dest_path: the destination path on the target node
2352
  @type cluster_name: str
2353
  @param cluster_name: the cluster name, needed for SSH hostalias
2354
  @rtype: None
2355

2356
  """
2357
  real_disk = _OpenRealBD(disk)
2358

    
2359
  # the block size on the read dd is 1MiB to match our units
2360
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2361
                               "dd if=%s bs=1048576 count=%s",
2362
                               real_disk.dev_path, str(disk.size))
2363

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

    
2373
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2374
                                                   constants.SSH_LOGIN_USER,
2375
                                                   destcmd)
2376

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

    
2380
  result = utils.RunCmd(["bash", "-c", command])
2381

    
2382
  if result.failed:
2383
    _Fail("Disk copy command '%s' returned error: %s"
2384
          " output: %s", command, result.fail_reason, result.output)
2385

    
2386

    
2387
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2388
  """Write a file to the filesystem.
2389

2390
  This allows the master to overwrite(!) a file. It will only perform
2391
  the operation if the file belongs to a list of configuration files.
2392

2393
  @type file_name: str
2394
  @param file_name: the target file name
2395
  @type data: str
2396
  @param data: the new contents of the file
2397
  @type mode: int
2398
  @param mode: the mode to give the file (can be None)
2399
  @type uid: string
2400
  @param uid: the owner of the file
2401
  @type gid: string
2402
  @param gid: the group of the file
2403
  @type atime: float
2404
  @param atime: the atime to set on the file (can be None)
2405
  @type mtime: float
2406
  @param mtime: the mtime to set on the file (can be None)
2407
  @rtype: None
2408

2409
  """
2410
  file_name = vcluster.LocalizeVirtualPath(file_name)
2411

    
2412
  if not os.path.isabs(file_name):
2413
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2414

    
2415
  if file_name not in _ALLOWED_UPLOAD_FILES:
2416
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2417
          file_name)
2418

    
2419
  raw_data = _Decompress(data)
2420

    
2421
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2422
    _Fail("Invalid username/groupname type")
2423

    
2424
  getents = runtime.GetEnts()
2425
  uid = getents.LookupUser(uid)
2426
  gid = getents.LookupGroup(gid)
2427

    
2428
  utils.SafeWriteFile(file_name, None,
2429
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2430
                      atime=atime, mtime=mtime)
2431

    
2432

    
2433
def RunOob(oob_program, command, node, timeout):
2434
  """Executes oob_program with given command on given node.
2435

2436
  @param oob_program: The path to the executable oob_program
2437
  @param command: The command to invoke on oob_program
2438
  @param node: The node given as an argument to the program
2439
  @param timeout: Timeout after which we kill the oob program
2440

2441
  @return: stdout
2442
  @raise RPCFail: If execution fails for some reason
2443

2444
  """
2445
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2446

    
2447
  if result.failed:
2448
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2449
          result.fail_reason, result.output)
2450

    
2451
  return result.stdout
2452

    
2453

    
2454
def _OSOndiskAPIVersion(os_dir):
2455
  """Compute and return the API version of a given OS.
2456

2457
  This function will try to read the API version of the OS residing in
2458
  the 'os_dir' directory.
2459

2460
  @type os_dir: str
2461
  @param os_dir: the directory in which we should look for the OS
2462
  @rtype: tuple
2463
  @return: tuple (status, data) with status denoting the validity and
2464
      data holding either the vaid versions or an error message
2465

2466
  """
2467
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2468

    
2469
  try:
2470
    st = os.stat(api_file)
2471
  except EnvironmentError, err:
2472
    return False, ("Required file '%s' not found under path %s: %s" %
2473
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2474

    
2475
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2476
    return False, ("File '%s' in %s is not a regular file" %
2477
                   (constants.OS_API_FILE, os_dir))
2478

    
2479
  try:
2480
    api_versions = utils.ReadFile(api_file).splitlines()
2481
  except EnvironmentError, err:
2482
    return False, ("Error while reading the API version file at %s: %s" %
2483
                   (api_file, utils.ErrnoOrStr(err)))
2484

    
2485
  try:
2486
    api_versions = [int(version.strip()) for version in api_versions]
2487
  except (TypeError, ValueError), err:
2488
    return False, ("API version(s) can't be converted to integer: %s" %
2489
                   str(err))
2490

    
2491
  return True, api_versions
2492

    
2493

    
2494
def DiagnoseOS(top_dirs=None):
2495
  """Compute the validity for all OSes.
2496

2497
  @type top_dirs: list
2498
  @param top_dirs: the list of directories in which to
2499
      search (if not given defaults to
2500
      L{pathutils.OS_SEARCH_PATH})
2501
  @rtype: list of L{objects.OS}
2502
  @return: a list of tuples (name, path, status, diagnose, variants,
2503
      parameters, api_version) for all (potential) OSes under all
2504
      search paths, where:
2505
          - name is the (potential) OS name
2506
          - path is the full path to the OS
2507
          - status True/False is the validity of the OS
2508
          - diagnose is the error message for an invalid OS, otherwise empty
2509
          - variants is a list of supported OS variants, if any
2510
          - parameters is a list of (name, help) parameters, if any
2511
          - api_version is a list of support OS API versions
2512

2513
  """
2514
  if top_dirs is None:
2515
    top_dirs = pathutils.OS_SEARCH_PATH
2516

    
2517
  result = []
2518
  for dir_name in top_dirs:
2519
    if os.path.isdir(dir_name):
2520
      try:
2521
        f_names = utils.ListVisibleFiles(dir_name)
2522
      except EnvironmentError, err:
2523
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2524
        break
2525
      for name in f_names:
2526
        os_path = utils.PathJoin(dir_name, name)
2527
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2528
        if status:
2529
          diagnose = ""
2530
          variants = os_inst.supported_variants
2531
          parameters = os_inst.supported_parameters
2532
          api_versions = os_inst.api_versions
2533
        else:
2534
          diagnose = os_inst
2535
          variants = parameters = api_versions = []
2536
        result.append((name, os_path, status, diagnose, variants,
2537
                       parameters, api_versions))
2538

    
2539
  return result
2540

    
2541

    
2542
def _TryOSFromDisk(name, base_dir=None):
2543
  """Create an OS instance from disk.
2544

2545
  This function will return an OS instance if the given name is a
2546
  valid OS name.
2547

2548
  @type base_dir: string
2549
  @keyword base_dir: Base directory containing OS installations.
2550
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2551
  @rtype: tuple
2552
  @return: success and either the OS instance if we find a valid one,
2553
      or error message
2554

2555
  """
2556
  if base_dir is None:
2557
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2558
  else:
2559
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2560

    
2561
  if os_dir is None:
2562
    return False, "Directory for OS %s not found in search path" % name
2563

    
2564
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2565
  if not status:
2566
    # push the error up
2567
    return status, api_versions
2568

    
2569
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2570
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2571
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2572

    
2573
  # OS Files dictionary, we will populate it with the absolute path
2574
  # names; if the value is True, then it is a required file, otherwise
2575
  # an optional one
2576
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2577

    
2578
  if max(api_versions) >= constants.OS_API_V15:
2579
    os_files[constants.OS_VARIANTS_FILE] = False
2580

    
2581
  if max(api_versions) >= constants.OS_API_V20:
2582
    os_files[constants.OS_PARAMETERS_FILE] = True
2583
  else:
2584
    del os_files[constants.OS_SCRIPT_VERIFY]
2585

    
2586
  for (filename, required) in os_files.items():
2587
    os_files[filename] = utils.PathJoin(os_dir, filename)
2588

    
2589
    try:
2590
      st = os.stat(os_files[filename])
2591
    except EnvironmentError, err:
2592
      if err.errno == errno.ENOENT and not required:
2593
        del os_files[filename]
2594
        continue
2595
      return False, ("File '%s' under path '%s' is missing (%s)" %
2596
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2597

    
2598
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2599
      return False, ("File '%s' under path '%s' is not a regular file" %
2600
                     (filename, os_dir))
2601

    
2602
    if filename in constants.OS_SCRIPTS:
2603
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2604
        return False, ("File '%s' under path '%s' is not executable" %
2605
                       (filename, os_dir))
2606

    
2607
  variants = []
2608
  if constants.OS_VARIANTS_FILE in os_files:
2609
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2610
    try:
2611
      variants = \
2612
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2613
    except EnvironmentError, err:
2614
      # we accept missing files, but not other errors
2615
      if err.errno != errno.ENOENT:
2616
        return False, ("Error while reading the OS variants file at %s: %s" %
2617
                       (variants_file, utils.ErrnoOrStr(err)))
2618

    
2619
  parameters = []
2620
  if constants.OS_PARAMETERS_FILE in os_files:
2621
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2622
    try:
2623
      parameters = utils.ReadFile(parameters_file).splitlines()
2624
    except EnvironmentError, err:
2625
      return False, ("Error while reading the OS parameters file at %s: %s" %
2626
                     (parameters_file, utils.ErrnoOrStr(err)))
2627
    parameters = [v.split(None, 1) for v in parameters]
2628

    
2629
  os_obj = objects.OS(name=name, path=os_dir,
2630
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2631
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2632
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2633
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2634
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2635
                                                 None),
2636
                      supported_variants=variants,
2637
                      supported_parameters=parameters,
2638
                      api_versions=api_versions)
2639
  return True, os_obj
2640

    
2641

    
2642
def OSFromDisk(name, base_dir=None):
2643
  """Create an OS instance from disk.
2644

2645
  This function will return an OS instance if the given name is a
2646
  valid OS name. Otherwise, it will raise an appropriate
2647
  L{RPCFail} exception, detailing why this is not a valid OS.
2648

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

2652
  @type base_dir: string
2653
  @keyword base_dir: Base directory containing OS installations.
2654
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2655
  @rtype: L{objects.OS}
2656
  @return: the OS instance if we find a valid one
2657
  @raise RPCFail: if we don't find a valid OS
2658

2659
  """
2660
  name_only = objects.OS.GetName(name)
2661
  status, payload = _TryOSFromDisk(name_only, base_dir)
2662

    
2663
  if not status:
2664
    _Fail(payload)
2665

    
2666
  return payload
2667

    
2668

    
2669
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2670
  """Calculate the basic environment for an os script.
2671

2672
  @type os_name: str
2673
  @param os_name: full operating system name (including variant)
2674
  @type inst_os: L{objects.OS}
2675
  @param inst_os: operating system for which the environment is being built
2676
  @type os_params: dict
2677
  @param os_params: the OS parameters
2678
  @type debug: integer
2679
  @param debug: debug level (0 or 1, for OS Api 10)
2680
  @rtype: dict
2681
  @return: dict of environment variables
2682
  @raise errors.BlockDeviceError: if the block device
2683
      cannot be found
2684

2685
  """
2686
  result = {}
2687
  api_version = \
2688
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2689
  result["OS_API_VERSION"] = "%d" % api_version
2690
  result["OS_NAME"] = inst_os.name
2691
  result["DEBUG_LEVEL"] = "%d" % debug
2692

    
2693
  # OS variants
2694
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2695
    variant = objects.OS.GetVariant(os_name)
2696
    if not variant:
2697
      variant = inst_os.supported_variants[0]
2698
  else:
2699
    variant = ""
2700
  result["OS_VARIANT"] = variant
2701

    
2702
  # OS params
2703
  for pname, pvalue in os_params.items():
2704
    result["OSP_%s" % pname.upper()] = pvalue
2705

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

    
2711
  return result
2712

    
2713

    
2714
def OSEnvironment(instance, inst_os, debug=0):
2715
  """Calculate the environment for an os script.
2716

2717
  @type instance: L{objects.Instance}
2718
  @param instance: target instance for the os script run
2719
  @type inst_os: L{objects.OS}
2720
  @param inst_os: operating system for which the environment is being built
2721
  @type debug: integer
2722
  @param debug: debug level (0 or 1, for OS Api 10)
2723
  @rtype: dict
2724
  @return: dict of environment variables
2725
  @raise errors.BlockDeviceError: if the block device
2726
      cannot be found
2727

2728
  """
2729
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2730

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

    
2734
  result["HYPERVISOR"] = instance.hypervisor
2735
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2736
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2737
  result["INSTANCE_SECONDARY_NODES"] = \
2738
      ("%s" % " ".join(instance.secondary_nodes))
2739

    
2740
  # Disks
2741
  for idx, disk in enumerate(instance.disks):
2742
    real_disk = _OpenRealBD(disk)
2743
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2744
    result["DISK_%d_ACCESS" % idx] = disk.mode
2745
    if constants.HV_DISK_TYPE in instance.hvparams:
2746
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2747
        instance.hvparams[constants.HV_DISK_TYPE]
2748
    if disk.dev_type in constants.LDS_BLOCK:
2749
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2750
    elif disk.dev_type == constants.LD_FILE:
2751
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2752
        "file:%s" % disk.physical_id[0]
2753

    
2754
  # NICs
2755
  for idx, nic in enumerate(instance.nics):
2756
    result["NIC_%d_MAC" % idx] = nic.mac
2757
    if nic.ip:
2758
      result["NIC_%d_IP" % idx] = nic.ip
2759
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2760
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2761
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2762
    if nic.nicparams[constants.NIC_LINK]:
2763
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2764
    if nic.netinfo:
2765
      nobj = objects.Network.FromDict(nic.netinfo)
2766
      result.update(nobj.HooksDict("NIC_%d_" % idx))
2767
    if constants.HV_NIC_TYPE in instance.hvparams:
2768
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2769
        instance.hvparams[constants.HV_NIC_TYPE]
2770

    
2771
  # HV/BE params
2772
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2773
    for key, value in source.items():
2774
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2775

    
2776
  return result
2777

    
2778

    
2779
def DiagnoseExtStorage(top_dirs=None):
2780
  """Compute the validity for all ExtStorage Providers.
2781

2782
  @type top_dirs: list
2783
  @param top_dirs: the list of directories in which to
2784
      search (if not given defaults to
2785
      L{pathutils.ES_SEARCH_PATH})
2786
  @rtype: list of L{objects.ExtStorage}
2787
  @return: a list of tuples (name, path, status, diagnose, parameters)
2788
      for all (potential) ExtStorage Providers under all
2789
      search paths, where:
2790
          - name is the (potential) ExtStorage Provider
2791
          - path is the full path to the ExtStorage Provider
2792
          - status True/False is the validity of the ExtStorage Provider
2793
          - diagnose is the error message for an invalid ExtStorage Provider,
2794
            otherwise empty
2795
          - parameters is a list of (name, help) parameters, if any
2796

2797
  """
2798
  if top_dirs is None:
2799
    top_dirs = pathutils.ES_SEARCH_PATH
2800

    
2801
  result = []
2802
  for dir_name in top_dirs:
2803
    if os.path.isdir(dir_name):
2804
      try:
2805
        f_names = utils.ListVisibleFiles(dir_name)
2806
      except EnvironmentError, err:
2807
        logging.exception("Can't list the ExtStorage directory %s: %s",
2808
                          dir_name, err)
2809
        break
2810
      for name in f_names:
2811
        es_path = utils.PathJoin(dir_name, name)
2812
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2813
        if status:
2814
          diagnose = ""
2815
          parameters = es_inst.supported_parameters
2816
        else:
2817
          diagnose = es_inst
2818
          parameters = []
2819
        result.append((name, es_path, status, diagnose, parameters))
2820

    
2821
  return result
2822

    
2823

    
2824
def BlockdevGrow(disk, amount, dryrun, backingstore):
2825
  """Grow a stack of block devices.
2826

2827
  This function is called recursively, with the childrens being the
2828
  first ones to resize.
2829

2830
  @type disk: L{objects.Disk}
2831
  @param disk: the disk to be grown
2832
  @type amount: integer
2833
  @param amount: the amount (in mebibytes) to grow with
2834
  @type dryrun: boolean
2835
  @param dryrun: whether to execute the operation in simulation mode
2836
      only, without actually increasing the size
2837
  @param backingstore: whether to execute the operation on backing storage
2838
      only, or on "logical" storage only; e.g. DRBD is logical storage,
2839
      whereas LVM, file, RBD are backing storage
2840
  @rtype: (status, result)
2841
  @return: a tuple with the status of the operation (True/False), and
2842
      the errors message if status is False
2843

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

    
2849
  try:
2850
    r_dev.Grow(amount, dryrun, backingstore)
2851
  except errors.BlockDeviceError, err:
2852
    _Fail("Failed to grow block device: %s", err, exc=True)
2853

    
2854

    
2855
def BlockdevSnapshot(disk):
2856
  """Create a snapshot copy of a block device.
2857

2858
  This function is called recursively, and the snapshot is actually created
2859
  just for the leaf lvm backend device.
2860

2861
  @type disk: L{objects.Disk}
2862
  @param disk: the disk to be snapshotted
2863
  @rtype: string
2864
  @return: snapshot disk ID as (vg, lv)
2865

2866
  """
2867
  if disk.dev_type == constants.LD_DRBD8:
2868
    if not disk.children:
2869
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2870
            disk.unique_id)
2871
    return BlockdevSnapshot(disk.children[0])
2872
  elif disk.dev_type == constants.LD_LV:
2873
    r_dev = _RecursiveFindBD(disk)
2874
    if r_dev is not None:
2875
      # FIXME: choose a saner value for the snapshot size
2876
      # let's stay on the safe side and ask for the full size, for now
2877
      return r_dev.Snapshot(disk.size)
2878
    else:
2879
      _Fail("Cannot find block device %s", disk)
2880
  else:
2881
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2882
          disk.unique_id, disk.dev_type)
2883

    
2884

    
2885
def BlockdevSetInfo(disk, info):
2886
  """Sets 'metadata' information on block devices.
2887

2888
  This function sets 'info' metadata on block devices. Initial
2889
  information is set at device creation; this function should be used
2890
  for example after renames.
2891

2892
  @type disk: L{objects.Disk}
2893
  @param disk: the disk to be grown
2894
  @type info: string
2895
  @param info: new 'info' metadata
2896
  @rtype: (status, result)
2897
  @return: a tuple with the status of the operation (True/False), and
2898
      the errors message if status is False
2899

2900
  """
2901
  r_dev = _RecursiveFindBD(disk)
2902
  if r_dev is None:
2903
    _Fail("Cannot find block device %s", disk)
2904

    
2905
  try:
2906
    r_dev.SetInfo(info)
2907
  except errors.BlockDeviceError, err:
2908
    _Fail("Failed to set information on block device: %s", err, exc=True)
2909

    
2910

    
2911
def FinalizeExport(instance, snap_disks):
2912
  """Write out the export configuration information.
2913

2914
  @type instance: L{objects.Instance}
2915
  @param instance: the instance which we export, used for
2916
      saving configuration
2917
  @type snap_disks: list of L{objects.Disk}
2918
  @param snap_disks: list of snapshot block devices, which
2919
      will be used to get the actual name of the dump file
2920

2921
  @rtype: None
2922

2923
  """
2924
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
2925
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
2926

    
2927
  config = objects.SerializableConfigParser()
2928

    
2929
  config.add_section(constants.INISECT_EXP)
2930
  config.set(constants.INISECT_EXP, "version", "0")
2931
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2932
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2933
  config.set(constants.INISECT_EXP, "os", instance.os)
2934
  config.set(constants.INISECT_EXP, "compression", "none")
2935

    
2936
  config.add_section(constants.INISECT_INS)
2937
  config.set(constants.INISECT_INS, "name", instance.name)
2938
  config.set(constants.INISECT_INS, "maxmem", "%d" %
2939
             instance.beparams[constants.BE_MAXMEM])
2940
  config.set(constants.INISECT_INS, "minmem", "%d" %
2941
             instance.beparams[constants.BE_MINMEM])
2942
  # "memory" is deprecated, but useful for exporting to old ganeti versions
2943
  config.set(constants.INISECT_INS, "memory", "%d" %
2944
             instance.beparams[constants.BE_MAXMEM])
2945
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2946
             instance.beparams[constants.BE_VCPUS])
2947
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2948
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2949
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2950

    
2951
  nic_total = 0
2952
  for nic_count, nic in enumerate(instance.nics):
2953
    nic_total += 1
2954
    config.set(constants.INISECT_INS, "nic%d_mac" %
2955
               nic_count, "%s" % nic.mac)
2956
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2957
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
2958
               "%s" % nic.network)
2959
    for param in constants.NICS_PARAMETER_TYPES:
2960
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2961
                 "%s" % nic.nicparams.get(param, None))
2962
  # TODO: redundant: on load can read nics until it doesn't exist
2963
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2964

    
2965
  disk_total = 0
2966
  for disk_count, disk in enumerate(snap_disks):
2967
    if disk:
2968
      disk_total += 1
2969
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2970
                 ("%s" % disk.iv_name))
2971
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2972
                 ("%s" % disk.physical_id[1]))
2973
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2974
                 ("%d" % disk.size))
2975

    
2976
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2977

    
2978
  # New-style hypervisor/backend parameters
2979

    
2980
  config.add_section(constants.INISECT_HYP)
2981
  for name, value in instance.hvparams.items():
2982
    if name not in constants.HVC_GLOBALS:
2983
      config.set(constants.INISECT_HYP, name, str(value))
2984

    
2985
  config.add_section(constants.INISECT_BEP)
2986
  for name, value in instance.beparams.items():
2987
    config.set(constants.INISECT_BEP, name, str(value))
2988

    
2989
  config.add_section(constants.INISECT_OSP)
2990
  for name, value in instance.osparams.items():
2991
    config.set(constants.INISECT_OSP, name, str(value))
2992

    
2993
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2994
                  data=config.Dumps())
2995
  shutil.rmtree(finaldestdir, ignore_errors=True)
2996
  shutil.move(destdir, finaldestdir)
2997

    
2998

    
2999
def ExportInfo(dest):
3000
  """Get export configuration information.
3001

3002
  @type dest: str
3003
  @param dest: directory containing the export
3004

3005
  @rtype: L{objects.SerializableConfigParser}
3006
  @return: a serializable config file containing the
3007
      export info
3008

3009
  """
3010
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
3011

    
3012
  config = objects.SerializableConfigParser()
3013
  config.read(cff)
3014

    
3015
  if (not config.has_section(constants.INISECT_EXP) or
3016
      not config.has_section(constants.INISECT_INS)):
3017
    _Fail("Export info file doesn't have the required fields")
3018

    
3019
  return config.Dumps()
3020

    
3021

    
3022
def ListExports():
3023
  """Return a list of exports currently available on this machine.
3024

3025
  @rtype: list
3026
  @return: list of the exports
3027

3028
  """
3029
  if os.path.isdir(pathutils.EXPORT_DIR):
3030
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
3031
  else:
3032
    _Fail("No exports directory")
3033

    
3034

    
3035
def RemoveExport(export):
3036
  """Remove an existing export from the node.
3037

3038
  @type export: str
3039
  @param export: the name of the export to remove
3040
  @rtype: None
3041

3042
  """
3043
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
3044

    
3045
  try:
3046
    shutil.rmtree(target)
3047
  except EnvironmentError, err:
3048
    _Fail("Error while removing the export: %s", err, exc=True)
3049

    
3050

    
3051
def BlockdevRename(devlist):
3052
  """Rename a list of block devices.
3053

3054
  @type devlist: list of tuples
3055
  @param devlist: list of tuples of the form  (disk,
3056
      new_logical_id, new_physical_id); disk is an
3057
      L{objects.Disk} object describing the current disk,
3058
      and new logical_id/physical_id is the name we
3059
      rename it to
3060
  @rtype: boolean
3061
  @return: True if all renames succeeded, False otherwise
3062

3063
  """
3064
  msgs = []
3065
  result = True
3066
  for disk, unique_id in devlist:
3067
    dev = _RecursiveFindBD(disk)
3068
    if dev is None:
3069
      msgs.append("Can't find device %s in rename" % str(disk))
3070
      result = False
3071
      continue
3072
    try:
3073
      old_rpath = dev.dev_path
3074
      dev.Rename(unique_id)
3075
      new_rpath = dev.dev_path
3076
      if old_rpath != new_rpath:
3077
        DevCacheManager.RemoveCache(old_rpath)
3078
        # FIXME: we should add the new cache information here, like:
3079
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
3080
        # but we don't have the owner here - maybe parse from existing
3081
        # cache? for now, we only lose lvm data when we rename, which
3082
        # is less critical than DRBD or MD
3083
    except errors.BlockDeviceError, err:
3084
      msgs.append("Can't rename device '%s' to '%s': %s" %
3085
                  (dev, unique_id, err))
3086
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
3087
      result = False
3088
  if not result:
3089
    _Fail("; ".join(msgs))
3090

    
3091

    
3092
def _TransformFileStorageDir(fs_dir):
3093
  """Checks whether given file_storage_dir is valid.
3094

3095
  Checks wheter the given fs_dir is within the cluster-wide default
3096
  file_storage_dir or the shared_file_storage_dir, which are stored in
3097
  SimpleStore. Only paths under those directories are allowed.
3098

3099
  @type fs_dir: str
3100
  @param fs_dir: the path to check
3101

3102
  @return: the normalized path if valid, None otherwise
3103

3104
  """
3105
  if not (constants.ENABLE_FILE_STORAGE or
3106
          constants.ENABLE_SHARED_FILE_STORAGE):
3107
    _Fail("File storage disabled at configure time")
3108

    
3109
  bdev.CheckFileStoragePath(fs_dir)
3110

    
3111
  return os.path.normpath(fs_dir)
3112

    
3113

    
3114
def CreateFileStorageDir(file_storage_dir):
3115
  """Create file storage directory.
3116

3117
  @type file_storage_dir: str
3118
  @param file_storage_dir: directory to create
3119

3120
  @rtype: tuple
3121
  @return: tuple with first element a boolean indicating wheter dir
3122
      creation was successful or not
3123

3124
  """
3125
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3126
  if os.path.exists(file_storage_dir):
3127
    if not os.path.isdir(file_storage_dir):
3128
      _Fail("Specified storage dir '%s' is not a directory",
3129
            file_storage_dir)
3130
  else:
3131
    try:
3132
      os.makedirs(file_storage_dir, 0750)
3133
    except OSError, err:
3134
      _Fail("Cannot create file storage directory '%s': %s",
3135
            file_storage_dir, err, exc=True)
3136

    
3137

    
3138
def RemoveFileStorageDir(file_storage_dir):
3139
  """Remove file storage directory.
3140

3141
  Remove it only if it's empty. If not log an error and return.
3142

3143
  @type file_storage_dir: str
3144
  @param file_storage_dir: the directory we should cleanup
3145
  @rtype: tuple (success,)
3146
  @return: tuple of one element, C{success}, denoting
3147
      whether the operation was successful
3148

3149
  """
3150
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3151
  if os.path.exists(file_storage_dir):
3152
    if not os.path.isdir(file_storage_dir):
3153
      _Fail("Specified Storage directory '%s' is not a directory",
3154
            file_storage_dir)
3155
    # deletes dir only if empty, otherwise we want to fail the rpc call
3156
    try:
3157
      os.rmdir(file_storage_dir)
3158
    except OSError, err:
3159
      _Fail("Cannot remove file storage directory '%s': %s",
3160
            file_storage_dir, err)
3161

    
3162

    
3163
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
3164
  """Rename the file storage directory.
3165

3166
  @type old_file_storage_dir: str
3167
  @param old_file_storage_dir: the current path
3168
  @type new_file_storage_dir: str
3169
  @param new_file_storage_dir: the name we should rename to
3170
  @rtype: tuple (success,)
3171
  @return: tuple of one element, C{success}, denoting
3172
      whether the operation was successful
3173

3174
  """
3175
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
3176
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
3177
  if not os.path.exists(new_file_storage_dir):
3178
    if os.path.isdir(old_file_storage_dir):
3179
      try:
3180
        os.rename(old_file_storage_dir, new_file_storage_dir)
3181
      except OSError, err:
3182
        _Fail("Cannot rename '%s' to '%s': %s",
3183
              old_file_storage_dir, new_file_storage_dir, err)
3184
    else:
3185
      _Fail("Specified storage dir '%s' is not a directory",
3186
            old_file_storage_dir)
3187
  else:
3188
    if os.path.exists(old_file_storage_dir):
3189
      _Fail("Cannot rename '%s' to '%s': both locations exist",
3190
            old_file_storage_dir, new_file_storage_dir)
3191

    
3192

    
3193
def _EnsureJobQueueFile(file_name):
3194
  """Checks whether the given filename is in the queue directory.
3195

3196
  @type file_name: str
3197
  @param file_name: the file name we should check
3198
  @rtype: None
3199
  @raises RPCFail: if the file is not valid
3200

3201
  """
3202
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
3203
    _Fail("Passed job queue file '%s' does not belong to"
3204
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
3205

    
3206

    
3207
def JobQueueUpdate(file_name, content):
3208
  """Updates a file in the queue directory.
3209

3210
  This is just a wrapper over L{utils.io.WriteFile}, with proper
3211
  checking.
3212

3213
  @type file_name: str
3214
  @param file_name: the job file name
3215
  @type content: str
3216
  @param content: the new job contents
3217
  @rtype: boolean
3218
  @return: the success of the operation
3219

3220
  """
3221
  file_name = vcluster.LocalizeVirtualPath(file_name)
3222

    
3223
  _EnsureJobQueueFile(file_name)
3224
  getents = runtime.GetEnts()
3225

    
3226
  # Write and replace the file atomically
3227
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3228
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3229

    
3230

    
3231
def JobQueueRename(old, new):
3232
  """Renames a job queue file.
3233

3234
  This is just a wrapper over os.rename with proper checking.
3235

3236
  @type old: str
3237
  @param old: the old (actual) file name
3238
  @type new: str
3239
  @param new: the desired file name
3240
  @rtype: tuple
3241
  @return: the success of the operation and payload
3242

3243
  """
3244
  old = vcluster.LocalizeVirtualPath(old)
3245
  new = vcluster.LocalizeVirtualPath(new)
3246

    
3247
  _EnsureJobQueueFile(old)
3248
  _EnsureJobQueueFile(new)
3249

    
3250
  getents = runtime.GetEnts()
3251

    
3252
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3253
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3254

    
3255

    
3256
def BlockdevClose(instance_name, disks):
3257
  """Closes the given block devices.
3258

3259
  This means they will be switched to secondary mode (in case of
3260
  DRBD).
3261

3262
  @param instance_name: if the argument is not empty, the symlinks
3263
      of this instance will be removed
3264
  @type disks: list of L{objects.Disk}
3265
  @param disks: the list of disks to be closed
3266
  @rtype: tuple (success, message)
3267
  @return: a tuple of success and message, where success
3268
      indicates the succes of the operation, and message
3269
      which will contain the error details in case we
3270
      failed
3271

3272
  """
3273
  bdevs = []
3274
  for cf in disks:
3275
    rd = _RecursiveFindBD(cf)
3276
    if rd is None:
3277
      _Fail("Can't find device %s", cf)
3278
    bdevs.append(rd)
3279

    
3280
  msg = []
3281
  for rd in bdevs:
3282
    try:
3283
      rd.Close()
3284
    except errors.BlockDeviceError, err:
3285
      msg.append(str(err))
3286
  if msg:
3287
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3288
  else:
3289
    if instance_name:
3290
      _RemoveBlockDevLinks(instance_name, disks)
3291

    
3292

    
3293
def ValidateHVParams(hvname, hvparams):
3294
  """Validates the given hypervisor parameters.
3295

3296
  @type hvname: string
3297
  @param hvname: the hypervisor name
3298
  @type hvparams: dict
3299
  @param hvparams: the hypervisor parameters to be validated
3300
  @rtype: None
3301

3302
  """
3303
  try:
3304
    hv_type = hypervisor.GetHypervisor(hvname)
3305
    hv_type.ValidateParameters(hvparams)
3306
  except errors.HypervisorError, err:
3307
    _Fail(str(err), log=False)
3308

    
3309

    
3310
def _CheckOSPList(os_obj, parameters):
3311
  """Check whether a list of parameters is supported by the OS.
3312

3313
  @type os_obj: L{objects.OS}
3314
  @param os_obj: OS object to check
3315
  @type parameters: list
3316
  @param parameters: the list of parameters to check
3317

3318
  """
3319
  supported = [v[0] for v in os_obj.supported_parameters]
3320
  delta = frozenset(parameters).difference(supported)
3321
  if delta:
3322
    _Fail("The following parameters are not supported"
3323
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3324

    
3325

    
3326
def ValidateOS(required, osname, checks, osparams):
3327
  """Validate the given OS' parameters.
3328

3329
  @type required: boolean
3330
  @param required: whether absence of the OS should translate into
3331
      failure or not
3332
  @type osname: string
3333
  @param osname: the OS to be validated
3334
  @type checks: list
3335
  @param checks: list of the checks to run (currently only 'parameters')
3336
  @type osparams: dict
3337
  @param osparams: dictionary with OS parameters
3338
  @rtype: boolean
3339
  @return: True if the validation passed, or False if the OS was not
3340
      found and L{required} was false
3341

3342
  """
3343
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3344
    _Fail("Unknown checks required for OS %s: %s", osname,
3345
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3346

    
3347
  name_only = objects.OS.GetName(osname)
3348
  status, tbv = _TryOSFromDisk(name_only, None)
3349

    
3350
  if not status:
3351
    if required:
3352
      _Fail(tbv)
3353
    else:
3354
      return False
3355

    
3356
  if max(tbv.api_versions) < constants.OS_API_V20:
3357
    return True
3358

    
3359
  if constants.OS_VALIDATE_PARAMETERS in checks:
3360
    _CheckOSPList(tbv, osparams.keys())
3361

    
3362
  validate_env = OSCoreEnv(osname, tbv, osparams)
3363
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3364
                        cwd=tbv.path, reset_env=True)
3365
  if result.failed:
3366
    logging.error("os validate command '%s' returned error: %s output: %s",
3367
                  result.cmd, result.fail_reason, result.output)
3368
    _Fail("OS validation script failed (%s), output: %s",
3369
          result.fail_reason, result.output, log=False)
3370

    
3371
  return True
3372

    
3373

    
3374
def DemoteFromMC():
3375
  """Demotes the current node from master candidate role.
3376

3377
  """
3378
  # try to ensure we're not the master by mistake
3379
  master, myself = ssconf.GetMasterAndMyself()
3380
  if master == myself:
3381
    _Fail("ssconf status shows I'm the master node, will not demote")
3382

    
3383
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3384
  if not result.failed:
3385
    _Fail("The master daemon is running, will not demote")
3386

    
3387
  try:
3388
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3389
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3390
  except EnvironmentError, err:
3391
    if err.errno != errno.ENOENT:
3392
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3393

    
3394
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3395

    
3396

    
3397
def _GetX509Filenames(cryptodir, name):
3398
  """Returns the full paths for the private key and certificate.
3399

3400
  """
3401
  return (utils.PathJoin(cryptodir, name),
3402
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3403
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3404

    
3405

    
3406
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3407
  """Creates a new X509 certificate for SSL/TLS.
3408

3409
  @type validity: int
3410
  @param validity: Validity in seconds
3411
  @rtype: tuple; (string, string)
3412
  @return: Certificate name and public part
3413

3414
  """
3415
  (key_pem, cert_pem) = \
3416
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3417
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3418

    
3419
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3420
                              prefix="x509-%s-" % utils.TimestampForFilename())
3421
  try:
3422
    name = os.path.basename(cert_dir)
3423
    assert len(name) > 5
3424

    
3425
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3426

    
3427
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3428
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3429

    
3430
    # Never return private key as it shouldn't leave the node
3431
    return (name, cert_pem)
3432
  except Exception:
3433
    shutil.rmtree(cert_dir, ignore_errors=True)
3434
    raise
3435

    
3436

    
3437
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3438
  """Removes a X509 certificate.
3439

3440
  @type name: string
3441
  @param name: Certificate name
3442

3443
  """
3444
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3445

    
3446
  utils.RemoveFile(key_file)
3447
  utils.RemoveFile(cert_file)
3448

    
3449
  try:
3450
    os.rmdir(cert_dir)
3451
  except EnvironmentError, err:
3452
    _Fail("Cannot remove certificate directory '%s': %s",
3453
          cert_dir, err)
3454

    
3455

    
3456
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3457
  """Returns the command for the requested input/output.
3458

3459
  @type instance: L{objects.Instance}
3460
  @param instance: The instance object
3461
  @param mode: Import/export mode
3462
  @param ieio: Input/output type
3463
  @param ieargs: Input/output arguments
3464

3465
  """
3466
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3467

    
3468
  env = None
3469
  prefix = None
3470
  suffix = None
3471
  exp_size = None
3472

    
3473
  if ieio == constants.IEIO_FILE:
3474
    (filename, ) = ieargs
3475

    
3476
    if not utils.IsNormAbsPath(filename):
3477
      _Fail("Path '%s' is not normalized or absolute", filename)
3478

    
3479
    real_filename = os.path.realpath(filename)
3480
    directory = os.path.dirname(real_filename)
3481

    
3482
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3483
      _Fail("File '%s' is not under exports directory '%s': %s",
3484
            filename, pathutils.EXPORT_DIR, real_filename)
3485

    
3486
    # Create directory
3487
    utils.Makedirs(directory, mode=0750)
3488

    
3489
    quoted_filename = utils.ShellQuote(filename)
3490

    
3491
    if mode == constants.IEM_IMPORT:
3492
      suffix = "> %s" % quoted_filename
3493
    elif mode == constants.IEM_EXPORT:
3494
      suffix = "< %s" % quoted_filename
3495

    
3496
      # Retrieve file size
3497
      try:
3498
        st = os.stat(filename)
3499
      except EnvironmentError, err:
3500
        logging.error("Can't stat(2) %s: %s", filename, err)
3501
      else:
3502
        exp_size = utils.BytesToMebibyte(st.st_size)
3503

    
3504
  elif ieio == constants.IEIO_RAW_DISK:
3505
    (disk, ) = ieargs
3506

    
3507
    real_disk = _OpenRealBD(disk)
3508

    
3509
    if mode == constants.IEM_IMPORT:
3510
      # we set here a smaller block size as, due to transport buffering, more
3511
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3512
      # is not already there or we pass a wrong path; we use notrunc to no
3513
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3514
      # much memory; this means that at best, we flush every 64k, which will
3515
      # not be very fast
3516
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3517
                                    " bs=%s oflag=dsync"),
3518
                                    real_disk.dev_path,
3519
                                    str(64 * 1024))
3520

    
3521
    elif mode == constants.IEM_EXPORT:
3522
      # the block size on the read dd is 1MiB to match our units
3523
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3524
                                   real_disk.dev_path,
3525
                                   str(1024 * 1024), # 1 MB
3526
                                   str(disk.size))
3527
      exp_size = disk.size
3528

    
3529
  elif ieio == constants.IEIO_SCRIPT:
3530
    (disk, disk_index, ) = ieargs
3531

    
3532
    assert isinstance(disk_index, (int, long))
3533

    
3534
    real_disk = _OpenRealBD(disk)
3535

    
3536
    inst_os = OSFromDisk(instance.os)
3537
    env = OSEnvironment(instance, inst_os)
3538

    
3539
    if mode == constants.IEM_IMPORT:
3540
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3541
      env["IMPORT_INDEX"] = str(disk_index)
3542
      script = inst_os.import_script
3543

    
3544
    elif mode == constants.IEM_EXPORT:
3545
      env["EXPORT_DEVICE"] = real_disk.dev_path
3546
      env["EXPORT_INDEX"] = str(disk_index)
3547
      script = inst_os.export_script
3548

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

    
3552
    if mode == constants.IEM_IMPORT:
3553
      suffix = "| %s" % script_cmd
3554

    
3555
    elif mode == constants.IEM_EXPORT:
3556
      prefix = "%s |" % script_cmd
3557

    
3558
    # Let script predict size
3559
    exp_size = constants.IE_CUSTOM_SIZE
3560

    
3561
  else:
3562
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3563

    
3564
  return (env, prefix, suffix, exp_size)
3565

    
3566

    
3567
def _CreateImportExportStatusDir(prefix):
3568
  """Creates status directory for import/export.
3569

3570
  """
3571
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3572
                          prefix=("%s-%s-" %
3573
                                  (prefix, utils.TimestampForFilename())))
3574

    
3575

    
3576
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3577
                            ieio, ieioargs):
3578
  """Starts an import or export daemon.
3579

3580
  @param mode: Import/output mode
3581
  @type opts: L{objects.ImportExportOptions}
3582
  @param opts: Daemon options
3583
  @type host: string
3584
  @param host: Remote host for export (None for import)
3585
  @type port: int
3586
  @param port: Remote port for export (None for import)
3587
  @type instance: L{objects.Instance}
3588
  @param instance: Instance object
3589
  @type component: string
3590
  @param component: which part of the instance is transferred now,
3591
      e.g. 'disk/0'
3592
  @param ieio: Input/output type
3593
  @param ieioargs: Input/output arguments
3594

3595
  """
3596
  if mode == constants.IEM_IMPORT:
3597
    prefix = "import"
3598

    
3599
    if not (host is None and port is None):
3600
      _Fail("Can not specify host or port on import")
3601

    
3602
  elif mode == constants.IEM_EXPORT:
3603
    prefix = "export"
3604

    
3605
    if host is None or port is None:
3606
      _Fail("Host and port must be specified for an export")
3607

    
3608
  else:
3609
    _Fail("Invalid mode %r", mode)
3610

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

    
3614
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3615
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3616

    
3617
  if opts.key_name is None:
3618
    # Use server.pem
3619
    key_path = pathutils.NODED_CERT_FILE
3620
    cert_path = pathutils.NODED_CERT_FILE
3621
    assert opts.ca_pem is None
3622
  else:
3623
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3624
                                                 opts.key_name)
3625
    assert opts.ca_pem is not None
3626

    
3627
  for i in [key_path, cert_path]:
3628
    if not os.path.exists(i):
3629
      _Fail("File '%s' does not exist" % i)
3630

    
3631
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3632
  try:
3633
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3634
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3635
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3636

    
3637
    if opts.ca_pem is None:
3638
      # Use server.pem
3639
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3640
    else:
3641
      ca = opts.ca_pem
3642

    
3643
    # Write CA file
3644
    utils.WriteFile(ca_file, data=ca, mode=0400)
3645

    
3646
    cmd = [
3647
      pathutils.IMPORT_EXPORT_DAEMON,
3648
      status_file, mode,
3649
      "--key=%s" % key_path,
3650
      "--cert=%s" % cert_path,
3651
      "--ca=%s" % ca_file,
3652
      ]
3653

    
3654
    if host:
3655
      cmd.append("--host=%s" % host)
3656

    
3657
    if port:
3658
      cmd.append("--port=%s" % port)
3659

    
3660
    if opts.ipv6:
3661
      cmd.append("--ipv6")
3662
    else:
3663
      cmd.append("--ipv4")
3664

    
3665
    if opts.compress:
3666
      cmd.append("--compress=%s" % opts.compress)
3667

    
3668
    if opts.magic:
3669
      cmd.append("--magic=%s" % opts.magic)
3670

    
3671
    if exp_size is not None:
3672
      cmd.append("--expected-size=%s" % exp_size)
3673

    
3674
    if cmd_prefix:
3675
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3676

    
3677
    if cmd_suffix:
3678
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3679

    
3680
    if mode == constants.IEM_EXPORT:
3681
      # Retry connection a few times when connecting to remote peer
3682
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3683
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3684
    elif opts.connect_timeout is not None:
3685
      assert mode == constants.IEM_IMPORT
3686
      # Overall timeout for establishing connection while listening
3687
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3688

    
3689
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3690

    
3691
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3692
    # support for receiving a file descriptor for output
3693
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3694
                      output=logfile)
3695

    
3696
    # The import/export name is simply the status directory name
3697
    return os.path.basename(status_dir)
3698

    
3699
  except Exception:
3700
    shutil.rmtree(status_dir, ignore_errors=True)
3701
    raise
3702

    
3703

    
3704
def GetImportExportStatus(names):
3705
  """Returns import/export daemon status.
3706

3707
  @type names: sequence
3708
  @param names: List of names
3709
  @rtype: List of dicts
3710
  @return: Returns a list of the state of each named import/export or None if a
3711
           status couldn't be read
3712

3713
  """
3714
  result = []
3715

    
3716
  for name in names:
3717
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3718
                                 _IES_STATUS_FILE)
3719

    
3720
    try:
3721
      data = utils.ReadFile(status_file)
3722
    except EnvironmentError, err:
3723
      if err.errno != errno.ENOENT:
3724
        raise
3725
      data = None
3726

    
3727
    if not data:
3728
      result.append(None)
3729
      continue
3730

    
3731
    result.append(serializer.LoadJson(data))
3732

    
3733
  return result
3734

    
3735

    
3736
def AbortImportExport(name):
3737
  """Sends SIGTERM to a running import/export daemon.
3738

3739
  """
3740
  logging.info("Abort import/export %s", name)
3741

    
3742
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3743
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3744

    
3745
  if pid:
3746
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3747
                 name, pid)
3748
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3749

    
3750

    
3751
def CleanupImportExport(name):
3752
  """Cleanup after an import or export.
3753

3754
  If the import/export daemon is still running it's killed. Afterwards the
3755
  whole status directory is removed.
3756

3757
  """
3758
  logging.info("Finalizing import/export %s", name)
3759

    
3760
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3761

    
3762
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3763

    
3764
  if pid:
3765
    logging.info("Import/export %s is still running with PID %s",
3766
                 name, pid)
3767
    utils.KillProcess(pid, waitpid=False)
3768

    
3769
  shutil.rmtree(status_dir, ignore_errors=True)
3770

    
3771

    
3772
def _FindDisks(nodes_ip, disks):
3773
  """Sets the physical ID on disks and returns the block devices.
3774

3775
  """
3776
  # set the correct physical ID
3777
  my_name = netutils.Hostname.GetSysName()
3778
  for cf in disks:
3779
    cf.SetPhysicalID(my_name, nodes_ip)
3780

    
3781
  bdevs = []
3782

    
3783
  for cf in disks:
3784
    rd = _RecursiveFindBD(cf)
3785
    if rd is None:
3786
      _Fail("Can't find device %s", cf)
3787
    bdevs.append(rd)
3788
  return bdevs
3789

    
3790

    
3791
def DrbdDisconnectNet(nodes_ip, disks):
3792
  """Disconnects the network on a list of drbd devices.
3793

3794
  """
3795
  bdevs = _FindDisks(nodes_ip, disks)
3796

    
3797
  # disconnect disks
3798
  for rd in bdevs:
3799
    try:
3800
      rd.DisconnectNet()
3801
    except errors.BlockDeviceError, err:
3802
      _Fail("Can't change network configuration to standalone mode: %s",
3803
            err, exc=True)
3804

    
3805

    
3806
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3807
  """Attaches the network on a list of drbd devices.
3808

3809
  """
3810
  bdevs = _FindDisks(nodes_ip, disks)
3811

    
3812
  if multimaster:
3813
    for idx, rd in enumerate(bdevs):
3814
      try:
3815
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3816
      except EnvironmentError, err:
3817
        _Fail("Can't create symlink: %s", err)
3818
  # reconnect disks, switch to new master configuration and if
3819
  # needed primary mode
3820
  for rd in bdevs:
3821
    try:
3822
      rd.AttachNet(multimaster)
3823
    except errors.BlockDeviceError, err:
3824
      _Fail("Can't change network configuration: %s", err)
3825

    
3826
  # wait until the disks are connected; we need to retry the re-attach
3827
  # if the device becomes standalone, as this might happen if the one
3828
  # node disconnects and reconnects in a different mode before the
3829
  # other node reconnects; in this case, one or both of the nodes will
3830
  # decide it has wrong configuration and switch to standalone
3831

    
3832
  def _Attach():
3833
    all_connected = True
3834

    
3835
    for rd in bdevs:
3836
      stats = rd.GetProcStatus()
3837

    
3838
      all_connected = (all_connected and
3839
                       (stats.is_connected or stats.is_in_resync))
3840

    
3841
      if stats.is_standalone:
3842
        # peer had different config info and this node became
3843
        # standalone, even though this should not happen with the
3844
        # new staged way of changing disk configs
3845
        try:
3846
          rd.AttachNet(multimaster)
3847
        except errors.BlockDeviceError, err:
3848
          _Fail("Can't change network configuration: %s", err)
3849

    
3850
    if not all_connected:
3851
      raise utils.RetryAgain()
3852

    
3853
  try:
3854
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3855
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3856
  except utils.RetryTimeout:
3857
    _Fail("Timeout in disk reconnecting")
3858

    
3859
  if multimaster:
3860
    # change to primary mode
3861
    for rd in bdevs:
3862
      try:
3863
        rd.Open()
3864
      except errors.BlockDeviceError, err:
3865
        _Fail("Can't change to primary mode: %s", err)
3866

    
3867

    
3868
def DrbdWaitSync(nodes_ip, disks):
3869
  """Wait until DRBDs have synchronized.
3870

3871
  """
3872
  def _helper(rd):
3873
    stats = rd.GetProcStatus()
3874
    if not (stats.is_connected or stats.is_in_resync):
3875
      raise utils.RetryAgain()
3876
    return stats
3877

    
3878
  bdevs = _FindDisks(nodes_ip, disks)
3879

    
3880
  min_resync = 100
3881
  alldone = True
3882
  for rd in bdevs:
3883
    try:
3884
      # poll each second for 15 seconds
3885
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3886
    except utils.RetryTimeout:
3887
      stats = rd.GetProcStatus()
3888
      # last check
3889
      if not (stats.is_connected or stats.is_in_resync):
3890
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3891
    alldone = alldone and (not stats.is_in_resync)
3892
    if stats.sync_percent is not None:
3893
      min_resync = min(min_resync, stats.sync_percent)
3894

    
3895
  return (alldone, min_resync)
3896

    
3897

    
3898
def GetDrbdUsermodeHelper():
3899
  """Returns DRBD usermode helper currently configured.
3900

3901
  """
3902
  try:
3903
    return drbd.DRBD8.GetUsermodeHelper()
3904
  except errors.BlockDeviceError, err:
3905
    _Fail(str(err))
3906

    
3907

    
3908
def PowercycleNode(hypervisor_type):
3909
  """Hard-powercycle the node.
3910

3911
  Because we need to return first, and schedule the powercycle in the
3912
  background, we won't be able to report failures nicely.
3913

3914
  """
3915
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3916
  try:
3917
    pid = os.fork()
3918
  except OSError:
3919
    # if we can't fork, we'll pretend that we're in the child process
3920
    pid = 0
3921
  if pid > 0:
3922
    return "Reboot scheduled in 5 seconds"
3923
  # ensure the child is running on ram
3924
  try:
3925
    utils.Mlockall()
3926
  except Exception: # pylint: disable=W0703
3927
    pass
3928
  time.sleep(5)
3929
  hyper.PowercycleNode()
3930

    
3931

    
3932
def _VerifyRestrictedCmdName(cmd):
3933
  """Verifies a restricted command name.
3934

3935
  @type cmd: string
3936
  @param cmd: Command name
3937
  @rtype: tuple; (boolean, string or None)
3938
  @return: The tuple's first element is the status; if C{False}, the second
3939
    element is an error message string, otherwise it's C{None}
3940

3941
  """
3942
  if not cmd.strip():
3943
    return (False, "Missing command name")
3944

    
3945
  if os.path.basename(cmd) != cmd:
3946
    return (False, "Invalid command name")
3947

    
3948
  if not constants.EXT_PLUGIN_MASK.match(cmd):
3949
    return (False, "Command name contains forbidden characters")
3950

    
3951
  return (True, None)
3952

    
3953

    
3954
def _CommonRestrictedCmdCheck(path, owner):
3955
  """Common checks for restricted command file system directories and files.
3956

3957
  @type path: string
3958
  @param path: Path to check
3959
  @param owner: C{None} or tuple containing UID and GID
3960
  @rtype: tuple; (boolean, string or C{os.stat} result)
3961
  @return: The tuple's first element is the status; if C{False}, the second
3962
    element is an error message string, otherwise it's the result of C{os.stat}
3963

3964
  """
3965
  if owner is None:
3966
    # Default to root as owner
3967
    owner = (0, 0)
3968

    
3969
  try:
3970
    st = os.stat(path)
3971
  except EnvironmentError, err:
3972
    return (False, "Can't stat(2) '%s': %s" % (path, err))
3973

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

    
3977
  if (st.st_uid, st.st_gid) != owner:
3978
    (owner_uid, owner_gid) = owner
3979
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
3980

    
3981
  return (True, st)
3982

    
3983

    
3984
def _VerifyRestrictedCmdDirectory(path, _owner=None):
3985
  """Verifies restricted command directory.
3986

3987
  @type path: string
3988
  @param path: Path to check
3989
  @rtype: tuple; (boolean, string or None)
3990
  @return: The tuple's first element is the status; if C{False}, the second
3991
    element is an error message string, otherwise it's C{None}
3992

3993
  """
3994
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
3995

    
3996
  if not status:
3997
    return (False, value)
3998

    
3999
  if not stat.S_ISDIR(value.st_mode):
4000
    return (False, "Path '%s' is not a directory" % path)
4001

    
4002
  return (True, None)
4003

    
4004

    
4005
def _VerifyRestrictedCmd(path, cmd, _owner=None):
4006
  """Verifies a whole restricted command and returns its executable filename.
4007

4008
  @type path: string
4009
  @param path: Directory containing restricted commands
4010
  @type cmd: string
4011
  @param cmd: Command name
4012
  @rtype: tuple; (boolean, string)
4013
  @return: The tuple's first element is the status; if C{False}, the second
4014
    element is an error message string, otherwise the second element is the
4015
    absolute path to the executable
4016

4017
  """
4018
  executable = utils.PathJoin(path, cmd)
4019

    
4020
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
4021

    
4022
  if not status:
4023
    return (False, msg)
4024

    
4025
  if not utils.IsExecutable(executable):
4026
    return (False, "access(2) thinks '%s' can't be executed" % executable)
4027

    
4028
  return (True, executable)
4029

    
4030

    
4031
def _PrepareRestrictedCmd(path, cmd,
4032
                          _verify_dir=_VerifyRestrictedCmdDirectory,
4033
                          _verify_name=_VerifyRestrictedCmdName,
4034
                          _verify_cmd=_VerifyRestrictedCmd):
4035
  """Performs a number of tests on a restricted command.
4036

4037
  @type path: string
4038
  @param path: Directory containing restricted commands
4039
  @type cmd: string
4040
  @param cmd: Command name
4041
  @return: Same as L{_VerifyRestrictedCmd}
4042

4043
  """
4044
  # Verify the directory first
4045
  (status, msg) = _verify_dir(path)
4046
  if status:
4047
    # Check command if everything was alright
4048
    (status, msg) = _verify_name(cmd)
4049

    
4050
  if not status:
4051
    return (False, msg)
4052

    
4053
  # Check actual executable
4054
  return _verify_cmd(path, cmd)
4055

    
4056

    
4057
def RunRestrictedCmd(cmd,
4058
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
4059
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
4060
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
4061
                     _sleep_fn=time.sleep,
4062
                     _prepare_fn=_PrepareRestrictedCmd,
4063
                     _runcmd_fn=utils.RunCmd,
4064
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
4065
  """Executes a restricted command after performing strict tests.
4066

4067
  @type cmd: string
4068
  @param cmd: Command name
4069
  @rtype: string
4070
  @return: Command output
4071
  @raise RPCFail: In case of an error
4072

4073
  """
4074
  logging.info("Preparing to run restricted command '%s'", cmd)
4075

    
4076
  if not _enabled:
4077
    _Fail("Restricted commands disabled at configure time")
4078

    
4079
  lock = None
4080
  try:
4081
    cmdresult = None
4082
    try:
4083
      lock = utils.FileLock.Open(_lock_file)
4084
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
4085

    
4086
      (status, value) = _prepare_fn(_path, cmd)
4087

    
4088
      if status:
4089
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
4090
                               postfork_fn=lambda _: lock.Unlock())
4091
      else:
4092
        logging.error(value)
4093
    except Exception: # pylint: disable=W0703
4094
      # Keep original error in log
4095
      logging.exception("Caught exception")
4096

    
4097
    if cmdresult is None:
4098
      logging.info("Sleeping for %0.1f seconds before returning",
4099
                   _RCMD_INVALID_DELAY)
4100
      _sleep_fn(_RCMD_INVALID_DELAY)
4101

    
4102
      # Do not include original error message in returned error
4103
      _Fail("Executing command '%s' failed" % cmd)
4104
    elif cmdresult.failed or cmdresult.fail_reason:
4105
      _Fail("Restricted command '%s' failed: %s; output: %s",
4106
            cmd, cmdresult.fail_reason, cmdresult.output)
4107
    else:
4108
      return cmdresult.output
4109
  finally:
4110
    if lock is not None:
4111
      # Release lock at last
4112
      lock.Close()
4113
      lock = None
4114

    
4115

    
4116
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
4117
  """Creates or removes the watcher pause file.
4118

4119
  @type until: None or number
4120
  @param until: Unix timestamp saying until when the watcher shouldn't run
4121

4122
  """
4123
  if until is None:
4124
    logging.info("Received request to no longer pause watcher")
4125
    utils.RemoveFile(_filename)
4126
  else:
4127
    logging.info("Received request to pause watcher until %s", until)
4128

    
4129
    if not ht.TNumber(until):
4130
      _Fail("Duration must be numeric")
4131

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

    
4134