Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 0f0f6d7d

History | View | Annotate | Download (133.8 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
    "type": constants.ST_LVM_VG,
590
    "name": name,
591
    "vg_free": vg_free,
592
    "vg_size": vg_size,
593
    }
594

    
595

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

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

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

    
620

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

624
  The information returned depends on the hypervisor. Common items:
625

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

633
  @type hvparams: dict of string
634
  @param hvparams: the hypervisor's hvparams
635

636
  """
637
  return get_hv_fn(name).GetNodeInfo(hvparams=hvparams)
638

    
639

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

643
  See C{_GetHvInfo} for information on the output.
644

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

648
  """
649
  if hv_specs is None:
650
    return None
651

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

    
657

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

661
  @rtype: None or dict
662

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

    
669

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

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

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

    
695

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

    
707

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

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

    
733

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

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

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

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

    
750

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

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

767
  """
768
  if not vm_capable:
769
    return
770

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

    
781

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

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

796
  """
797
  if not vm_capable:
798
    return
799

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

    
809

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

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

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

    
833

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

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

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

    
854

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

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

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

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

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

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

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

    
893
  _VerifyHypervisors(what, vm_capable, result, all_hvparams)
894
  _VerifyHvparams(what, vm_capable, result)
895

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

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

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

    
912
    # Use a random order
913
    random.shuffle(nodes)
914

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

    
922
    result[constants.NV_NODELIST] = val
923

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

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

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

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

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

    
986
  _VerifyInstanceList(what, vm_capable, result, all_hvparams)
987

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

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

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

    
1007
  _VerifyNodeInfo(what, vm_capable, result, all_hvparams)
1008

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

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

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

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

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

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

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

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

    
1062
  return result
1063

    
1064

    
1065
def GetBlockDevSizes(devices):
1066
  """Return the size of the given block devices
1067

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

1075
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
1076

1077
  """
1078
  DEV_PREFIX = "/dev/"
1079
  blockdevs = {}
1080

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

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

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

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

    
1102

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

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

1114
        {'xenvg/test1': ('20.06', True, True)}
1115

1116
      in case of errors, a string is returned with the error
1117
      details.
1118

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

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

    
1146
  return lvs
1147

    
1148

    
1149
def ListVolumeGroups():
1150
  """List the volume groups and their size.
1151

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

1156
  """
1157
  return utils.ListVolumeGroups()
1158

    
1159

    
1160
def NodeVolumes():
1161
  """List all volumes on this node.
1162

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

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

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

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

    
1186
  def parse_dev(dev):
1187
    return dev.split("(")[0]
1188

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

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

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

    
1205

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

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

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

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

    
1221

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

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

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

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

    
1250

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

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

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

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

    
1277

    
1278
def GetInstanceInfo(instance, hname, hvparams=None):
1279
  """Gives back the information about an instance as a dictionary.
1280

1281
  @type instance: string
1282
  @param instance: the instance name
1283
  @type hname: string
1284
  @param hname: the hypervisor type of the instance
1285
  @type hvparams: dict of strings
1286
  @param hvparams: the instance's hvparams
1287

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

1295
  """
1296
  output = {}
1297

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

    
1306
  return output
1307

    
1308

    
1309
def GetInstanceMigratable(instance):
1310
  """Computes whether an instance can be migrated.
1311

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

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

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

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

    
1332

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

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

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

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

1352
  """
1353
  output = {}
1354

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

    
1376
  return output
1377

    
1378

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

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

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

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

    
1406

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

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

1418
  """
1419
  inst_os = OSFromDisk(instance.os)
1420

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

    
1425
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1426

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

    
1438

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

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

1451
  """
1452
  inst_os = OSFromDisk(instance.os)
1453

    
1454
  rename_env = OSEnvironment(instance, inst_os, debug)
1455
  rename_env["OLD_INSTANCE_NAME"] = old_name
1456

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

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

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

    
1471

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

1475
  """
1476
  if _dir is None:
1477
    _dir = pathutils.DISK_LINKS_DIR
1478

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

    
1483

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

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

1490

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

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

    
1509
  return link_name
1510

    
1511

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

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

    
1524

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

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

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

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

    
1550
    block_devices.append((disk, link_name))
1551

    
1552
  return block_devices
1553

    
1554

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

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

1568
  """
1569
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1570
                                                   instance.hvparams)
1571

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

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

    
1588

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

1592
  @note: this functions uses polling with a hardcoded timeout.
1593

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

1604
  """
1605
  hv_name = instance.hypervisor
1606
  hyper = hypervisor.GetHypervisor(hv_name)
1607
  iname = instance.name
1608

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

    
1613
  class _TryShutdown:
1614
    def __init__(self):
1615
      self.tried_once = False
1616

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

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

    
1631
        _Fail("Failed to stop instance %s: %s", iname, err)
1632

    
1633
      self.tried_once = True
1634

    
1635
      raise utils.RetryAgain()
1636

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

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

    
1651
    time.sleep(1)
1652

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

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

    
1661
  _RemoveBlockDevLinks(iname, instance.disks)
1662

    
1663

    
1664
def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1665
  """Reboot an instance.
1666

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

1686
  """
1687
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1688
                                                   instance.hvparams)
1689

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

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

    
1710

    
1711
def InstanceBalloonMemory(instance, memory):
1712
  """Resize an instance's memory.
1713

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

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

    
1731

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

1735
  @type instance: L{objects.Instance}
1736
  @param instance: the instance definition
1737

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

    
1746

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

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

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

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

    
1775

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

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

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

    
1793

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

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

1808
  """
1809
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1810

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

    
1816

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

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

1828
  """
1829
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1830

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

    
1837

    
1838
def GetMigrationStatus(instance):
1839
  """Get the migration status
1840

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

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

    
1856

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

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

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

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

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

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

    
1917
  device.SetInfo(info)
1918

    
1919
  return device.unique_id
1920

    
1921

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

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

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

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

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

    
1944

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

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

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

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

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

    
1974
  _WipeDevice(rdev.dev_path, offset, size)
1975

    
1976

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

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

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

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

    
1998
    result = rdev.PauseResumeSync(pause)
1999

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

    
2009
  return success
2010

    
2011

    
2012
def BlockdevRemove(disk):
2013
  """Remove a block device.
2014

2015
  @note: This is intended to be called recursively.
2016

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

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

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

    
2046
  if msgs:
2047
    _Fail("; ".join(msgs))
2048

    
2049

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

2053
  This is run on the primary and secondary nodes for an instance.
2054

2055
  @note: this function is called recursively.
2056

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

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

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

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

    
2098
  else:
2099
    result = True
2100
  return result
2101

    
2102

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

2106
  This is a wrapper over _RecursiveAssembleBD.
2107

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

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

    
2125
  return result
2126

    
2127

    
2128
def BlockdevShutdown(disk):
2129
  """Shut down a block device.
2130

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

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

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

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

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

    
2162
  if msgs:
2163
    _Fail("; ".join(msgs))
2164

    
2165

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

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

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

    
2184

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

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

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

    
2213

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

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

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

    
2231
    stats.append(rbd.CombinedSyncStatus())
2232

    
2233
  return stats
2234

    
2235

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

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

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

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

    
2262
  assert len(disks) == len(result)
2263

    
2264
  return result
2265

    
2266

    
2267
def _RecursiveFindBD(disk):
2268
  """Check if a device is activated.
2269

2270
  If so, return information about the real device.
2271

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

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

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

    
2284
  return bdev.FindDevice(disk, children)
2285

    
2286

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

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

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

    
2298
  real_disk.Open()
2299

    
2300
  return real_disk
2301

    
2302

    
2303
def BlockdevFind(disk):
2304
  """Check if a device is activated.
2305

2306
  If it is, return information about the real device.
2307

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

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

    
2320
  if rbd is None:
2321
    return None
2322

    
2323
  return rbd.GetSyncStatus()
2324

    
2325

    
2326
def BlockdevGetdimensions(disks):
2327
  """Computes the size of the given disks.
2328

2329
  If a disk is not found, returns None instead.
2330

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

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

    
2352

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

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

2366
  """
2367
  real_disk = _OpenRealBD(disk)
2368

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

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

    
2383
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2384
                                                   constants.SSH_LOGIN_USER,
2385
                                                   destcmd)
2386

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

    
2390
  result = utils.RunCmd(["bash", "-c", command])
2391

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

    
2396

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

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

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

2419
  """
2420
  file_name = vcluster.LocalizeVirtualPath(file_name)
2421

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

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

    
2429
  raw_data = _Decompress(data)
2430

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

    
2434
  getents = runtime.GetEnts()
2435
  uid = getents.LookupUser(uid)
2436
  gid = getents.LookupGroup(gid)
2437

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

    
2442

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

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

2451
  @return: stdout
2452
  @raise RPCFail: If execution fails for some reason
2453

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

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

    
2461
  return result.stdout
2462

    
2463

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

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

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

2476
  """
2477
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2478

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

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

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

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

    
2501
  return True, api_versions
2502

    
2503

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

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

2523
  """
2524
  if top_dirs is None:
2525
    top_dirs = pathutils.OS_SEARCH_PATH
2526

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

    
2549
  return result
2550

    
2551

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2651

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

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

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

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

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

    
2673
  if not status:
2674
    _Fail(payload)
2675

    
2676
  return payload
2677

    
2678

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

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

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

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

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

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

    
2721
  return result
2722

    
2723

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

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

2738
  """
2739
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2740

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

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

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

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

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

    
2786
  return result
2787

    
2788

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

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

2807
  """
2808
  if top_dirs is None:
2809
    top_dirs = pathutils.ES_SEARCH_PATH
2810

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

    
2831
  return result
2832

    
2833

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

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

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

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

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

    
2864

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

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

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

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

    
2894

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

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

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

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

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

    
2920

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

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

2931
  @rtype: None
2932

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

    
2937
  config = objects.SerializableConfigParser()
2938

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

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

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

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

    
2986
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2987

    
2988
  # New-style hypervisor/backend parameters
2989

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

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

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

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

    
3008

    
3009
def ExportInfo(dest):
3010
  """Get export configuration information.
3011

3012
  @type dest: str
3013
  @param dest: directory containing the export
3014

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

3019
  """
3020
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
3021

    
3022
  config = objects.SerializableConfigParser()
3023
  config.read(cff)
3024

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

    
3029
  return config.Dumps()
3030

    
3031

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

3035
  @rtype: list
3036
  @return: list of the exports
3037

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

    
3044

    
3045
def RemoveExport(export):
3046
  """Remove an existing export from the node.
3047

3048
  @type export: str
3049
  @param export: the name of the export to remove
3050
  @rtype: None
3051

3052
  """
3053
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
3054

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

    
3060

    
3061
def BlockdevRename(devlist):
3062
  """Rename a list of block devices.
3063

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

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

    
3101

    
3102
def _TransformFileStorageDir(fs_dir):
3103
  """Checks whether given file_storage_dir is valid.
3104

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

3109
  @type fs_dir: str
3110
  @param fs_dir: the path to check
3111

3112
  @return: the normalized path if valid, None otherwise
3113

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

    
3119
  bdev.CheckFileStoragePath(fs_dir)
3120

    
3121
  return os.path.normpath(fs_dir)
3122

    
3123

    
3124
def CreateFileStorageDir(file_storage_dir):
3125
  """Create file storage directory.
3126

3127
  @type file_storage_dir: str
3128
  @param file_storage_dir: directory to create
3129

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

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

    
3147

    
3148
def RemoveFileStorageDir(file_storage_dir):
3149
  """Remove file storage directory.
3150

3151
  Remove it only if it's empty. If not log an error and return.
3152

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

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

    
3172

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

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

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

    
3202

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

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

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

    
3216

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

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

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

3230
  """
3231
  file_name = vcluster.LocalizeVirtualPath(file_name)
3232

    
3233
  _EnsureJobQueueFile(file_name)
3234
  getents = runtime.GetEnts()
3235

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

    
3240

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

3244
  This is just a wrapper over os.rename with proper checking.
3245

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

3253
  """
3254
  old = vcluster.LocalizeVirtualPath(old)
3255
  new = vcluster.LocalizeVirtualPath(new)
3256

    
3257
  _EnsureJobQueueFile(old)
3258
  _EnsureJobQueueFile(new)
3259

    
3260
  getents = runtime.GetEnts()
3261

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

    
3265

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

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

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

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

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

    
3302

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

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

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

    
3319

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

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

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

    
3335

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

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

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

    
3357
  name_only = objects.OS.GetName(osname)
3358
  status, tbv = _TryOSFromDisk(name_only, None)
3359

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

    
3366
  if max(tbv.api_versions) < constants.OS_API_V20:
3367
    return True
3368

    
3369
  if constants.OS_VALIDATE_PARAMETERS in checks:
3370
    _CheckOSPList(tbv, osparams.keys())
3371

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

    
3381
  return True
3382

    
3383

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

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

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

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

    
3404
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3405

    
3406

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

3410
  """
3411
  return (utils.PathJoin(cryptodir, name),
3412
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3413
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3414

    
3415

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

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

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

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

    
3435
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3436

    
3437
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3438
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3439

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

    
3446

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

3450
  @type name: string
3451
  @param name: Certificate name
3452

3453
  """
3454
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3455

    
3456
  utils.RemoveFile(key_file)
3457
  utils.RemoveFile(cert_file)
3458

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

    
3465

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

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

3475
  """
3476
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3477

    
3478
  env = None
3479
  prefix = None
3480
  suffix = None
3481
  exp_size = None
3482

    
3483
  if ieio == constants.IEIO_FILE:
3484
    (filename, ) = ieargs
3485

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

    
3489
    real_filename = os.path.realpath(filename)
3490
    directory = os.path.dirname(real_filename)
3491

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

    
3496
    # Create directory
3497
    utils.Makedirs(directory, mode=0750)
3498

    
3499
    quoted_filename = utils.ShellQuote(filename)
3500

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

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

    
3514
  elif ieio == constants.IEIO_RAW_DISK:
3515
    (disk, ) = ieargs
3516

    
3517
    real_disk = _OpenRealBD(disk)
3518

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

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

    
3539
  elif ieio == constants.IEIO_SCRIPT:
3540
    (disk, disk_index, ) = ieargs
3541

    
3542
    assert isinstance(disk_index, (int, long))
3543

    
3544
    real_disk = _OpenRealBD(disk)
3545

    
3546
    inst_os = OSFromDisk(instance.os)
3547
    env = OSEnvironment(instance, inst_os)
3548

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

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

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

    
3562
    if mode == constants.IEM_IMPORT:
3563
      suffix = "| %s" % script_cmd
3564

    
3565
    elif mode == constants.IEM_EXPORT:
3566
      prefix = "%s |" % script_cmd
3567

    
3568
    # Let script predict size
3569
    exp_size = constants.IE_CUSTOM_SIZE
3570

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

    
3574
  return (env, prefix, suffix, exp_size)
3575

    
3576

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

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

    
3585

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

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

3605
  """
3606
  if mode == constants.IEM_IMPORT:
3607
    prefix = "import"
3608

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

    
3612
  elif mode == constants.IEM_EXPORT:
3613
    prefix = "export"
3614

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

    
3618
  else:
3619
    _Fail("Invalid mode %r", mode)
3620

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

    
3624
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3625
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3626

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

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

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

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

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

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

    
3664
    if host:
3665
      cmd.append("--host=%s" % host)
3666

    
3667
    if port:
3668
      cmd.append("--port=%s" % port)
3669

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

    
3675
    if opts.compress:
3676
      cmd.append("--compress=%s" % opts.compress)
3677

    
3678
    if opts.magic:
3679
      cmd.append("--magic=%s" % opts.magic)
3680

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

    
3684
    if cmd_prefix:
3685
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3686

    
3687
    if cmd_suffix:
3688
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3689

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

    
3699
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3700

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

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

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

    
3713

    
3714
def GetImportExportStatus(names):
3715
  """Returns import/export daemon status.
3716

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

3723
  """
3724
  result = []
3725

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

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

    
3737
    if not data:
3738
      result.append(None)
3739
      continue
3740

    
3741
    result.append(serializer.LoadJson(data))
3742

    
3743
  return result
3744

    
3745

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

3749
  """
3750
  logging.info("Abort import/export %s", name)
3751

    
3752
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3753
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3754

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

    
3760

    
3761
def CleanupImportExport(name):
3762
  """Cleanup after an import or export.
3763

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

3767
  """
3768
  logging.info("Finalizing import/export %s", name)
3769

    
3770
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3771

    
3772
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3773

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

    
3779
  shutil.rmtree(status_dir, ignore_errors=True)
3780

    
3781

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

3785
  """
3786
  # set the correct physical ID
3787
  for cf in disks:
3788
    cf.SetPhysicalID(target_node_uuid, nodes_ip)
3789

    
3790
  bdevs = []
3791

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

    
3799

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

3803
  """
3804
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3805

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

    
3814

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

3819
  """
3820
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3821

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

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

    
3842
  def _Attach():
3843
    all_connected = True
3844

    
3845
    for rd in bdevs:
3846
      stats = rd.GetProcStatus()
3847

    
3848
      all_connected = (all_connected and
3849
                       (stats.is_connected or stats.is_in_resync))
3850

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

    
3860
    if not all_connected:
3861
      raise utils.RetryAgain()
3862

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

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

    
3877

    
3878
def DrbdWaitSync(target_node_uuid, nodes_ip, disks):
3879
  """Wait until DRBDs have synchronized.
3880

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

    
3888
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3889

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

    
3905
  return (alldone, min_resync)
3906

    
3907

    
3908
def GetDrbdUsermodeHelper():
3909
  """Returns DRBD usermode helper currently configured.
3910

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

    
3917

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

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

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

    
3941

    
3942
def _VerifyRestrictedCmdName(cmd):
3943
  """Verifies a restricted command name.
3944

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

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

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

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

    
3961
  return (True, None)
3962

    
3963

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

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

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

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

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

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

    
3991
  return (True, st)
3992

    
3993

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

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

4003
  """
4004
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
4005

    
4006
  if not status:
4007
    return (False, value)
4008

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

    
4012
  return (True, None)
4013

    
4014

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

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

4027
  """
4028
  executable = utils.PathJoin(path, cmd)
4029

    
4030
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
4031

    
4032
  if not status:
4033
    return (False, msg)
4034

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

    
4038
  return (True, executable)
4039

    
4040

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

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

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

    
4060
  if not status:
4061
    return (False, msg)
4062

    
4063
  # Check actual executable
4064
  return _verify_cmd(path, cmd)
4065

    
4066

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

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

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

    
4086
  if not _enabled:
4087
    _Fail("Restricted commands disabled at configure time")
4088

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

    
4096
      (status, value) = _prepare_fn(_path, cmd)
4097

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

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

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

    
4125

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

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

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

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

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

    
4144

    
4145
class HooksRunner(object):
4146
  """Hook runner.
4147

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

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

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

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

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

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

    
4175
    results = self.RunHooks(hpath, phase, env)
4176

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

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

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

4198
    @raise errors.ProgrammerError: for invalid input
4199
        parameters
4200

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

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

    
4212
    results = []
4213

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

    
4219
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
4220

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

    
4236
    return results
4237

    
4238

    
4239
class IAllocatorRunner(object):
4240
  """IAllocator runner.
4241

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

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

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

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

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

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

    
4277
    return result.stdout
4278

    
4279

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

4283
  """
4284
  _DEV_PREFIX = "/dev/"
4285
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4286

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

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

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

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

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

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

4321
    @rtype: None
4322

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

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

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

4347
    @type dev_path: str
4348
    @param dev_path: the pathname of the device
4349

4350
    @rtype: None
4351

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