Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 0200a1af

History | View | Annotate | Download (133.5 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(instance, target, live):
1793
  """Migrates an instance to another node.
1794

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

1804
  """
1805
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1806

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

    
1812

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

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

1824
  """
1825
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1826

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

    
1833

    
1834
def GetMigrationStatus(instance):
1835
  """Get the migration status
1836

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

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

    
1852

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

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

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

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

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

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

    
1913
  device.SetInfo(info)
1914

    
1915
  return device.unique_id
1916

    
1917

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

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

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

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

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

    
1940

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

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

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

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

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

    
1970
  _WipeDevice(rdev.dev_path, offset, size)
1971

    
1972

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

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

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

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

    
1994
    result = rdev.PauseResumeSync(pause)
1995

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

    
2005
  return success
2006

    
2007

    
2008
def BlockdevRemove(disk):
2009
  """Remove a block device.
2010

2011
  @note: This is intended to be called recursively.
2012

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

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

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

    
2042
  if msgs:
2043
    _Fail("; ".join(msgs))
2044

    
2045

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

2049
  This is run on the primary and secondary nodes for an instance.
2050

2051
  @note: this function is called recursively.
2052

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

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

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

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

    
2094
  else:
2095
    result = True
2096
  return result
2097

    
2098

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

2102
  This is a wrapper over _RecursiveAssembleBD.
2103

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

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

    
2121
  return result
2122

    
2123

    
2124
def BlockdevShutdown(disk):
2125
  """Shut down a block device.
2126

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

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

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

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

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

    
2158
  if msgs:
2159
    _Fail("; ".join(msgs))
2160

    
2161

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

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

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

    
2180

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

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

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

    
2209

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

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

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

    
2227
    stats.append(rbd.CombinedSyncStatus())
2228

    
2229
  return stats
2230

    
2231

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

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

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

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

    
2258
  assert len(disks) == len(result)
2259

    
2260
  return result
2261

    
2262

    
2263
def _RecursiveFindBD(disk):
2264
  """Check if a device is activated.
2265

2266
  If so, return information about the real device.
2267

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

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

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

    
2280
  return bdev.FindDevice(disk, children)
2281

    
2282

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

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

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

    
2294
  real_disk.Open()
2295

    
2296
  return real_disk
2297

    
2298

    
2299
def BlockdevFind(disk):
2300
  """Check if a device is activated.
2301

2302
  If it is, return information about the real device.
2303

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

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

    
2316
  if rbd is None:
2317
    return None
2318

    
2319
  return rbd.GetSyncStatus()
2320

    
2321

    
2322
def BlockdevGetdimensions(disks):
2323
  """Computes the size of the given disks.
2324

2325
  If a disk is not found, returns None instead.
2326

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

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

    
2348

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

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

2362
  """
2363
  real_disk = _OpenRealBD(disk)
2364

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

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

    
2379
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2380
                                                   constants.SSH_LOGIN_USER,
2381
                                                   destcmd)
2382

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

    
2386
  result = utils.RunCmd(["bash", "-c", command])
2387

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

    
2392

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

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

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

2415
  """
2416
  file_name = vcluster.LocalizeVirtualPath(file_name)
2417

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

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

    
2425
  raw_data = _Decompress(data)
2426

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

    
2430
  getents = runtime.GetEnts()
2431
  uid = getents.LookupUser(uid)
2432
  gid = getents.LookupGroup(gid)
2433

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

    
2438

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

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

2447
  @return: stdout
2448
  @raise RPCFail: If execution fails for some reason
2449

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

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

    
2457
  return result.stdout
2458

    
2459

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

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

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

2472
  """
2473
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2474

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

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

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

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

    
2497
  return True, api_versions
2498

    
2499

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

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

2519
  """
2520
  if top_dirs is None:
2521
    top_dirs = pathutils.OS_SEARCH_PATH
2522

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

    
2545
  return result
2546

    
2547

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2647

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

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

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

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

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

    
2669
  if not status:
2670
    _Fail(payload)
2671

    
2672
  return payload
2673

    
2674

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

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

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

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

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

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

    
2717
  return result
2718

    
2719

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

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

2734
  """
2735
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2736

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

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

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

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

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

    
2782
  return result
2783

    
2784

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

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

2803
  """
2804
  if top_dirs is None:
2805
    top_dirs = pathutils.ES_SEARCH_PATH
2806

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

    
2827
  return result
2828

    
2829

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

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

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

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

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

    
2860

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

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

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

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

    
2890

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

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

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

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

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

    
2916

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

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

2927
  @rtype: None
2928

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

    
2933
  config = objects.SerializableConfigParser()
2934

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

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

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

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

    
2982
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2983

    
2984
  # New-style hypervisor/backend parameters
2985

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

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

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

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

    
3004

    
3005
def ExportInfo(dest):
3006
  """Get export configuration information.
3007

3008
  @type dest: str
3009
  @param dest: directory containing the export
3010

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

3015
  """
3016
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
3017

    
3018
  config = objects.SerializableConfigParser()
3019
  config.read(cff)
3020

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

    
3025
  return config.Dumps()
3026

    
3027

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

3031
  @rtype: list
3032
  @return: list of the exports
3033

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

    
3040

    
3041
def RemoveExport(export):
3042
  """Remove an existing export from the node.
3043

3044
  @type export: str
3045
  @param export: the name of the export to remove
3046
  @rtype: None
3047

3048
  """
3049
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
3050

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

    
3056

    
3057
def BlockdevRename(devlist):
3058
  """Rename a list of block devices.
3059

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

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

    
3097

    
3098
def _TransformFileStorageDir(fs_dir):
3099
  """Checks whether given file_storage_dir is valid.
3100

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

3105
  @type fs_dir: str
3106
  @param fs_dir: the path to check
3107

3108
  @return: the normalized path if valid, None otherwise
3109

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

    
3115
  bdev.CheckFileStoragePath(fs_dir)
3116

    
3117
  return os.path.normpath(fs_dir)
3118

    
3119

    
3120
def CreateFileStorageDir(file_storage_dir):
3121
  """Create file storage directory.
3122

3123
  @type file_storage_dir: str
3124
  @param file_storage_dir: directory to create
3125

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

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

    
3143

    
3144
def RemoveFileStorageDir(file_storage_dir):
3145
  """Remove file storage directory.
3146

3147
  Remove it only if it's empty. If not log an error and return.
3148

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

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

    
3168

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

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

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

    
3198

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

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

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

    
3212

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

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

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

3226
  """
3227
  file_name = vcluster.LocalizeVirtualPath(file_name)
3228

    
3229
  _EnsureJobQueueFile(file_name)
3230
  getents = runtime.GetEnts()
3231

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

    
3236

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

3240
  This is just a wrapper over os.rename with proper checking.
3241

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

3249
  """
3250
  old = vcluster.LocalizeVirtualPath(old)
3251
  new = vcluster.LocalizeVirtualPath(new)
3252

    
3253
  _EnsureJobQueueFile(old)
3254
  _EnsureJobQueueFile(new)
3255

    
3256
  getents = runtime.GetEnts()
3257

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

    
3261

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

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

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

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

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

    
3298

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

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

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

    
3315

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

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

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

    
3331

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

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

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

    
3353
  name_only = objects.OS.GetName(osname)
3354
  status, tbv = _TryOSFromDisk(name_only, None)
3355

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

    
3362
  if max(tbv.api_versions) < constants.OS_API_V20:
3363
    return True
3364

    
3365
  if constants.OS_VALIDATE_PARAMETERS in checks:
3366
    _CheckOSPList(tbv, osparams.keys())
3367

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

    
3377
  return True
3378

    
3379

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

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

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

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

    
3400
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3401

    
3402

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

3406
  """
3407
  return (utils.PathJoin(cryptodir, name),
3408
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3409
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3410

    
3411

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

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

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

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

    
3431
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3432

    
3433
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3434
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3435

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

    
3442

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

3446
  @type name: string
3447
  @param name: Certificate name
3448

3449
  """
3450
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3451

    
3452
  utils.RemoveFile(key_file)
3453
  utils.RemoveFile(cert_file)
3454

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

    
3461

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

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

3471
  """
3472
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3473

    
3474
  env = None
3475
  prefix = None
3476
  suffix = None
3477
  exp_size = None
3478

    
3479
  if ieio == constants.IEIO_FILE:
3480
    (filename, ) = ieargs
3481

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

    
3485
    real_filename = os.path.realpath(filename)
3486
    directory = os.path.dirname(real_filename)
3487

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

    
3492
    # Create directory
3493
    utils.Makedirs(directory, mode=0750)
3494

    
3495
    quoted_filename = utils.ShellQuote(filename)
3496

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

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

    
3510
  elif ieio == constants.IEIO_RAW_DISK:
3511
    (disk, ) = ieargs
3512

    
3513
    real_disk = _OpenRealBD(disk)
3514

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

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

    
3535
  elif ieio == constants.IEIO_SCRIPT:
3536
    (disk, disk_index, ) = ieargs
3537

    
3538
    assert isinstance(disk_index, (int, long))
3539

    
3540
    real_disk = _OpenRealBD(disk)
3541

    
3542
    inst_os = OSFromDisk(instance.os)
3543
    env = OSEnvironment(instance, inst_os)
3544

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

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

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

    
3558
    if mode == constants.IEM_IMPORT:
3559
      suffix = "| %s" % script_cmd
3560

    
3561
    elif mode == constants.IEM_EXPORT:
3562
      prefix = "%s |" % script_cmd
3563

    
3564
    # Let script predict size
3565
    exp_size = constants.IE_CUSTOM_SIZE
3566

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

    
3570
  return (env, prefix, suffix, exp_size)
3571

    
3572

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

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

    
3581

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

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

3601
  """
3602
  if mode == constants.IEM_IMPORT:
3603
    prefix = "import"
3604

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

    
3608
  elif mode == constants.IEM_EXPORT:
3609
    prefix = "export"
3610

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

    
3614
  else:
3615
    _Fail("Invalid mode %r", mode)
3616

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

    
3620
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3621
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3622

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

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

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

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

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

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

    
3660
    if host:
3661
      cmd.append("--host=%s" % host)
3662

    
3663
    if port:
3664
      cmd.append("--port=%s" % port)
3665

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

    
3671
    if opts.compress:
3672
      cmd.append("--compress=%s" % opts.compress)
3673

    
3674
    if opts.magic:
3675
      cmd.append("--magic=%s" % opts.magic)
3676

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

    
3680
    if cmd_prefix:
3681
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3682

    
3683
    if cmd_suffix:
3684
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3685

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

    
3695
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3696

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

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

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

    
3709

    
3710
def GetImportExportStatus(names):
3711
  """Returns import/export daemon status.
3712

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

3719
  """
3720
  result = []
3721

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

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

    
3733
    if not data:
3734
      result.append(None)
3735
      continue
3736

    
3737
    result.append(serializer.LoadJson(data))
3738

    
3739
  return result
3740

    
3741

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

3745
  """
3746
  logging.info("Abort import/export %s", name)
3747

    
3748
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3749
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3750

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

    
3756

    
3757
def CleanupImportExport(name):
3758
  """Cleanup after an import or export.
3759

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

3763
  """
3764
  logging.info("Finalizing import/export %s", name)
3765

    
3766
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3767

    
3768
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3769

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

    
3775
  shutil.rmtree(status_dir, ignore_errors=True)
3776

    
3777

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

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

    
3787
  bdevs = []
3788

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

    
3796

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

3800
  """
3801
  bdevs = _FindDisks(nodes_ip, disks)
3802

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

    
3811

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

3815
  """
3816
  bdevs = _FindDisks(nodes_ip, disks)
3817

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

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

    
3838
  def _Attach():
3839
    all_connected = True
3840

    
3841
    for rd in bdevs:
3842
      stats = rd.GetProcStatus()
3843

    
3844
      all_connected = (all_connected and
3845
                       (stats.is_connected or stats.is_in_resync))
3846

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

    
3856
    if not all_connected:
3857
      raise utils.RetryAgain()
3858

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

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

    
3873

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

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

    
3884
  bdevs = _FindDisks(nodes_ip, disks)
3885

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

    
3901
  return (alldone, min_resync)
3902

    
3903

    
3904
def GetDrbdUsermodeHelper():
3905
  """Returns DRBD usermode helper currently configured.
3906

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

    
3913

    
3914
def PowercycleNode(hypervisor_type):
3915
  """Hard-powercycle the node.
3916

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

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

    
3937

    
3938
def _VerifyRestrictedCmdName(cmd):
3939
  """Verifies a restricted command name.
3940

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

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

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

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

    
3957
  return (True, None)
3958

    
3959

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

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

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

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

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

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

    
3987
  return (True, st)
3988

    
3989

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

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

3999
  """
4000
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
4001

    
4002
  if not status:
4003
    return (False, value)
4004

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

    
4008
  return (True, None)
4009

    
4010

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

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

4023
  """
4024
  executable = utils.PathJoin(path, cmd)
4025

    
4026
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
4027

    
4028
  if not status:
4029
    return (False, msg)
4030

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

    
4034
  return (True, executable)
4035

    
4036

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

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

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

    
4056
  if not status:
4057
    return (False, msg)
4058

    
4059
  # Check actual executable
4060
  return _verify_cmd(path, cmd)
4061

    
4062

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

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

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

    
4082
  if not _enabled:
4083
    _Fail("Restricted commands disabled at configure time")
4084

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

    
4092
      (status, value) = _prepare_fn(_path, cmd)
4093

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

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

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

    
4121

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

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

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

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

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

    
4140

    
4141
class HooksRunner(object):
4142
  """Hook runner.
4143

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

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

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

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

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

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

    
4171
    results = self.RunHooks(hpath, phase, env)
4172

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

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

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

4194
    @raise errors.ProgrammerError: for invalid input
4195
        parameters
4196

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

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

    
4208
    results = []
4209

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

    
4215
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
4216

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

    
4232
    return results
4233

    
4234

    
4235
class IAllocatorRunner(object):
4236
  """IAllocator runner.
4237

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

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

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

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

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

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

    
4273
    return result.stdout
4274

    
4275

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

4279
  """
4280
  _DEV_PREFIX = "/dev/"
4281
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4282

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

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

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

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

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

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

4317
    @rtype: None
4318

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

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

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

4343
    @type dev_path: str
4344
    @param dev_path: the pathname of the device
4345

4346
    @rtype: None
4347

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