Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ bc0a2284

History | View | Annotate | Download (133.7 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, hvparams=None):
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
  @type hvparams: dict of strings
1284
  @param hvparams: the instance's hvparams
1285

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

1293
  """
1294
  output = {}
1295

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

    
1304
  return output
1305

    
1306

    
1307
def GetInstanceMigratable(instance):
1308
  """Computes whether an instance can be migrated.
1309

1310
  @type instance: L{objects.Instance}
1311
  @param instance: object representing the instance to be checked.
1312

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

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

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

    
1330

    
1331
def GetAllInstancesInfo(hypervisor_list, all_hvparams):
1332
  """Gather data about all instances.
1333

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

1338
  @type hypervisor_list: list
1339
  @param hypervisor_list: list of hypervisors to query for instance data
1340
  @type all_hvparams: dict of dict of strings
1341
  @param all_hvparams: mapping of hypervisor names to hvparams
1342

1343
  @rtype: dict
1344
  @return: dictionary of instance: data, with data having the following keys:
1345
      - memory: memory size of instance (int)
1346
      - state: xen state of instance (string)
1347
      - time: cpu time of instance (float)
1348
      - vcpus: the number of vcpus
1349

1350
  """
1351
  output = {}
1352

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

    
1374
  return output
1375

    
1376

    
1377
def _InstanceLogName(kind, os_name, instance, component):
1378
  """Compute the OS log filename for a given instance and operation.
1379

1380
  The instance name and os name are passed in as strings since not all
1381
  operations have these as part of an instance object.
1382

1383
  @type kind: string
1384
  @param kind: the operation type (e.g. add, import, etc.)
1385
  @type os_name: string
1386
  @param os_name: the os name
1387
  @type instance: string
1388
  @param instance: the name of the instance being imported/added/etc.
1389
  @type component: string or None
1390
  @param component: the name of the component of the instance being
1391
      transferred
1392

1393
  """
1394
  # TODO: Use tempfile.mkstemp to create unique filename
1395
  if component:
1396
    assert "/" not in component
1397
    c_msg = "-%s" % component
1398
  else:
1399
    c_msg = ""
1400
  base = ("%s-%s-%s%s-%s.log" %
1401
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1402
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1403

    
1404

    
1405
def InstanceOsAdd(instance, reinstall, debug):
1406
  """Add an OS to an instance.
1407

1408
  @type instance: L{objects.Instance}
1409
  @param instance: Instance whose OS is to be installed
1410
  @type reinstall: boolean
1411
  @param reinstall: whether this is an instance reinstall
1412
  @type debug: integer
1413
  @param debug: debug level, passed to the OS scripts
1414
  @rtype: None
1415

1416
  """
1417
  inst_os = OSFromDisk(instance.os)
1418

    
1419
  create_env = OSEnvironment(instance, inst_os, debug)
1420
  if reinstall:
1421
    create_env["INSTANCE_REINSTALL"] = "1"
1422

    
1423
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1424

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

    
1436

    
1437
def RunRenameInstance(instance, old_name, debug):
1438
  """Run the OS rename script for an instance.
1439

1440
  @type instance: L{objects.Instance}
1441
  @param instance: Instance whose OS is to be installed
1442
  @type old_name: string
1443
  @param old_name: previous instance name
1444
  @type debug: integer
1445
  @param debug: debug level, passed to the OS scripts
1446
  @rtype: boolean
1447
  @return: the success of the operation
1448

1449
  """
1450
  inst_os = OSFromDisk(instance.os)
1451

    
1452
  rename_env = OSEnvironment(instance, inst_os, debug)
1453
  rename_env["OLD_INSTANCE_NAME"] = old_name
1454

    
1455
  logfile = _InstanceLogName("rename", instance.os,
1456
                             "%s-%s" % (old_name, instance.name), None)
1457

    
1458
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1459
                        cwd=inst_os.path, output=logfile, reset_env=True)
1460

    
1461
  if result.failed:
1462
    logging.error("os create command '%s' returned error: %s output: %s",
1463
                  result.cmd, result.fail_reason, result.output)
1464
    lines = [utils.SafeEncode(val)
1465
             for val in utils.TailFile(logfile, lines=20)]
1466
    _Fail("OS rename script failed (%s), last lines in the"
1467
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1468

    
1469

    
1470
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1471
  """Returns symlink path for block device.
1472

1473
  """
1474
  if _dir is None:
1475
    _dir = pathutils.DISK_LINKS_DIR
1476

    
1477
  return utils.PathJoin(_dir,
1478
                        ("%s%s%s" %
1479
                         (instance_name, constants.DISK_SEPARATOR, idx)))
1480

    
1481

    
1482
def _SymlinkBlockDev(instance_name, device_path, idx):
1483
  """Set up symlinks to a instance's block device.
1484

1485
  This is an auxiliary function run when an instance is start (on the primary
1486
  node) or when an instance is migrated (on the target node).
1487

1488

1489
  @param instance_name: the name of the target instance
1490
  @param device_path: path of the physical block device, on the node
1491
  @param idx: the disk index
1492
  @return: absolute path to the disk's symlink
1493

1494
  """
1495
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1496
  try:
1497
    os.symlink(device_path, link_name)
1498
  except OSError, err:
1499
    if err.errno == errno.EEXIST:
1500
      if (not os.path.islink(link_name) or
1501
          os.readlink(link_name) != device_path):
1502
        os.remove(link_name)
1503
        os.symlink(device_path, link_name)
1504
    else:
1505
      raise
1506

    
1507
  return link_name
1508

    
1509

    
1510
def _RemoveBlockDevLinks(instance_name, disks):
1511
  """Remove the block device symlinks belonging to the given instance.
1512

1513
  """
1514
  for idx, _ in enumerate(disks):
1515
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1516
    if os.path.islink(link_name):
1517
      try:
1518
        os.remove(link_name)
1519
      except OSError:
1520
        logging.exception("Can't remove symlink '%s'", link_name)
1521

    
1522

    
1523
def _GatherAndLinkBlockDevs(instance):
1524
  """Set up an instance's block device(s).
1525

1526
  This is run on the primary node at instance startup. The block
1527
  devices must be already assembled.
1528

1529
  @type instance: L{objects.Instance}
1530
  @param instance: the instance whose disks we shoul assemble
1531
  @rtype: list
1532
  @return: list of (disk_object, device_path)
1533

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

    
1548
    block_devices.append((disk, link_name))
1549

    
1550
  return block_devices
1551

    
1552

    
1553
def StartInstance(instance, startup_paused, reason, store_reason=True):
1554
  """Start an instance.
1555

1556
  @type instance: L{objects.Instance}
1557
  @param instance: the instance object
1558
  @type startup_paused: bool
1559
  @param instance: pause instance at startup?
1560
  @type reason: list of reasons
1561
  @param reason: the reason trail for this startup
1562
  @type store_reason: boolean
1563
  @param store_reason: whether to store the shutdown reason trail on file
1564
  @rtype: None
1565

1566
  """
1567
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1568
                                                   instance.hvparams)
1569

    
1570
  if instance.name in running_instances:
1571
    logging.info("Instance %s already running, not starting", instance.name)
1572
    return
1573

    
1574
  try:
1575
    block_devices = _GatherAndLinkBlockDevs(instance)
1576
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1577
    hyper.StartInstance(instance, block_devices, startup_paused)
1578
    if store_reason:
1579
      _StoreInstReasonTrail(instance.name, reason)
1580
  except errors.BlockDeviceError, err:
1581
    _Fail("Block device error: %s", err, exc=True)
1582
  except errors.HypervisorError, err:
1583
    _RemoveBlockDevLinks(instance.name, instance.disks)
1584
    _Fail("Hypervisor error: %s", err, exc=True)
1585

    
1586

    
1587
def InstanceShutdown(instance, timeout, reason, store_reason=True):
1588
  """Shut an instance down.
1589

1590
  @note: this functions uses polling with a hardcoded timeout.
1591

1592
  @type instance: L{objects.Instance}
1593
  @param instance: the instance object
1594
  @type timeout: integer
1595
  @param timeout: maximum timeout for soft shutdown
1596
  @type reason: list of reasons
1597
  @param reason: the reason trail for this shutdown
1598
  @type store_reason: boolean
1599
  @param store_reason: whether to store the shutdown reason trail on file
1600
  @rtype: None
1601

1602
  """
1603
  hv_name = instance.hypervisor
1604
  hyper = hypervisor.GetHypervisor(hv_name)
1605
  iname = instance.name
1606

    
1607
  if instance.name not in hyper.ListInstances(instance.hvparams):
1608
    logging.info("Instance %s not running, doing nothing", iname)
1609
    return
1610

    
1611
  class _TryShutdown:
1612
    def __init__(self):
1613
      self.tried_once = False
1614

    
1615
    def __call__(self):
1616
      if iname not in hyper.ListInstances(instance.hvparams):
1617
        return
1618

    
1619
      try:
1620
        hyper.StopInstance(instance, retry=self.tried_once)
1621
        if store_reason:
1622
          _StoreInstReasonTrail(instance.name, reason)
1623
      except errors.HypervisorError, err:
1624
        if iname not in hyper.ListInstances(instance.hvparams):
1625
          # if the instance is no longer existing, consider this a
1626
          # success and go to cleanup
1627
          return
1628

    
1629
        _Fail("Failed to stop instance %s: %s", iname, err)
1630

    
1631
      self.tried_once = True
1632

    
1633
      raise utils.RetryAgain()
1634

    
1635
  try:
1636
    utils.Retry(_TryShutdown(), 5, timeout)
1637
  except utils.RetryTimeout:
1638
    # the shutdown did not succeed
1639
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1640

    
1641
    try:
1642
      hyper.StopInstance(instance, force=True)
1643
    except errors.HypervisorError, err:
1644
      if iname in hyper.ListInstances(instance.hvparams):
1645
        # only raise an error if the instance still exists, otherwise
1646
        # the error could simply be "instance ... unknown"!
1647
        _Fail("Failed to force stop instance %s: %s", iname, err)
1648

    
1649
    time.sleep(1)
1650

    
1651
    if iname in hyper.ListInstances(instance.hvparams):
1652
      _Fail("Could not shutdown instance %s even by destroy", iname)
1653

    
1654
  try:
1655
    hyper.CleanupInstance(instance.name)
1656
  except errors.HypervisorError, err:
1657
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1658

    
1659
  _RemoveBlockDevLinks(iname, instance.disks)
1660

    
1661

    
1662
def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1663
  """Reboot an instance.
1664

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

1684
  """
1685
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1686
                                                   instance.hvparams)
1687

    
1688
  if instance.name not in running_instances:
1689
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1690

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

    
1708

    
1709
def InstanceBalloonMemory(instance, memory):
1710
  """Resize an instance's memory.
1711

1712
  @type instance: L{objects.Instance}
1713
  @param instance: the instance object
1714
  @type memory: int
1715
  @param memory: new memory amount in MB
1716
  @rtype: None
1717

1718
  """
1719
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1720
  running = hyper.ListInstances(instance.hvparams)
1721
  if instance.name not in running:
1722
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1723
    return
1724
  try:
1725
    hyper.BalloonInstanceMemory(instance, memory)
1726
  except errors.HypervisorError, err:
1727
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1728

    
1729

    
1730
def MigrationInfo(instance):
1731
  """Gather information about an instance to be migrated.
1732

1733
  @type instance: L{objects.Instance}
1734
  @param instance: the instance definition
1735

1736
  """
1737
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1738
  try:
1739
    info = hyper.MigrationInfo(instance)
1740
  except errors.HypervisorError, err:
1741
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1742
  return info
1743

    
1744

    
1745
def AcceptInstance(instance, info, target):
1746
  """Prepare the node to accept an instance.
1747

1748
  @type instance: L{objects.Instance}
1749
  @param instance: the instance definition
1750
  @type info: string/data (opaque)
1751
  @param info: migration information, from the source node
1752
  @type target: string
1753
  @param target: target host (usually ip), on this node
1754

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

    
1765
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1766
  try:
1767
    hyper.AcceptInstance(instance, info, target)
1768
  except errors.HypervisorError, err:
1769
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1770
      _RemoveBlockDevLinks(instance.name, instance.disks)
1771
    _Fail("Failed to accept instance: %s", err, exc=True)
1772

    
1773

    
1774
def FinalizeMigrationDst(instance, info, success):
1775
  """Finalize any preparation to accept an instance.
1776

1777
  @type instance: L{objects.Instance}
1778
  @param instance: the instance definition
1779
  @type info: string/data (opaque)
1780
  @param info: migration information, from the source node
1781
  @type success: boolean
1782
  @param success: whether the migration was a success or a failure
1783

1784
  """
1785
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1786
  try:
1787
    hyper.FinalizeMigrationDst(instance, info, success)
1788
  except errors.HypervisorError, err:
1789
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1790

    
1791

    
1792
def MigrateInstance(cluster_name, instance, target, live):
1793
  """Migrates an instance to another node.
1794

1795
  @type cluster_name: string
1796
  @param cluster_name: name of the cluster
1797
  @type instance: L{objects.Instance}
1798
  @param instance: the instance definition
1799
  @type target: string
1800
  @param target: the target node name
1801
  @type live: boolean
1802
  @param live: whether the migration should be done live or not (the
1803
      interpretation of this parameter is left to the hypervisor)
1804
  @raise RPCFail: if migration fails for some reason
1805

1806
  """
1807
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1808

    
1809
  try:
1810
    hyper.MigrateInstance(cluster_name, instance, target, live)
1811
  except errors.HypervisorError, err:
1812
    _Fail("Failed to migrate instance: %s", err, exc=True)
1813

    
1814

    
1815
def FinalizeMigrationSource(instance, success, live):
1816
  """Finalize the instance migration on the source node.
1817

1818
  @type instance: L{objects.Instance}
1819
  @param instance: the instance definition of the migrated instance
1820
  @type success: bool
1821
  @param success: whether the migration succeeded or not
1822
  @type live: bool
1823
  @param live: whether the user requested a live migration or not
1824
  @raise RPCFail: If the execution fails for some reason
1825

1826
  """
1827
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1828

    
1829
  try:
1830
    hyper.FinalizeMigrationSource(instance, success, live)
1831
  except Exception, err:  # pylint: disable=W0703
1832
    _Fail("Failed to finalize the migration on the source node: %s", err,
1833
          exc=True)
1834

    
1835

    
1836
def GetMigrationStatus(instance):
1837
  """Get the migration status
1838

1839
  @type instance: L{objects.Instance}
1840
  @param instance: the instance that is being migrated
1841
  @rtype: L{objects.MigrationStatus}
1842
  @return: the status of the current migration (one of
1843
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1844
           progress info that can be retrieved from the hypervisor
1845
  @raise RPCFail: If the migration status cannot be retrieved
1846

1847
  """
1848
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1849
  try:
1850
    return hyper.GetMigrationStatus(instance)
1851
  except Exception, err:  # pylint: disable=W0703
1852
    _Fail("Failed to get migration status: %s", err, exc=True)
1853

    
1854

    
1855
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
1856
  """Creates a block device for an instance.
1857

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

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

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

    
1897
  try:
1898
    device = bdev.Create(disk, clist, excl_stor)
1899
  except errors.BlockDeviceError, err:
1900
    _Fail("Can't create block device: %s", err)
1901

    
1902
  if on_primary or disk.AssembleOnSecondary():
1903
    try:
1904
      device.Assemble()
1905
    except errors.BlockDeviceError, err:
1906
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1907
    if on_primary or disk.OpenOnSecondary():
1908
      try:
1909
        device.Open(force=True)
1910
      except errors.BlockDeviceError, err:
1911
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1912
    DevCacheManager.UpdateCache(device.dev_path, owner,
1913
                                on_primary, disk.iv_name)
1914

    
1915
  device.SetInfo(info)
1916

    
1917
  return device.unique_id
1918

    
1919

    
1920
def _WipeDevice(path, offset, size):
1921
  """This function actually wipes the device.
1922

1923
  @param path: The path to the device to wipe
1924
  @param offset: The offset in MiB in the file
1925
  @param size: The size in MiB to write
1926

1927
  """
1928
  # Internal sizes are always in Mebibytes; if the following "dd" command
1929
  # should use a different block size the offset and size given to this
1930
  # function must be adjusted accordingly before being passed to "dd".
1931
  block_size = 1024 * 1024
1932

    
1933
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1934
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
1935
         "count=%d" % size]
1936
  result = utils.RunCmd(cmd)
1937

    
1938
  if result.failed:
1939
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1940
          result.fail_reason, result.output)
1941

    
1942

    
1943
def BlockdevWipe(disk, offset, size):
1944
  """Wipes a block device.
1945

1946
  @type disk: L{objects.Disk}
1947
  @param disk: the disk object we want to wipe
1948
  @type offset: int
1949
  @param offset: The offset in MiB in the file
1950
  @type size: int
1951
  @param size: The size in MiB to write
1952

1953
  """
1954
  try:
1955
    rdev = _RecursiveFindBD(disk)
1956
  except errors.BlockDeviceError:
1957
    rdev = None
1958

    
1959
  if not rdev:
1960
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1961

    
1962
  # Do cross verify some of the parameters
1963
  if offset < 0:
1964
    _Fail("Negative offset")
1965
  if size < 0:
1966
    _Fail("Negative size")
1967
  if offset > rdev.size:
1968
    _Fail("Offset is bigger than device size")
1969
  if (offset + size) > rdev.size:
1970
    _Fail("The provided offset and size to wipe is bigger than device size")
1971

    
1972
  _WipeDevice(rdev.dev_path, offset, size)
1973

    
1974

    
1975
def BlockdevPauseResumeSync(disks, pause):
1976
  """Pause or resume the sync of the block device.
1977

1978
  @type disks: list of L{objects.Disk}
1979
  @param disks: the disks object we want to pause/resume
1980
  @type pause: bool
1981
  @param pause: Wheater to pause or resume
1982

1983
  """
1984
  success = []
1985
  for disk in disks:
1986
    try:
1987
      rdev = _RecursiveFindBD(disk)
1988
    except errors.BlockDeviceError:
1989
      rdev = None
1990

    
1991
    if not rdev:
1992
      success.append((False, ("Cannot change sync for device %s:"
1993
                              " device not found" % disk.iv_name)))
1994
      continue
1995

    
1996
    result = rdev.PauseResumeSync(pause)
1997

    
1998
    if result:
1999
      success.append((result, None))
2000
    else:
2001
      if pause:
2002
        msg = "Pause"
2003
      else:
2004
        msg = "Resume"
2005
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
2006

    
2007
  return success
2008

    
2009

    
2010
def BlockdevRemove(disk):
2011
  """Remove a block device.
2012

2013
  @note: This is intended to be called recursively.
2014

2015
  @type disk: L{objects.Disk}
2016
  @param disk: the disk object we should remove
2017
  @rtype: boolean
2018
  @return: the success of the operation
2019

2020
  """
2021
  msgs = []
2022
  try:
2023
    rdev = _RecursiveFindBD(disk)
2024
  except errors.BlockDeviceError, err:
2025
    # probably can't attach
2026
    logging.info("Can't attach to device %s in remove", disk)
2027
    rdev = None
2028
  if rdev is not None:
2029
    r_path = rdev.dev_path
2030
    try:
2031
      rdev.Remove()
2032
    except errors.BlockDeviceError, err:
2033
      msgs.append(str(err))
2034
    if not msgs:
2035
      DevCacheManager.RemoveCache(r_path)
2036

    
2037
  if disk.children:
2038
    for child in disk.children:
2039
      try:
2040
        BlockdevRemove(child)
2041
      except RPCFail, err:
2042
        msgs.append(str(err))
2043

    
2044
  if msgs:
2045
    _Fail("; ".join(msgs))
2046

    
2047

    
2048
def _RecursiveAssembleBD(disk, owner, as_primary):
2049
  """Activate a block device for an instance.
2050

2051
  This is run on the primary and secondary nodes for an instance.
2052

2053
  @note: this function is called recursively.
2054

2055
  @type disk: L{objects.Disk}
2056
  @param disk: the disk we try to assemble
2057
  @type owner: str
2058
  @param owner: the name of the instance which owns the disk
2059
  @type as_primary: boolean
2060
  @param as_primary: if we should make the block device
2061
      read/write
2062

2063
  @return: the assembled device or None (in case no device
2064
      was assembled)
2065
  @raise errors.BlockDeviceError: in case there is an error
2066
      during the activation of the children or the device
2067
      itself
2068

2069
  """
2070
  children = []
2071
  if disk.children:
2072
    mcn = disk.ChildrenNeeded()
2073
    if mcn == -1:
2074
      mcn = 0 # max number of Nones allowed
2075
    else:
2076
      mcn = len(disk.children) - mcn # max number of Nones
2077
    for chld_disk in disk.children:
2078
      try:
2079
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
2080
      except errors.BlockDeviceError, err:
2081
        if children.count(None) >= mcn:
2082
          raise
2083
        cdev = None
2084
        logging.error("Error in child activation (but continuing): %s",
2085
                      str(err))
2086
      children.append(cdev)
2087

    
2088
  if as_primary or disk.AssembleOnSecondary():
2089
    r_dev = bdev.Assemble(disk, children)
2090
    result = r_dev
2091
    if as_primary or disk.OpenOnSecondary():
2092
      r_dev.Open()
2093
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
2094
                                as_primary, disk.iv_name)
2095

    
2096
  else:
2097
    result = True
2098
  return result
2099

    
2100

    
2101
def BlockdevAssemble(disk, owner, as_primary, idx):
2102
  """Activate a block device for an instance.
2103

2104
  This is a wrapper over _RecursiveAssembleBD.
2105

2106
  @rtype: str or boolean
2107
  @return: a C{/dev/...} path for primary nodes, and
2108
      C{True} for secondary nodes
2109

2110
  """
2111
  try:
2112
    result = _RecursiveAssembleBD(disk, owner, as_primary)
2113
    if isinstance(result, BlockDev):
2114
      # pylint: disable=E1103
2115
      result = result.dev_path
2116
      if as_primary:
2117
        _SymlinkBlockDev(owner, result, idx)
2118
  except errors.BlockDeviceError, err:
2119
    _Fail("Error while assembling disk: %s", err, exc=True)
2120
  except OSError, err:
2121
    _Fail("Error while symlinking disk: %s", err, exc=True)
2122

    
2123
  return result
2124

    
2125

    
2126
def BlockdevShutdown(disk):
2127
  """Shut down a block device.
2128

2129
  First, if the device is assembled (Attach() is successful), then
2130
  the device is shutdown. Then the children of the device are
2131
  shutdown.
2132

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

2137
  @type disk: L{objects.Disk}
2138
  @param disk: the description of the disk we should
2139
      shutdown
2140
  @rtype: None
2141

2142
  """
2143
  msgs = []
2144
  r_dev = _RecursiveFindBD(disk)
2145
  if r_dev is not None:
2146
    r_path = r_dev.dev_path
2147
    try:
2148
      r_dev.Shutdown()
2149
      DevCacheManager.RemoveCache(r_path)
2150
    except errors.BlockDeviceError, err:
2151
      msgs.append(str(err))
2152

    
2153
  if disk.children:
2154
    for child in disk.children:
2155
      try:
2156
        BlockdevShutdown(child)
2157
      except RPCFail, err:
2158
        msgs.append(str(err))
2159

    
2160
  if msgs:
2161
    _Fail("; ".join(msgs))
2162

    
2163

    
2164
def BlockdevAddchildren(parent_cdev, new_cdevs):
2165
  """Extend a mirrored block device.
2166

2167
  @type parent_cdev: L{objects.Disk}
2168
  @param parent_cdev: the disk to which we should add children
2169
  @type new_cdevs: list of L{objects.Disk}
2170
  @param new_cdevs: the list of children which we should add
2171
  @rtype: None
2172

2173
  """
2174
  parent_bdev = _RecursiveFindBD(parent_cdev)
2175
  if parent_bdev is None:
2176
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
2177
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
2178
  if new_bdevs.count(None) > 0:
2179
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
2180
  parent_bdev.AddChildren(new_bdevs)
2181

    
2182

    
2183
def BlockdevRemovechildren(parent_cdev, new_cdevs):
2184
  """Shrink a mirrored block device.
2185

2186
  @type parent_cdev: L{objects.Disk}
2187
  @param parent_cdev: the disk from which we should remove children
2188
  @type new_cdevs: list of L{objects.Disk}
2189
  @param new_cdevs: the list of children which we should remove
2190
  @rtype: None
2191

2192
  """
2193
  parent_bdev = _RecursiveFindBD(parent_cdev)
2194
  if parent_bdev is None:
2195
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
2196
  devs = []
2197
  for disk in new_cdevs:
2198
    rpath = disk.StaticDevPath()
2199
    if rpath is None:
2200
      bd = _RecursiveFindBD(disk)
2201
      if bd is None:
2202
        _Fail("Can't find device %s while removing children", disk)
2203
      else:
2204
        devs.append(bd.dev_path)
2205
    else:
2206
      if not utils.IsNormAbsPath(rpath):
2207
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
2208
      devs.append(rpath)
2209
  parent_bdev.RemoveChildren(devs)
2210

    
2211

    
2212
def BlockdevGetmirrorstatus(disks):
2213
  """Get the mirroring status of a list of devices.
2214

2215
  @type disks: list of L{objects.Disk}
2216
  @param disks: the list of disks which we should query
2217
  @rtype: disk
2218
  @return: List of L{objects.BlockDevStatus}, one for each disk
2219
  @raise errors.BlockDeviceError: if any of the disks cannot be
2220
      found
2221

2222
  """
2223
  stats = []
2224
  for dsk in disks:
2225
    rbd = _RecursiveFindBD(dsk)
2226
    if rbd is None:
2227
      _Fail("Can't find device %s", dsk)
2228

    
2229
    stats.append(rbd.CombinedSyncStatus())
2230

    
2231
  return stats
2232

    
2233

    
2234
def BlockdevGetmirrorstatusMulti(disks):
2235
  """Get the mirroring status of a list of devices.
2236

2237
  @type disks: list of L{objects.Disk}
2238
  @param disks: the list of disks which we should query
2239
  @rtype: disk
2240
  @return: List of tuples, (bool, status), one for each disk; bool denotes
2241
    success/failure, status is L{objects.BlockDevStatus} on success, string
2242
    otherwise
2243

2244
  """
2245
  result = []
2246
  for disk in disks:
2247
    try:
2248
      rbd = _RecursiveFindBD(disk)
2249
      if rbd is None:
2250
        result.append((False, "Can't find device %s" % disk))
2251
        continue
2252

    
2253
      status = rbd.CombinedSyncStatus()
2254
    except errors.BlockDeviceError, err:
2255
      logging.exception("Error while getting disk status")
2256
      result.append((False, str(err)))
2257
    else:
2258
      result.append((True, status))
2259

    
2260
  assert len(disks) == len(result)
2261

    
2262
  return result
2263

    
2264

    
2265
def _RecursiveFindBD(disk):
2266
  """Check if a device is activated.
2267

2268
  If so, return information about the real device.
2269

2270
  @type disk: L{objects.Disk}
2271
  @param disk: the disk object we need to find
2272

2273
  @return: None if the device can't be found,
2274
      otherwise the device instance
2275

2276
  """
2277
  children = []
2278
  if disk.children:
2279
    for chdisk in disk.children:
2280
      children.append(_RecursiveFindBD(chdisk))
2281

    
2282
  return bdev.FindDevice(disk, children)
2283

    
2284

    
2285
def _OpenRealBD(disk):
2286
  """Opens the underlying block device of a disk.
2287

2288
  @type disk: L{objects.Disk}
2289
  @param disk: the disk object we want to open
2290

2291
  """
2292
  real_disk = _RecursiveFindBD(disk)
2293
  if real_disk is None:
2294
    _Fail("Block device '%s' is not set up", disk)
2295

    
2296
  real_disk.Open()
2297

    
2298
  return real_disk
2299

    
2300

    
2301
def BlockdevFind(disk):
2302
  """Check if a device is activated.
2303

2304
  If it is, return information about the real device.
2305

2306
  @type disk: L{objects.Disk}
2307
  @param disk: the disk to find
2308
  @rtype: None or objects.BlockDevStatus
2309
  @return: None if the disk cannot be found, otherwise a the current
2310
           information
2311

2312
  """
2313
  try:
2314
    rbd = _RecursiveFindBD(disk)
2315
  except errors.BlockDeviceError, err:
2316
    _Fail("Failed to find device: %s", err, exc=True)
2317

    
2318
  if rbd is None:
2319
    return None
2320

    
2321
  return rbd.GetSyncStatus()
2322

    
2323

    
2324
def BlockdevGetdimensions(disks):
2325
  """Computes the size of the given disks.
2326

2327
  If a disk is not found, returns None instead.
2328

2329
  @type disks: list of L{objects.Disk}
2330
  @param disks: the list of disk to compute the size for
2331
  @rtype: list
2332
  @return: list with elements None if the disk cannot be found,
2333
      otherwise the pair (size, spindles), where spindles is None if the
2334
      device doesn't support that
2335

2336
  """
2337
  result = []
2338
  for cf in disks:
2339
    try:
2340
      rbd = _RecursiveFindBD(cf)
2341
    except errors.BlockDeviceError:
2342
      result.append(None)
2343
      continue
2344
    if rbd is None:
2345
      result.append(None)
2346
    else:
2347
      result.append(rbd.GetActualDimensions())
2348
  return result
2349

    
2350

    
2351
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2352
  """Export a block device to a remote node.
2353

2354
  @type disk: L{objects.Disk}
2355
  @param disk: the description of the disk to export
2356
  @type dest_node: str
2357
  @param dest_node: the destination node to export to
2358
  @type dest_path: str
2359
  @param dest_path: the destination path on the target node
2360
  @type cluster_name: str
2361
  @param cluster_name: the cluster name, needed for SSH hostalias
2362
  @rtype: None
2363

2364
  """
2365
  real_disk = _OpenRealBD(disk)
2366

    
2367
  # the block size on the read dd is 1MiB to match our units
2368
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2369
                               "dd if=%s bs=1048576 count=%s",
2370
                               real_disk.dev_path, str(disk.size))
2371

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

    
2381
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2382
                                                   constants.SSH_LOGIN_USER,
2383
                                                   destcmd)
2384

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

    
2388
  result = utils.RunCmd(["bash", "-c", command])
2389

    
2390
  if result.failed:
2391
    _Fail("Disk copy command '%s' returned error: %s"
2392
          " output: %s", command, result.fail_reason, result.output)
2393

    
2394

    
2395
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2396
  """Write a file to the filesystem.
2397

2398
  This allows the master to overwrite(!) a file. It will only perform
2399
  the operation if the file belongs to a list of configuration files.
2400

2401
  @type file_name: str
2402
  @param file_name: the target file name
2403
  @type data: str
2404
  @param data: the new contents of the file
2405
  @type mode: int
2406
  @param mode: the mode to give the file (can be None)
2407
  @type uid: string
2408
  @param uid: the owner of the file
2409
  @type gid: string
2410
  @param gid: the group of the file
2411
  @type atime: float
2412
  @param atime: the atime to set on the file (can be None)
2413
  @type mtime: float
2414
  @param mtime: the mtime to set on the file (can be None)
2415
  @rtype: None
2416

2417
  """
2418
  file_name = vcluster.LocalizeVirtualPath(file_name)
2419

    
2420
  if not os.path.isabs(file_name):
2421
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2422

    
2423
  if file_name not in _ALLOWED_UPLOAD_FILES:
2424
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2425
          file_name)
2426

    
2427
  raw_data = _Decompress(data)
2428

    
2429
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2430
    _Fail("Invalid username/groupname type")
2431

    
2432
  getents = runtime.GetEnts()
2433
  uid = getents.LookupUser(uid)
2434
  gid = getents.LookupGroup(gid)
2435

    
2436
  utils.SafeWriteFile(file_name, None,
2437
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2438
                      atime=atime, mtime=mtime)
2439

    
2440

    
2441
def RunOob(oob_program, command, node, timeout):
2442
  """Executes oob_program with given command on given node.
2443

2444
  @param oob_program: The path to the executable oob_program
2445
  @param command: The command to invoke on oob_program
2446
  @param node: The node given as an argument to the program
2447
  @param timeout: Timeout after which we kill the oob program
2448

2449
  @return: stdout
2450
  @raise RPCFail: If execution fails for some reason
2451

2452
  """
2453
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2454

    
2455
  if result.failed:
2456
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2457
          result.fail_reason, result.output)
2458

    
2459
  return result.stdout
2460

    
2461

    
2462
def _OSOndiskAPIVersion(os_dir):
2463
  """Compute and return the API version of a given OS.
2464

2465
  This function will try to read the API version of the OS residing in
2466
  the 'os_dir' directory.
2467

2468
  @type os_dir: str
2469
  @param os_dir: the directory in which we should look for the OS
2470
  @rtype: tuple
2471
  @return: tuple (status, data) with status denoting the validity and
2472
      data holding either the vaid versions or an error message
2473

2474
  """
2475
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2476

    
2477
  try:
2478
    st = os.stat(api_file)
2479
  except EnvironmentError, err:
2480
    return False, ("Required file '%s' not found under path %s: %s" %
2481
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2482

    
2483
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2484
    return False, ("File '%s' in %s is not a regular file" %
2485
                   (constants.OS_API_FILE, os_dir))
2486

    
2487
  try:
2488
    api_versions = utils.ReadFile(api_file).splitlines()
2489
  except EnvironmentError, err:
2490
    return False, ("Error while reading the API version file at %s: %s" %
2491
                   (api_file, utils.ErrnoOrStr(err)))
2492

    
2493
  try:
2494
    api_versions = [int(version.strip()) for version in api_versions]
2495
  except (TypeError, ValueError), err:
2496
    return False, ("API version(s) can't be converted to integer: %s" %
2497
                   str(err))
2498

    
2499
  return True, api_versions
2500

    
2501

    
2502
def DiagnoseOS(top_dirs=None):
2503
  """Compute the validity for all OSes.
2504

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

2521
  """
2522
  if top_dirs is None:
2523
    top_dirs = pathutils.OS_SEARCH_PATH
2524

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

    
2547
  return result
2548

    
2549

    
2550
def _TryOSFromDisk(name, base_dir=None):
2551
  """Create an OS instance from disk.
2552

2553
  This function will return an OS instance if the given name is a
2554
  valid OS name.
2555

2556
  @type base_dir: string
2557
  @keyword base_dir: Base directory containing OS installations.
2558
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2559
  @rtype: tuple
2560
  @return: success and either the OS instance if we find a valid one,
2561
      or error message
2562

2563
  """
2564
  if base_dir is None:
2565
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2566
  else:
2567
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2568

    
2569
  if os_dir is None:
2570
    return False, "Directory for OS %s not found in search path" % name
2571

    
2572
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2573
  if not status:
2574
    # push the error up
2575
    return status, api_versions
2576

    
2577
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2578
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2579
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2580

    
2581
  # OS Files dictionary, we will populate it with the absolute path
2582
  # names; if the value is True, then it is a required file, otherwise
2583
  # an optional one
2584
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2585

    
2586
  if max(api_versions) >= constants.OS_API_V15:
2587
    os_files[constants.OS_VARIANTS_FILE] = False
2588

    
2589
  if max(api_versions) >= constants.OS_API_V20:
2590
    os_files[constants.OS_PARAMETERS_FILE] = True
2591
  else:
2592
    del os_files[constants.OS_SCRIPT_VERIFY]
2593

    
2594
  for (filename, required) in os_files.items():
2595
    os_files[filename] = utils.PathJoin(os_dir, filename)
2596

    
2597
    try:
2598
      st = os.stat(os_files[filename])
2599
    except EnvironmentError, err:
2600
      if err.errno == errno.ENOENT and not required:
2601
        del os_files[filename]
2602
        continue
2603
      return False, ("File '%s' under path '%s' is missing (%s)" %
2604
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2605

    
2606
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2607
      return False, ("File '%s' under path '%s' is not a regular file" %
2608
                     (filename, os_dir))
2609

    
2610
    if filename in constants.OS_SCRIPTS:
2611
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2612
        return False, ("File '%s' under path '%s' is not executable" %
2613
                       (filename, os_dir))
2614

    
2615
  variants = []
2616
  if constants.OS_VARIANTS_FILE in os_files:
2617
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2618
    try:
2619
      variants = \
2620
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2621
    except EnvironmentError, err:
2622
      # we accept missing files, but not other errors
2623
      if err.errno != errno.ENOENT:
2624
        return False, ("Error while reading the OS variants file at %s: %s" %
2625
                       (variants_file, utils.ErrnoOrStr(err)))
2626

    
2627
  parameters = []
2628
  if constants.OS_PARAMETERS_FILE in os_files:
2629
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2630
    try:
2631
      parameters = utils.ReadFile(parameters_file).splitlines()
2632
    except EnvironmentError, err:
2633
      return False, ("Error while reading the OS parameters file at %s: %s" %
2634
                     (parameters_file, utils.ErrnoOrStr(err)))
2635
    parameters = [v.split(None, 1) for v in parameters]
2636

    
2637
  os_obj = objects.OS(name=name, path=os_dir,
2638
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2639
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2640
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2641
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2642
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2643
                                                 None),
2644
                      supported_variants=variants,
2645
                      supported_parameters=parameters,
2646
                      api_versions=api_versions)
2647
  return True, os_obj
2648

    
2649

    
2650
def OSFromDisk(name, base_dir=None):
2651
  """Create an OS instance from disk.
2652

2653
  This function will return an OS instance if the given name is a
2654
  valid OS name. Otherwise, it will raise an appropriate
2655
  L{RPCFail} exception, detailing why this is not a valid OS.
2656

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

2660
  @type base_dir: string
2661
  @keyword base_dir: Base directory containing OS installations.
2662
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2663
  @rtype: L{objects.OS}
2664
  @return: the OS instance if we find a valid one
2665
  @raise RPCFail: if we don't find a valid OS
2666

2667
  """
2668
  name_only = objects.OS.GetName(name)
2669
  status, payload = _TryOSFromDisk(name_only, base_dir)
2670

    
2671
  if not status:
2672
    _Fail(payload)
2673

    
2674
  return payload
2675

    
2676

    
2677
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2678
  """Calculate the basic environment for an os script.
2679

2680
  @type os_name: str
2681
  @param os_name: full operating system name (including variant)
2682
  @type inst_os: L{objects.OS}
2683
  @param inst_os: operating system for which the environment is being built
2684
  @type os_params: dict
2685
  @param os_params: the OS parameters
2686
  @type debug: integer
2687
  @param debug: debug level (0 or 1, for OS Api 10)
2688
  @rtype: dict
2689
  @return: dict of environment variables
2690
  @raise errors.BlockDeviceError: if the block device
2691
      cannot be found
2692

2693
  """
2694
  result = {}
2695
  api_version = \
2696
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2697
  result["OS_API_VERSION"] = "%d" % api_version
2698
  result["OS_NAME"] = inst_os.name
2699
  result["DEBUG_LEVEL"] = "%d" % debug
2700

    
2701
  # OS variants
2702
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2703
    variant = objects.OS.GetVariant(os_name)
2704
    if not variant:
2705
      variant = inst_os.supported_variants[0]
2706
  else:
2707
    variant = ""
2708
  result["OS_VARIANT"] = variant
2709

    
2710
  # OS params
2711
  for pname, pvalue in os_params.items():
2712
    result["OSP_%s" % pname.upper()] = pvalue
2713

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

    
2719
  return result
2720

    
2721

    
2722
def OSEnvironment(instance, inst_os, debug=0):
2723
  """Calculate the environment for an os script.
2724

2725
  @type instance: L{objects.Instance}
2726
  @param instance: target instance for the os script run
2727
  @type inst_os: L{objects.OS}
2728
  @param inst_os: operating system for which the environment is being built
2729
  @type debug: integer
2730
  @param debug: debug level (0 or 1, for OS Api 10)
2731
  @rtype: dict
2732
  @return: dict of environment variables
2733
  @raise errors.BlockDeviceError: if the block device
2734
      cannot be found
2735

2736
  """
2737
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2738

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

    
2742
  result["HYPERVISOR"] = instance.hypervisor
2743
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2744
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2745
  result["INSTANCE_SECONDARY_NODES"] = \
2746
      ("%s" % " ".join(instance.secondary_nodes))
2747

    
2748
  # Disks
2749
  for idx, disk in enumerate(instance.disks):
2750
    real_disk = _OpenRealBD(disk)
2751
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2752
    result["DISK_%d_ACCESS" % idx] = disk.mode
2753
    if constants.HV_DISK_TYPE in instance.hvparams:
2754
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2755
        instance.hvparams[constants.HV_DISK_TYPE]
2756
    if disk.dev_type in constants.LDS_BLOCK:
2757
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2758
    elif disk.dev_type == constants.LD_FILE:
2759
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2760
        "file:%s" % disk.physical_id[0]
2761

    
2762
  # NICs
2763
  for idx, nic in enumerate(instance.nics):
2764
    result["NIC_%d_MAC" % idx] = nic.mac
2765
    if nic.ip:
2766
      result["NIC_%d_IP" % idx] = nic.ip
2767
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2768
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2769
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2770
    if nic.nicparams[constants.NIC_LINK]:
2771
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2772
    if nic.netinfo:
2773
      nobj = objects.Network.FromDict(nic.netinfo)
2774
      result.update(nobj.HooksDict("NIC_%d_" % idx))
2775
    if constants.HV_NIC_TYPE in instance.hvparams:
2776
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2777
        instance.hvparams[constants.HV_NIC_TYPE]
2778

    
2779
  # HV/BE params
2780
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2781
    for key, value in source.items():
2782
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2783

    
2784
  return result
2785

    
2786

    
2787
def DiagnoseExtStorage(top_dirs=None):
2788
  """Compute the validity for all ExtStorage Providers.
2789

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

2805
  """
2806
  if top_dirs is None:
2807
    top_dirs = pathutils.ES_SEARCH_PATH
2808

    
2809
  result = []
2810
  for dir_name in top_dirs:
2811
    if os.path.isdir(dir_name):
2812
      try:
2813
        f_names = utils.ListVisibleFiles(dir_name)
2814
      except EnvironmentError, err:
2815
        logging.exception("Can't list the ExtStorage directory %s: %s",
2816
                          dir_name, err)
2817
        break
2818
      for name in f_names:
2819
        es_path = utils.PathJoin(dir_name, name)
2820
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2821
        if status:
2822
          diagnose = ""
2823
          parameters = es_inst.supported_parameters
2824
        else:
2825
          diagnose = es_inst
2826
          parameters = []
2827
        result.append((name, es_path, status, diagnose, parameters))
2828

    
2829
  return result
2830

    
2831

    
2832
def BlockdevGrow(disk, amount, dryrun, backingstore):
2833
  """Grow a stack of block devices.
2834

2835
  This function is called recursively, with the childrens being the
2836
  first ones to resize.
2837

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

2852
  """
2853
  r_dev = _RecursiveFindBD(disk)
2854
  if r_dev is None:
2855
    _Fail("Cannot find block device %s", disk)
2856

    
2857
  try:
2858
    r_dev.Grow(amount, dryrun, backingstore)
2859
  except errors.BlockDeviceError, err:
2860
    _Fail("Failed to grow block device: %s", err, exc=True)
2861

    
2862

    
2863
def BlockdevSnapshot(disk):
2864
  """Create a snapshot copy of a block device.
2865

2866
  This function is called recursively, and the snapshot is actually created
2867
  just for the leaf lvm backend device.
2868

2869
  @type disk: L{objects.Disk}
2870
  @param disk: the disk to be snapshotted
2871
  @rtype: string
2872
  @return: snapshot disk ID as (vg, lv)
2873

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

    
2892

    
2893
def BlockdevSetInfo(disk, info):
2894
  """Sets 'metadata' information on block devices.
2895

2896
  This function sets 'info' metadata on block devices. Initial
2897
  information is set at device creation; this function should be used
2898
  for example after renames.
2899

2900
  @type disk: L{objects.Disk}
2901
  @param disk: the disk to be grown
2902
  @type info: string
2903
  @param info: new 'info' metadata
2904
  @rtype: (status, result)
2905
  @return: a tuple with the status of the operation (True/False), and
2906
      the errors message if status is False
2907

2908
  """
2909
  r_dev = _RecursiveFindBD(disk)
2910
  if r_dev is None:
2911
    _Fail("Cannot find block device %s", disk)
2912

    
2913
  try:
2914
    r_dev.SetInfo(info)
2915
  except errors.BlockDeviceError, err:
2916
    _Fail("Failed to set information on block device: %s", err, exc=True)
2917

    
2918

    
2919
def FinalizeExport(instance, snap_disks):
2920
  """Write out the export configuration information.
2921

2922
  @type instance: L{objects.Instance}
2923
  @param instance: the instance which we export, used for
2924
      saving configuration
2925
  @type snap_disks: list of L{objects.Disk}
2926
  @param snap_disks: list of snapshot block devices, which
2927
      will be used to get the actual name of the dump file
2928

2929
  @rtype: None
2930

2931
  """
2932
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
2933
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
2934

    
2935
  config = objects.SerializableConfigParser()
2936

    
2937
  config.add_section(constants.INISECT_EXP)
2938
  config.set(constants.INISECT_EXP, "version", "0")
2939
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2940
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2941
  config.set(constants.INISECT_EXP, "os", instance.os)
2942
  config.set(constants.INISECT_EXP, "compression", "none")
2943

    
2944
  config.add_section(constants.INISECT_INS)
2945
  config.set(constants.INISECT_INS, "name", instance.name)
2946
  config.set(constants.INISECT_INS, "maxmem", "%d" %
2947
             instance.beparams[constants.BE_MAXMEM])
2948
  config.set(constants.INISECT_INS, "minmem", "%d" %
2949
             instance.beparams[constants.BE_MINMEM])
2950
  # "memory" is deprecated, but useful for exporting to old ganeti versions
2951
  config.set(constants.INISECT_INS, "memory", "%d" %
2952
             instance.beparams[constants.BE_MAXMEM])
2953
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2954
             instance.beparams[constants.BE_VCPUS])
2955
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2956
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2957
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2958

    
2959
  nic_total = 0
2960
  for nic_count, nic in enumerate(instance.nics):
2961
    nic_total += 1
2962
    config.set(constants.INISECT_INS, "nic%d_mac" %
2963
               nic_count, "%s" % nic.mac)
2964
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2965
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
2966
               "%s" % nic.network)
2967
    for param in constants.NICS_PARAMETER_TYPES:
2968
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2969
                 "%s" % nic.nicparams.get(param, None))
2970
  # TODO: redundant: on load can read nics until it doesn't exist
2971
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2972

    
2973
  disk_total = 0
2974
  for disk_count, disk in enumerate(snap_disks):
2975
    if disk:
2976
      disk_total += 1
2977
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2978
                 ("%s" % disk.iv_name))
2979
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2980
                 ("%s" % disk.physical_id[1]))
2981
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2982
                 ("%d" % disk.size))
2983

    
2984
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2985

    
2986
  # New-style hypervisor/backend parameters
2987

    
2988
  config.add_section(constants.INISECT_HYP)
2989
  for name, value in instance.hvparams.items():
2990
    if name not in constants.HVC_GLOBALS:
2991
      config.set(constants.INISECT_HYP, name, str(value))
2992

    
2993
  config.add_section(constants.INISECT_BEP)
2994
  for name, value in instance.beparams.items():
2995
    config.set(constants.INISECT_BEP, name, str(value))
2996

    
2997
  config.add_section(constants.INISECT_OSP)
2998
  for name, value in instance.osparams.items():
2999
    config.set(constants.INISECT_OSP, name, str(value))
3000

    
3001
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
3002
                  data=config.Dumps())
3003
  shutil.rmtree(finaldestdir, ignore_errors=True)
3004
  shutil.move(destdir, finaldestdir)
3005

    
3006

    
3007
def ExportInfo(dest):
3008
  """Get export configuration information.
3009

3010
  @type dest: str
3011
  @param dest: directory containing the export
3012

3013
  @rtype: L{objects.SerializableConfigParser}
3014
  @return: a serializable config file containing the
3015
      export info
3016

3017
  """
3018
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
3019

    
3020
  config = objects.SerializableConfigParser()
3021
  config.read(cff)
3022

    
3023
  if (not config.has_section(constants.INISECT_EXP) or
3024
      not config.has_section(constants.INISECT_INS)):
3025
    _Fail("Export info file doesn't have the required fields")
3026

    
3027
  return config.Dumps()
3028

    
3029

    
3030
def ListExports():
3031
  """Return a list of exports currently available on this machine.
3032

3033
  @rtype: list
3034
  @return: list of the exports
3035

3036
  """
3037
  if os.path.isdir(pathutils.EXPORT_DIR):
3038
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
3039
  else:
3040
    _Fail("No exports directory")
3041

    
3042

    
3043
def RemoveExport(export):
3044
  """Remove an existing export from the node.
3045

3046
  @type export: str
3047
  @param export: the name of the export to remove
3048
  @rtype: None
3049

3050
  """
3051
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
3052

    
3053
  try:
3054
    shutil.rmtree(target)
3055
  except EnvironmentError, err:
3056
    _Fail("Error while removing the export: %s", err, exc=True)
3057

    
3058

    
3059
def BlockdevRename(devlist):
3060
  """Rename a list of block devices.
3061

3062
  @type devlist: list of tuples
3063
  @param devlist: list of tuples of the form  (disk,
3064
      new_logical_id, new_physical_id); disk is an
3065
      L{objects.Disk} object describing the current disk,
3066
      and new logical_id/physical_id is the name we
3067
      rename it to
3068
  @rtype: boolean
3069
  @return: True if all renames succeeded, False otherwise
3070

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

    
3099

    
3100
def _TransformFileStorageDir(fs_dir):
3101
  """Checks whether given file_storage_dir is valid.
3102

3103
  Checks wheter the given fs_dir is within the cluster-wide default
3104
  file_storage_dir or the shared_file_storage_dir, which are stored in
3105
  SimpleStore. Only paths under those directories are allowed.
3106

3107
  @type fs_dir: str
3108
  @param fs_dir: the path to check
3109

3110
  @return: the normalized path if valid, None otherwise
3111

3112
  """
3113
  if not (constants.ENABLE_FILE_STORAGE or
3114
          constants.ENABLE_SHARED_FILE_STORAGE):
3115
    _Fail("File storage disabled at configure time")
3116

    
3117
  bdev.CheckFileStoragePath(fs_dir)
3118

    
3119
  return os.path.normpath(fs_dir)
3120

    
3121

    
3122
def CreateFileStorageDir(file_storage_dir):
3123
  """Create file storage directory.
3124

3125
  @type file_storage_dir: str
3126
  @param file_storage_dir: directory to create
3127

3128
  @rtype: tuple
3129
  @return: tuple with first element a boolean indicating wheter dir
3130
      creation was successful or not
3131

3132
  """
3133
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3134
  if os.path.exists(file_storage_dir):
3135
    if not os.path.isdir(file_storage_dir):
3136
      _Fail("Specified storage dir '%s' is not a directory",
3137
            file_storage_dir)
3138
  else:
3139
    try:
3140
      os.makedirs(file_storage_dir, 0750)
3141
    except OSError, err:
3142
      _Fail("Cannot create file storage directory '%s': %s",
3143
            file_storage_dir, err, exc=True)
3144

    
3145

    
3146
def RemoveFileStorageDir(file_storage_dir):
3147
  """Remove file storage directory.
3148

3149
  Remove it only if it's empty. If not log an error and return.
3150

3151
  @type file_storage_dir: str
3152
  @param file_storage_dir: the directory we should cleanup
3153
  @rtype: tuple (success,)
3154
  @return: tuple of one element, C{success}, denoting
3155
      whether the operation was successful
3156

3157
  """
3158
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3159
  if os.path.exists(file_storage_dir):
3160
    if not os.path.isdir(file_storage_dir):
3161
      _Fail("Specified Storage directory '%s' is not a directory",
3162
            file_storage_dir)
3163
    # deletes dir only if empty, otherwise we want to fail the rpc call
3164
    try:
3165
      os.rmdir(file_storage_dir)
3166
    except OSError, err:
3167
      _Fail("Cannot remove file storage directory '%s': %s",
3168
            file_storage_dir, err)
3169

    
3170

    
3171
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
3172
  """Rename the file storage directory.
3173

3174
  @type old_file_storage_dir: str
3175
  @param old_file_storage_dir: the current path
3176
  @type new_file_storage_dir: str
3177
  @param new_file_storage_dir: the name we should rename to
3178
  @rtype: tuple (success,)
3179
  @return: tuple of one element, C{success}, denoting
3180
      whether the operation was successful
3181

3182
  """
3183
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
3184
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
3185
  if not os.path.exists(new_file_storage_dir):
3186
    if os.path.isdir(old_file_storage_dir):
3187
      try:
3188
        os.rename(old_file_storage_dir, new_file_storage_dir)
3189
      except OSError, err:
3190
        _Fail("Cannot rename '%s' to '%s': %s",
3191
              old_file_storage_dir, new_file_storage_dir, err)
3192
    else:
3193
      _Fail("Specified storage dir '%s' is not a directory",
3194
            old_file_storage_dir)
3195
  else:
3196
    if os.path.exists(old_file_storage_dir):
3197
      _Fail("Cannot rename '%s' to '%s': both locations exist",
3198
            old_file_storage_dir, new_file_storage_dir)
3199

    
3200

    
3201
def _EnsureJobQueueFile(file_name):
3202
  """Checks whether the given filename is in the queue directory.
3203

3204
  @type file_name: str
3205
  @param file_name: the file name we should check
3206
  @rtype: None
3207
  @raises RPCFail: if the file is not valid
3208

3209
  """
3210
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
3211
    _Fail("Passed job queue file '%s' does not belong to"
3212
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
3213

    
3214

    
3215
def JobQueueUpdate(file_name, content):
3216
  """Updates a file in the queue directory.
3217

3218
  This is just a wrapper over L{utils.io.WriteFile}, with proper
3219
  checking.
3220

3221
  @type file_name: str
3222
  @param file_name: the job file name
3223
  @type content: str
3224
  @param content: the new job contents
3225
  @rtype: boolean
3226
  @return: the success of the operation
3227

3228
  """
3229
  file_name = vcluster.LocalizeVirtualPath(file_name)
3230

    
3231
  _EnsureJobQueueFile(file_name)
3232
  getents = runtime.GetEnts()
3233

    
3234
  # Write and replace the file atomically
3235
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3236
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3237

    
3238

    
3239
def JobQueueRename(old, new):
3240
  """Renames a job queue file.
3241

3242
  This is just a wrapper over os.rename with proper checking.
3243

3244
  @type old: str
3245
  @param old: the old (actual) file name
3246
  @type new: str
3247
  @param new: the desired file name
3248
  @rtype: tuple
3249
  @return: the success of the operation and payload
3250

3251
  """
3252
  old = vcluster.LocalizeVirtualPath(old)
3253
  new = vcluster.LocalizeVirtualPath(new)
3254

    
3255
  _EnsureJobQueueFile(old)
3256
  _EnsureJobQueueFile(new)
3257

    
3258
  getents = runtime.GetEnts()
3259

    
3260
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3261
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3262

    
3263

    
3264
def BlockdevClose(instance_name, disks):
3265
  """Closes the given block devices.
3266

3267
  This means they will be switched to secondary mode (in case of
3268
  DRBD).
3269

3270
  @param instance_name: if the argument is not empty, the symlinks
3271
      of this instance will be removed
3272
  @type disks: list of L{objects.Disk}
3273
  @param disks: the list of disks to be closed
3274
  @rtype: tuple (success, message)
3275
  @return: a tuple of success and message, where success
3276
      indicates the succes of the operation, and message
3277
      which will contain the error details in case we
3278
      failed
3279

3280
  """
3281
  bdevs = []
3282
  for cf in disks:
3283
    rd = _RecursiveFindBD(cf)
3284
    if rd is None:
3285
      _Fail("Can't find device %s", cf)
3286
    bdevs.append(rd)
3287

    
3288
  msg = []
3289
  for rd in bdevs:
3290
    try:
3291
      rd.Close()
3292
    except errors.BlockDeviceError, err:
3293
      msg.append(str(err))
3294
  if msg:
3295
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3296
  else:
3297
    if instance_name:
3298
      _RemoveBlockDevLinks(instance_name, disks)
3299

    
3300

    
3301
def ValidateHVParams(hvname, hvparams):
3302
  """Validates the given hypervisor parameters.
3303

3304
  @type hvname: string
3305
  @param hvname: the hypervisor name
3306
  @type hvparams: dict
3307
  @param hvparams: the hypervisor parameters to be validated
3308
  @rtype: None
3309

3310
  """
3311
  try:
3312
    hv_type = hypervisor.GetHypervisor(hvname)
3313
    hv_type.ValidateParameters(hvparams)
3314
  except errors.HypervisorError, err:
3315
    _Fail(str(err), log=False)
3316

    
3317

    
3318
def _CheckOSPList(os_obj, parameters):
3319
  """Check whether a list of parameters is supported by the OS.
3320

3321
  @type os_obj: L{objects.OS}
3322
  @param os_obj: OS object to check
3323
  @type parameters: list
3324
  @param parameters: the list of parameters to check
3325

3326
  """
3327
  supported = [v[0] for v in os_obj.supported_parameters]
3328
  delta = frozenset(parameters).difference(supported)
3329
  if delta:
3330
    _Fail("The following parameters are not supported"
3331
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3332

    
3333

    
3334
def ValidateOS(required, osname, checks, osparams):
3335
  """Validate the given OS' parameters.
3336

3337
  @type required: boolean
3338
  @param required: whether absence of the OS should translate into
3339
      failure or not
3340
  @type osname: string
3341
  @param osname: the OS to be validated
3342
  @type checks: list
3343
  @param checks: list of the checks to run (currently only 'parameters')
3344
  @type osparams: dict
3345
  @param osparams: dictionary with OS parameters
3346
  @rtype: boolean
3347
  @return: True if the validation passed, or False if the OS was not
3348
      found and L{required} was false
3349

3350
  """
3351
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3352
    _Fail("Unknown checks required for OS %s: %s", osname,
3353
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3354

    
3355
  name_only = objects.OS.GetName(osname)
3356
  status, tbv = _TryOSFromDisk(name_only, None)
3357

    
3358
  if not status:
3359
    if required:
3360
      _Fail(tbv)
3361
    else:
3362
      return False
3363

    
3364
  if max(tbv.api_versions) < constants.OS_API_V20:
3365
    return True
3366

    
3367
  if constants.OS_VALIDATE_PARAMETERS in checks:
3368
    _CheckOSPList(tbv, osparams.keys())
3369

    
3370
  validate_env = OSCoreEnv(osname, tbv, osparams)
3371
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3372
                        cwd=tbv.path, reset_env=True)
3373
  if result.failed:
3374
    logging.error("os validate command '%s' returned error: %s output: %s",
3375
                  result.cmd, result.fail_reason, result.output)
3376
    _Fail("OS validation script failed (%s), output: %s",
3377
          result.fail_reason, result.output, log=False)
3378

    
3379
  return True
3380

    
3381

    
3382
def DemoteFromMC():
3383
  """Demotes the current node from master candidate role.
3384

3385
  """
3386
  # try to ensure we're not the master by mistake
3387
  master, myself = ssconf.GetMasterAndMyself()
3388
  if master == myself:
3389
    _Fail("ssconf status shows I'm the master node, will not demote")
3390

    
3391
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3392
  if not result.failed:
3393
    _Fail("The master daemon is running, will not demote")
3394

    
3395
  try:
3396
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3397
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3398
  except EnvironmentError, err:
3399
    if err.errno != errno.ENOENT:
3400
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3401

    
3402
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3403

    
3404

    
3405
def _GetX509Filenames(cryptodir, name):
3406
  """Returns the full paths for the private key and certificate.
3407

3408
  """
3409
  return (utils.PathJoin(cryptodir, name),
3410
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3411
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3412

    
3413

    
3414
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3415
  """Creates a new X509 certificate for SSL/TLS.
3416

3417
  @type validity: int
3418
  @param validity: Validity in seconds
3419
  @rtype: tuple; (string, string)
3420
  @return: Certificate name and public part
3421

3422
  """
3423
  (key_pem, cert_pem) = \
3424
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3425
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3426

    
3427
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3428
                              prefix="x509-%s-" % utils.TimestampForFilename())
3429
  try:
3430
    name = os.path.basename(cert_dir)
3431
    assert len(name) > 5
3432

    
3433
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3434

    
3435
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3436
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3437

    
3438
    # Never return private key as it shouldn't leave the node
3439
    return (name, cert_pem)
3440
  except Exception:
3441
    shutil.rmtree(cert_dir, ignore_errors=True)
3442
    raise
3443

    
3444

    
3445
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3446
  """Removes a X509 certificate.
3447

3448
  @type name: string
3449
  @param name: Certificate name
3450

3451
  """
3452
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3453

    
3454
  utils.RemoveFile(key_file)
3455
  utils.RemoveFile(cert_file)
3456

    
3457
  try:
3458
    os.rmdir(cert_dir)
3459
  except EnvironmentError, err:
3460
    _Fail("Cannot remove certificate directory '%s': %s",
3461
          cert_dir, err)
3462

    
3463

    
3464
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3465
  """Returns the command for the requested input/output.
3466

3467
  @type instance: L{objects.Instance}
3468
  @param instance: The instance object
3469
  @param mode: Import/export mode
3470
  @param ieio: Input/output type
3471
  @param ieargs: Input/output arguments
3472

3473
  """
3474
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3475

    
3476
  env = None
3477
  prefix = None
3478
  suffix = None
3479
  exp_size = None
3480

    
3481
  if ieio == constants.IEIO_FILE:
3482
    (filename, ) = ieargs
3483

    
3484
    if not utils.IsNormAbsPath(filename):
3485
      _Fail("Path '%s' is not normalized or absolute", filename)
3486

    
3487
    real_filename = os.path.realpath(filename)
3488
    directory = os.path.dirname(real_filename)
3489

    
3490
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3491
      _Fail("File '%s' is not under exports directory '%s': %s",
3492
            filename, pathutils.EXPORT_DIR, real_filename)
3493

    
3494
    # Create directory
3495
    utils.Makedirs(directory, mode=0750)
3496

    
3497
    quoted_filename = utils.ShellQuote(filename)
3498

    
3499
    if mode == constants.IEM_IMPORT:
3500
      suffix = "> %s" % quoted_filename
3501
    elif mode == constants.IEM_EXPORT:
3502
      suffix = "< %s" % quoted_filename
3503

    
3504
      # Retrieve file size
3505
      try:
3506
        st = os.stat(filename)
3507
      except EnvironmentError, err:
3508
        logging.error("Can't stat(2) %s: %s", filename, err)
3509
      else:
3510
        exp_size = utils.BytesToMebibyte(st.st_size)
3511

    
3512
  elif ieio == constants.IEIO_RAW_DISK:
3513
    (disk, ) = ieargs
3514

    
3515
    real_disk = _OpenRealBD(disk)
3516

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

    
3529
    elif mode == constants.IEM_EXPORT:
3530
      # the block size on the read dd is 1MiB to match our units
3531
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3532
                                   real_disk.dev_path,
3533
                                   str(1024 * 1024), # 1 MB
3534
                                   str(disk.size))
3535
      exp_size = disk.size
3536

    
3537
  elif ieio == constants.IEIO_SCRIPT:
3538
    (disk, disk_index, ) = ieargs
3539

    
3540
    assert isinstance(disk_index, (int, long))
3541

    
3542
    real_disk = _OpenRealBD(disk)
3543

    
3544
    inst_os = OSFromDisk(instance.os)
3545
    env = OSEnvironment(instance, inst_os)
3546

    
3547
    if mode == constants.IEM_IMPORT:
3548
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3549
      env["IMPORT_INDEX"] = str(disk_index)
3550
      script = inst_os.import_script
3551

    
3552
    elif mode == constants.IEM_EXPORT:
3553
      env["EXPORT_DEVICE"] = real_disk.dev_path
3554
      env["EXPORT_INDEX"] = str(disk_index)
3555
      script = inst_os.export_script
3556

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

    
3560
    if mode == constants.IEM_IMPORT:
3561
      suffix = "| %s" % script_cmd
3562

    
3563
    elif mode == constants.IEM_EXPORT:
3564
      prefix = "%s |" % script_cmd
3565

    
3566
    # Let script predict size
3567
    exp_size = constants.IE_CUSTOM_SIZE
3568

    
3569
  else:
3570
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3571

    
3572
  return (env, prefix, suffix, exp_size)
3573

    
3574

    
3575
def _CreateImportExportStatusDir(prefix):
3576
  """Creates status directory for import/export.
3577

3578
  """
3579
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3580
                          prefix=("%s-%s-" %
3581
                                  (prefix, utils.TimestampForFilename())))
3582

    
3583

    
3584
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3585
                            ieio, ieioargs):
3586
  """Starts an import or export daemon.
3587

3588
  @param mode: Import/output mode
3589
  @type opts: L{objects.ImportExportOptions}
3590
  @param opts: Daemon options
3591
  @type host: string
3592
  @param host: Remote host for export (None for import)
3593
  @type port: int
3594
  @param port: Remote port for export (None for import)
3595
  @type instance: L{objects.Instance}
3596
  @param instance: Instance object
3597
  @type component: string
3598
  @param component: which part of the instance is transferred now,
3599
      e.g. 'disk/0'
3600
  @param ieio: Input/output type
3601
  @param ieioargs: Input/output arguments
3602

3603
  """
3604
  if mode == constants.IEM_IMPORT:
3605
    prefix = "import"
3606

    
3607
    if not (host is None and port is None):
3608
      _Fail("Can not specify host or port on import")
3609

    
3610
  elif mode == constants.IEM_EXPORT:
3611
    prefix = "export"
3612

    
3613
    if host is None or port is None:
3614
      _Fail("Host and port must be specified for an export")
3615

    
3616
  else:
3617
    _Fail("Invalid mode %r", mode)
3618

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

    
3622
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3623
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3624

    
3625
  if opts.key_name is None:
3626
    # Use server.pem
3627
    key_path = pathutils.NODED_CERT_FILE
3628
    cert_path = pathutils.NODED_CERT_FILE
3629
    assert opts.ca_pem is None
3630
  else:
3631
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3632
                                                 opts.key_name)
3633
    assert opts.ca_pem is not None
3634

    
3635
  for i in [key_path, cert_path]:
3636
    if not os.path.exists(i):
3637
      _Fail("File '%s' does not exist" % i)
3638

    
3639
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3640
  try:
3641
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3642
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3643
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3644

    
3645
    if opts.ca_pem is None:
3646
      # Use server.pem
3647
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3648
    else:
3649
      ca = opts.ca_pem
3650

    
3651
    # Write CA file
3652
    utils.WriteFile(ca_file, data=ca, mode=0400)
3653

    
3654
    cmd = [
3655
      pathutils.IMPORT_EXPORT_DAEMON,
3656
      status_file, mode,
3657
      "--key=%s" % key_path,
3658
      "--cert=%s" % cert_path,
3659
      "--ca=%s" % ca_file,
3660
      ]
3661

    
3662
    if host:
3663
      cmd.append("--host=%s" % host)
3664

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

    
3668
    if opts.ipv6:
3669
      cmd.append("--ipv6")
3670
    else:
3671
      cmd.append("--ipv4")
3672

    
3673
    if opts.compress:
3674
      cmd.append("--compress=%s" % opts.compress)
3675

    
3676
    if opts.magic:
3677
      cmd.append("--magic=%s" % opts.magic)
3678

    
3679
    if exp_size is not None:
3680
      cmd.append("--expected-size=%s" % exp_size)
3681

    
3682
    if cmd_prefix:
3683
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3684

    
3685
    if cmd_suffix:
3686
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3687

    
3688
    if mode == constants.IEM_EXPORT:
3689
      # Retry connection a few times when connecting to remote peer
3690
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3691
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3692
    elif opts.connect_timeout is not None:
3693
      assert mode == constants.IEM_IMPORT
3694
      # Overall timeout for establishing connection while listening
3695
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3696

    
3697
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3698

    
3699
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3700
    # support for receiving a file descriptor for output
3701
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3702
                      output=logfile)
3703

    
3704
    # The import/export name is simply the status directory name
3705
    return os.path.basename(status_dir)
3706

    
3707
  except Exception:
3708
    shutil.rmtree(status_dir, ignore_errors=True)
3709
    raise
3710

    
3711

    
3712
def GetImportExportStatus(names):
3713
  """Returns import/export daemon status.
3714

3715
  @type names: sequence
3716
  @param names: List of names
3717
  @rtype: List of dicts
3718
  @return: Returns a list of the state of each named import/export or None if a
3719
           status couldn't be read
3720

3721
  """
3722
  result = []
3723

    
3724
  for name in names:
3725
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3726
                                 _IES_STATUS_FILE)
3727

    
3728
    try:
3729
      data = utils.ReadFile(status_file)
3730
    except EnvironmentError, err:
3731
      if err.errno != errno.ENOENT:
3732
        raise
3733
      data = None
3734

    
3735
    if not data:
3736
      result.append(None)
3737
      continue
3738

    
3739
    result.append(serializer.LoadJson(data))
3740

    
3741
  return result
3742

    
3743

    
3744
def AbortImportExport(name):
3745
  """Sends SIGTERM to a running import/export daemon.
3746

3747
  """
3748
  logging.info("Abort import/export %s", name)
3749

    
3750
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3751
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3752

    
3753
  if pid:
3754
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3755
                 name, pid)
3756
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3757

    
3758

    
3759
def CleanupImportExport(name):
3760
  """Cleanup after an import or export.
3761

3762
  If the import/export daemon is still running it's killed. Afterwards the
3763
  whole status directory is removed.
3764

3765
  """
3766
  logging.info("Finalizing import/export %s", name)
3767

    
3768
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3769

    
3770
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3771

    
3772
  if pid:
3773
    logging.info("Import/export %s is still running with PID %s",
3774
                 name, pid)
3775
    utils.KillProcess(pid, waitpid=False)
3776

    
3777
  shutil.rmtree(status_dir, ignore_errors=True)
3778

    
3779

    
3780
def _FindDisks(nodes_ip, disks):
3781
  """Sets the physical ID on disks and returns the block devices.
3782

3783
  """
3784
  # set the correct physical ID
3785
  my_name = netutils.Hostname.GetSysName()
3786
  for cf in disks:
3787
    cf.SetPhysicalID(my_name, nodes_ip)
3788

    
3789
  bdevs = []
3790

    
3791
  for cf in disks:
3792
    rd = _RecursiveFindBD(cf)
3793
    if rd is None:
3794
      _Fail("Can't find device %s", cf)
3795
    bdevs.append(rd)
3796
  return bdevs
3797

    
3798

    
3799
def DrbdDisconnectNet(nodes_ip, disks):
3800
  """Disconnects the network on a list of drbd devices.
3801

3802
  """
3803
  bdevs = _FindDisks(nodes_ip, disks)
3804

    
3805
  # disconnect disks
3806
  for rd in bdevs:
3807
    try:
3808
      rd.DisconnectNet()
3809
    except errors.BlockDeviceError, err:
3810
      _Fail("Can't change network configuration to standalone mode: %s",
3811
            err, exc=True)
3812

    
3813

    
3814
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3815
  """Attaches the network on a list of drbd devices.
3816

3817
  """
3818
  bdevs = _FindDisks(nodes_ip, disks)
3819

    
3820
  if multimaster:
3821
    for idx, rd in enumerate(bdevs):
3822
      try:
3823
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3824
      except EnvironmentError, err:
3825
        _Fail("Can't create symlink: %s", err)
3826
  # reconnect disks, switch to new master configuration and if
3827
  # needed primary mode
3828
  for rd in bdevs:
3829
    try:
3830
      rd.AttachNet(multimaster)
3831
    except errors.BlockDeviceError, err:
3832
      _Fail("Can't change network configuration: %s", err)
3833

    
3834
  # wait until the disks are connected; we need to retry the re-attach
3835
  # if the device becomes standalone, as this might happen if the one
3836
  # node disconnects and reconnects in a different mode before the
3837
  # other node reconnects; in this case, one or both of the nodes will
3838
  # decide it has wrong configuration and switch to standalone
3839

    
3840
  def _Attach():
3841
    all_connected = True
3842

    
3843
    for rd in bdevs:
3844
      stats = rd.GetProcStatus()
3845

    
3846
      all_connected = (all_connected and
3847
                       (stats.is_connected or stats.is_in_resync))
3848

    
3849
      if stats.is_standalone:
3850
        # peer had different config info and this node became
3851
        # standalone, even though this should not happen with the
3852
        # new staged way of changing disk configs
3853
        try:
3854
          rd.AttachNet(multimaster)
3855
        except errors.BlockDeviceError, err:
3856
          _Fail("Can't change network configuration: %s", err)
3857

    
3858
    if not all_connected:
3859
      raise utils.RetryAgain()
3860

    
3861
  try:
3862
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3863
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3864
  except utils.RetryTimeout:
3865
    _Fail("Timeout in disk reconnecting")
3866

    
3867
  if multimaster:
3868
    # change to primary mode
3869
    for rd in bdevs:
3870
      try:
3871
        rd.Open()
3872
      except errors.BlockDeviceError, err:
3873
        _Fail("Can't change to primary mode: %s", err)
3874

    
3875

    
3876
def DrbdWaitSync(nodes_ip, disks):
3877
  """Wait until DRBDs have synchronized.
3878

3879
  """
3880
  def _helper(rd):
3881
    stats = rd.GetProcStatus()
3882
    if not (stats.is_connected or stats.is_in_resync):
3883
      raise utils.RetryAgain()
3884
    return stats
3885

    
3886
  bdevs = _FindDisks(nodes_ip, disks)
3887

    
3888
  min_resync = 100
3889
  alldone = True
3890
  for rd in bdevs:
3891
    try:
3892
      # poll each second for 15 seconds
3893
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3894
    except utils.RetryTimeout:
3895
      stats = rd.GetProcStatus()
3896
      # last check
3897
      if not (stats.is_connected or stats.is_in_resync):
3898
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3899
    alldone = alldone and (not stats.is_in_resync)
3900
    if stats.sync_percent is not None:
3901
      min_resync = min(min_resync, stats.sync_percent)
3902

    
3903
  return (alldone, min_resync)
3904

    
3905

    
3906
def GetDrbdUsermodeHelper():
3907
  """Returns DRBD usermode helper currently configured.
3908

3909
  """
3910
  try:
3911
    return drbd.DRBD8.GetUsermodeHelper()
3912
  except errors.BlockDeviceError, err:
3913
    _Fail(str(err))
3914

    
3915

    
3916
def PowercycleNode(hypervisor_type, hvparams=None):
3917
  """Hard-powercycle the node.
3918

3919
  Because we need to return first, and schedule the powercycle in the
3920
  background, we won't be able to report failures nicely.
3921

3922
  """
3923
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3924
  try:
3925
    pid = os.fork()
3926
  except OSError:
3927
    # if we can't fork, we'll pretend that we're in the child process
3928
    pid = 0
3929
  if pid > 0:
3930
    return "Reboot scheduled in 5 seconds"
3931
  # ensure the child is running on ram
3932
  try:
3933
    utils.Mlockall()
3934
  except Exception: # pylint: disable=W0703
3935
    pass
3936
  time.sleep(5)
3937
  hyper.PowercycleNode(hvparams=hvparams)
3938

    
3939

    
3940
def _VerifyRestrictedCmdName(cmd):
3941
  """Verifies a restricted command name.
3942

3943
  @type cmd: string
3944
  @param cmd: Command name
3945
  @rtype: tuple; (boolean, string or None)
3946
  @return: The tuple's first element is the status; if C{False}, the second
3947
    element is an error message string, otherwise it's C{None}
3948

3949
  """
3950
  if not cmd.strip():
3951
    return (False, "Missing command name")
3952

    
3953
  if os.path.basename(cmd) != cmd:
3954
    return (False, "Invalid command name")
3955

    
3956
  if not constants.EXT_PLUGIN_MASK.match(cmd):
3957
    return (False, "Command name contains forbidden characters")
3958

    
3959
  return (True, None)
3960

    
3961

    
3962
def _CommonRestrictedCmdCheck(path, owner):
3963
  """Common checks for restricted command file system directories and files.
3964

3965
  @type path: string
3966
  @param path: Path to check
3967
  @param owner: C{None} or tuple containing UID and GID
3968
  @rtype: tuple; (boolean, string or C{os.stat} result)
3969
  @return: The tuple's first element is the status; if C{False}, the second
3970
    element is an error message string, otherwise it's the result of C{os.stat}
3971

3972
  """
3973
  if owner is None:
3974
    # Default to root as owner
3975
    owner = (0, 0)
3976

    
3977
  try:
3978
    st = os.stat(path)
3979
  except EnvironmentError, err:
3980
    return (False, "Can't stat(2) '%s': %s" % (path, err))
3981

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

    
3985
  if (st.st_uid, st.st_gid) != owner:
3986
    (owner_uid, owner_gid) = owner
3987
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
3988

    
3989
  return (True, st)
3990

    
3991

    
3992
def _VerifyRestrictedCmdDirectory(path, _owner=None):
3993
  """Verifies restricted command directory.
3994

3995
  @type path: string
3996
  @param path: Path to check
3997
  @rtype: tuple; (boolean, string or None)
3998
  @return: The tuple's first element is the status; if C{False}, the second
3999
    element is an error message string, otherwise it's C{None}
4000

4001
  """
4002
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
4003

    
4004
  if not status:
4005
    return (False, value)
4006

    
4007
  if not stat.S_ISDIR(value.st_mode):
4008
    return (False, "Path '%s' is not a directory" % path)
4009

    
4010
  return (True, None)
4011

    
4012

    
4013
def _VerifyRestrictedCmd(path, cmd, _owner=None):
4014
  """Verifies a whole restricted command and returns its executable filename.
4015

4016
  @type path: string
4017
  @param path: Directory containing restricted commands
4018
  @type cmd: string
4019
  @param cmd: Command name
4020
  @rtype: tuple; (boolean, string)
4021
  @return: The tuple's first element is the status; if C{False}, the second
4022
    element is an error message string, otherwise the second element is the
4023
    absolute path to the executable
4024

4025
  """
4026
  executable = utils.PathJoin(path, cmd)
4027

    
4028
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
4029

    
4030
  if not status:
4031
    return (False, msg)
4032

    
4033
  if not utils.IsExecutable(executable):
4034
    return (False, "access(2) thinks '%s' can't be executed" % executable)
4035

    
4036
  return (True, executable)
4037

    
4038

    
4039
def _PrepareRestrictedCmd(path, cmd,
4040
                          _verify_dir=_VerifyRestrictedCmdDirectory,
4041
                          _verify_name=_VerifyRestrictedCmdName,
4042
                          _verify_cmd=_VerifyRestrictedCmd):
4043
  """Performs a number of tests on a restricted command.
4044

4045
  @type path: string
4046
  @param path: Directory containing restricted commands
4047
  @type cmd: string
4048
  @param cmd: Command name
4049
  @return: Same as L{_VerifyRestrictedCmd}
4050

4051
  """
4052
  # Verify the directory first
4053
  (status, msg) = _verify_dir(path)
4054
  if status:
4055
    # Check command if everything was alright
4056
    (status, msg) = _verify_name(cmd)
4057

    
4058
  if not status:
4059
    return (False, msg)
4060

    
4061
  # Check actual executable
4062
  return _verify_cmd(path, cmd)
4063

    
4064

    
4065
def RunRestrictedCmd(cmd,
4066
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
4067
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
4068
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
4069
                     _sleep_fn=time.sleep,
4070
                     _prepare_fn=_PrepareRestrictedCmd,
4071
                     _runcmd_fn=utils.RunCmd,
4072
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
4073
  """Executes a restricted command after performing strict tests.
4074

4075
  @type cmd: string
4076
  @param cmd: Command name
4077
  @rtype: string
4078
  @return: Command output
4079
  @raise RPCFail: In case of an error
4080

4081
  """
4082
  logging.info("Preparing to run restricted command '%s'", cmd)
4083

    
4084
  if not _enabled:
4085
    _Fail("Restricted commands disabled at configure time")
4086

    
4087
  lock = None
4088
  try:
4089
    cmdresult = None
4090
    try:
4091
      lock = utils.FileLock.Open(_lock_file)
4092
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
4093

    
4094
      (status, value) = _prepare_fn(_path, cmd)
4095

    
4096
      if status:
4097
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
4098
                               postfork_fn=lambda _: lock.Unlock())
4099
      else:
4100
        logging.error(value)
4101
    except Exception: # pylint: disable=W0703
4102
      # Keep original error in log
4103
      logging.exception("Caught exception")
4104

    
4105
    if cmdresult is None:
4106
      logging.info("Sleeping for %0.1f seconds before returning",
4107
                   _RCMD_INVALID_DELAY)
4108
      _sleep_fn(_RCMD_INVALID_DELAY)
4109

    
4110
      # Do not include original error message in returned error
4111
      _Fail("Executing command '%s' failed" % cmd)
4112
    elif cmdresult.failed or cmdresult.fail_reason:
4113
      _Fail("Restricted command '%s' failed: %s; output: %s",
4114
            cmd, cmdresult.fail_reason, cmdresult.output)
4115
    else:
4116
      return cmdresult.output
4117
  finally:
4118
    if lock is not None:
4119
      # Release lock at last
4120
      lock.Close()
4121
      lock = None
4122

    
4123

    
4124
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
4125
  """Creates or removes the watcher pause file.
4126

4127
  @type until: None or number
4128
  @param until: Unix timestamp saying until when the watcher shouldn't run
4129

4130
  """
4131
  if until is None:
4132
    logging.info("Received request to no longer pause watcher")
4133
    utils.RemoveFile(_filename)
4134
  else:
4135
    logging.info("Received request to pause watcher until %s", until)
4136

    
4137
    if not ht.TNumber(until):
4138
      _Fail("Duration must be numeric")
4139

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

    
4142

    
4143
class HooksRunner(object):
4144
  """Hook runner.
4145

4146
  This class is instantiated on the node side (ganeti-noded) and not
4147
  on the master side.
4148

4149
  """
4150
  def __init__(self, hooks_base_dir=None):
4151
    """Constructor for hooks runner.
4152

4153
    @type hooks_base_dir: str or None
4154
    @param hooks_base_dir: if not None, this overrides the
4155
        L{pathutils.HOOKS_BASE_DIR} (useful for unittests)
4156

4157
    """
4158
    if hooks_base_dir is None:
4159
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
4160
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
4161
    # constant
4162
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
4163

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

4167
    """
4168
    assert len(node_list) == 1
4169
    node = node_list[0]
4170
    _, myself = ssconf.GetMasterAndMyself()
4171
    assert node == myself
4172

    
4173
    results = self.RunHooks(hpath, phase, env)
4174

    
4175
    # Return values in the form expected by HooksMaster
4176
    return {node: (None, False, results)}
4177

    
4178
  def RunHooks(self, hpath, phase, env):
4179
    """Run the scripts in the hooks directory.
4180

4181
    @type hpath: str
4182
    @param hpath: the path to the hooks directory which
4183
        holds the scripts
4184
    @type phase: str
4185
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
4186
        L{constants.HOOKS_PHASE_POST}
4187
    @type env: dict
4188
    @param env: dictionary with the environment for the hook
4189
    @rtype: list
4190
    @return: list of 3-element tuples:
4191
      - script path
4192
      - script result, either L{constants.HKR_SUCCESS} or
4193
        L{constants.HKR_FAIL}
4194
      - output of the script
4195

4196
    @raise errors.ProgrammerError: for invalid input
4197
        parameters
4198

4199
    """
4200
    if phase == constants.HOOKS_PHASE_PRE:
4201
      suffix = "pre"
4202
    elif phase == constants.HOOKS_PHASE_POST:
4203
      suffix = "post"
4204
    else:
4205
      _Fail("Unknown hooks phase '%s'", phase)
4206

    
4207
    subdir = "%s-%s.d" % (hpath, suffix)
4208
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
4209

    
4210
    results = []
4211

    
4212
    if not os.path.isdir(dir_name):
4213
      # for non-existing/non-dirs, we simply exit instead of logging a
4214
      # warning at every operation
4215
      return results
4216

    
4217
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
4218

    
4219
    for (relname, relstatus, runresult) in runparts_results:
4220
      if relstatus == constants.RUNPARTS_SKIP:
4221
        rrval = constants.HKR_SKIP
4222
        output = ""
4223
      elif relstatus == constants.RUNPARTS_ERR:
4224
        rrval = constants.HKR_FAIL
4225
        output = "Hook script execution error: %s" % runresult
4226
      elif relstatus == constants.RUNPARTS_RUN:
4227
        if runresult.failed:
4228
          rrval = constants.HKR_FAIL
4229
        else:
4230
          rrval = constants.HKR_SUCCESS
4231
        output = utils.SafeEncode(runresult.output.strip())
4232
      results.append(("%s/%s" % (subdir, relname), rrval, output))
4233

    
4234
    return results
4235

    
4236

    
4237
class IAllocatorRunner(object):
4238
  """IAllocator runner.
4239

4240
  This class is instantiated on the node side (ganeti-noded) and not on
4241
  the master side.
4242

4243
  """
4244
  @staticmethod
4245
  def Run(name, idata):
4246
    """Run an iallocator script.
4247

4248
    @type name: str
4249
    @param name: the iallocator script name
4250
    @type idata: str
4251
    @param idata: the allocator input data
4252

4253
    @rtype: tuple
4254
    @return: two element tuple of:
4255
       - status
4256
       - either error message or stdout of allocator (for success)
4257

4258
    """
4259
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
4260
                                  os.path.isfile)
4261
    if alloc_script is None:
4262
      _Fail("iallocator module '%s' not found in the search path", name)
4263

    
4264
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
4265
    try:
4266
      os.write(fd, idata)
4267
      os.close(fd)
4268
      result = utils.RunCmd([alloc_script, fin_name])
4269
      if result.failed:
4270
        _Fail("iallocator module '%s' failed: %s, output '%s'",
4271
              name, result.fail_reason, result.output)
4272
    finally:
4273
      os.unlink(fin_name)
4274

    
4275
    return result.stdout
4276

    
4277

    
4278
class DevCacheManager(object):
4279
  """Simple class for managing a cache of block device information.
4280

4281
  """
4282
  _DEV_PREFIX = "/dev/"
4283
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4284

    
4285
  @classmethod
4286
  def _ConvertPath(cls, dev_path):
4287
    """Converts a /dev/name path to the cache file name.
4288

4289
    This replaces slashes with underscores and strips the /dev
4290
    prefix. It then returns the full path to the cache file.
4291

4292
    @type dev_path: str
4293
    @param dev_path: the C{/dev/} path name
4294
    @rtype: str
4295
    @return: the converted path name
4296

4297
    """
4298
    if dev_path.startswith(cls._DEV_PREFIX):
4299
      dev_path = dev_path[len(cls._DEV_PREFIX):]
4300
    dev_path = dev_path.replace("/", "_")
4301
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4302
    return fpath
4303

    
4304
  @classmethod
4305
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4306
    """Updates the cache information for a given device.
4307

4308
    @type dev_path: str
4309
    @param dev_path: the pathname of the device
4310
    @type owner: str
4311
    @param owner: the owner (instance name) of the device
4312
    @type on_primary: bool
4313
    @param on_primary: whether this is the primary
4314
        node nor not
4315
    @type iv_name: str
4316
    @param iv_name: the instance-visible name of the
4317
        device, as in objects.Disk.iv_name
4318

4319
    @rtype: None
4320

4321
    """
4322
    if dev_path is None:
4323
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
4324
      return
4325
    fpath = cls._ConvertPath(dev_path)
4326
    if on_primary:
4327
      state = "primary"
4328
    else:
4329
      state = "secondary"
4330
    if iv_name is None:
4331
      iv_name = "not_visible"
4332
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4333
    try:
4334
      utils.WriteFile(fpath, data=fdata)
4335
    except EnvironmentError, err:
4336
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4337

    
4338
  @classmethod
4339
  def RemoveCache(cls, dev_path):
4340
    """Remove data for a dev_path.
4341

4342
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
4343
    path name and logging.
4344

4345
    @type dev_path: str
4346
    @param dev_path: the pathname of the device
4347

4348
    @rtype: None
4349

4350
    """
4351
    if dev_path is None:
4352
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
4353
      return
4354
    fpath = cls._ConvertPath(dev_path)
4355
    try:
4356
      utils.RemoveFile(fpath)
4357
    except EnvironmentError, err:
4358
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)