Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 72bb6b4e

History | View | Annotate | Download (107.6 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 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 import bdev
58
from ganeti import objects
59
from ganeti import ssconf
60
from ganeti import serializer
61
from ganeti import netutils
62
from ganeti import runtime
63

    
64

    
65
_BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id"
66
_ALLOWED_CLEAN_DIRS = frozenset([
67
  constants.DATA_DIR,
68
  constants.JOB_QUEUE_ARCHIVE_DIR,
69
  constants.QUEUE_DIR,
70
  constants.CRYPTO_KEYS_DIR,
71
  ])
72
_MAX_SSL_CERT_VALIDITY = 7 * 24 * 60 * 60
73
_X509_KEY_FILE = "key"
74
_X509_CERT_FILE = "cert"
75
_IES_STATUS_FILE = "status"
76
_IES_PID_FILE = "pid"
77
_IES_CA_FILE = "ca"
78

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

    
82

    
83
class RPCFail(Exception):
84
  """Class denoting RPC failure.
85

86
  Its argument is the error message.
87

88
  """
89

    
90

    
91
def _Fail(msg, *args, **kwargs):
92
  """Log an error and the raise an RPCFail exception.
93

94
  This exception is then handled specially in the ganeti daemon and
95
  turned into a 'failed' return type. As such, this function is a
96
  useful shortcut for logging the error and returning it to the master
97
  daemon.
98

99
  @type msg: string
100
  @param msg: the text of the exception
101
  @raise RPCFail
102

103
  """
104
  if args:
105
    msg = msg % args
106
  if "log" not in kwargs or kwargs["log"]: # if we should log this error
107
    if "exc" in kwargs and kwargs["exc"]:
108
      logging.exception(msg)
109
    else:
110
      logging.error(msg)
111
  raise RPCFail(msg)
112

    
113

    
114
def _GetConfig():
115
  """Simple wrapper to return a SimpleStore.
116

117
  @rtype: L{ssconf.SimpleStore}
118
  @return: a SimpleStore instance
119

120
  """
121
  return ssconf.SimpleStore()
122

    
123

    
124
def _GetSshRunner(cluster_name):
125
  """Simple wrapper to return an SshRunner.
126

127
  @type cluster_name: str
128
  @param cluster_name: the cluster name, which is needed
129
      by the SshRunner constructor
130
  @rtype: L{ssh.SshRunner}
131
  @return: an SshRunner instance
132

133
  """
134
  return ssh.SshRunner(cluster_name)
135

    
136

    
137
def _Decompress(data):
138
  """Unpacks data compressed by the RPC client.
139

140
  @type data: list or tuple
141
  @param data: Data sent by RPC client
142
  @rtype: str
143
  @return: Decompressed data
144

145
  """
146
  assert isinstance(data, (list, tuple))
147
  assert len(data) == 2
148
  (encoding, content) = data
149
  if encoding == constants.RPC_ENCODING_NONE:
150
    return content
151
  elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
152
    return zlib.decompress(base64.b64decode(content))
153
  else:
154
    raise AssertionError("Unknown data encoding")
155

    
156

    
157
def _CleanDirectory(path, exclude=None):
158
  """Removes all regular files in a directory.
159

160
  @type path: str
161
  @param path: the directory to clean
162
  @type exclude: list
163
  @param exclude: list of files to be excluded, defaults
164
      to the empty list
165

166
  """
167
  if path not in _ALLOWED_CLEAN_DIRS:
168
    _Fail("Path passed to _CleanDirectory not in allowed clean targets: '%s'",
169
          path)
170

    
171
  if not os.path.isdir(path):
172
    return
173
  if exclude is None:
174
    exclude = []
175
  else:
176
    # Normalize excluded paths
177
    exclude = [os.path.normpath(i) for i in exclude]
178

    
179
  for rel_name in utils.ListVisibleFiles(path):
180
    full_name = utils.PathJoin(path, rel_name)
181
    if full_name in exclude:
182
      continue
183
    if os.path.isfile(full_name) and not os.path.islink(full_name):
184
      utils.RemoveFile(full_name)
185

    
186

    
187
def _BuildUploadFileList():
188
  """Build the list of allowed upload files.
189

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

192
  """
193
  allowed_files = set([
194
    constants.CLUSTER_CONF_FILE,
195
    constants.ETC_HOSTS,
196
    constants.SSH_KNOWN_HOSTS_FILE,
197
    constants.VNC_PASSWORD_FILE,
198
    constants.RAPI_CERT_FILE,
199
    constants.SPICE_CERT_FILE,
200
    constants.SPICE_CACERT_FILE,
201
    constants.RAPI_USERS_FILE,
202
    constants.CONFD_HMAC_KEY,
203
    constants.CLUSTER_DOMAIN_SECRET_FILE,
204
    ])
205

    
206
  for hv_name in constants.HYPER_TYPES:
207
    hv_class = hypervisor.GetHypervisorClass(hv_name)
208
    allowed_files.update(hv_class.GetAncillaryFiles())
209

    
210
  return frozenset(allowed_files)
211

    
212

    
213
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
214

    
215

    
216
def JobQueuePurge():
217
  """Removes job queue files and archived jobs.
218

219
  @rtype: tuple
220
  @return: True, None
221

222
  """
223
  _CleanDirectory(constants.QUEUE_DIR, exclude=[constants.JOB_QUEUE_LOCK_FILE])
224
  _CleanDirectory(constants.JOB_QUEUE_ARCHIVE_DIR)
225

    
226

    
227
def GetMasterInfo():
228
  """Returns master information.
229

230
  This is an utility function to compute master information, either
231
  for consumption here or from the node daemon.
232

233
  @rtype: tuple
234
  @return: master_netdev, master_ip, master_name, primary_ip_family
235
  @raise RPCFail: in case of errors
236

237
  """
238
  try:
239
    cfg = _GetConfig()
240
    master_netdev = cfg.GetMasterNetdev()
241
    master_ip = cfg.GetMasterIP()
242
    master_node = cfg.GetMasterNode()
243
    primary_ip_family = cfg.GetPrimaryIPFamily()
244
  except errors.ConfigurationError, err:
245
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
246
  return (master_netdev, master_ip, master_node, primary_ip_family)
247

    
248

    
249
def ActivateMasterIp():
250
  """Activate the IP address of the master daemon.
251

252
  """
253
  # GetMasterInfo will raise an exception if not able to return data
254
  master_netdev, master_ip, _, family = GetMasterInfo()
255

    
256
  err_msg = None
257
  if netutils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
258
    if netutils.IPAddress.Own(master_ip):
259
      # we already have the ip:
260
      logging.debug("Master IP already configured, doing nothing")
261
    else:
262
      err_msg = "Someone else has the master ip, not activating"
263
      logging.error(err_msg)
264
  else:
265
    ipcls = netutils.IP4Address
266
    if family == netutils.IP6Address.family:
267
      ipcls = netutils.IP6Address
268

    
269
    result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
270
                           "%s/%d" % (master_ip, ipcls.iplen),
271
                           "dev", master_netdev, "label",
272
                           "%s:0" % master_netdev])
273
    if result.failed:
274
      err_msg = "Can't activate master IP: %s" % result.output
275
      logging.error(err_msg)
276

    
277
    # we ignore the exit code of the following cmds
278
    if ipcls == netutils.IP4Address:
279
      utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev, "-s",
280
                    master_ip, master_ip])
281
    elif ipcls == netutils.IP6Address:
282
      try:
283
        utils.RunCmd(["ndisc6", "-q", "-r 3", master_ip, master_netdev])
284
      except errors.OpExecError:
285
        # TODO: Better error reporting
286
        logging.warning("Can't execute ndisc6, please install if missing")
287

    
288
  if err_msg:
289
    _Fail(err_msg)
290

    
291

    
292
def StartMasterDaemons(no_voting):
293
  """Activate local node as master node.
294

295
  The function will start the master daemons (ganeti-masterd and ganeti-rapi).
296

297
  @type no_voting: boolean
298
  @param no_voting: whether to start ganeti-masterd without a node vote
299
      but still non-interactively
300
  @rtype: None
301

302
  """
303

    
304
  if no_voting:
305
    masterd_args = "--no-voting --yes-do-it"
306
  else:
307
    masterd_args = ""
308

    
309
  env = {
310
    "EXTRA_MASTERD_ARGS": masterd_args,
311
    }
312

    
313
  result = utils.RunCmd([constants.DAEMON_UTIL, "start-master"], env=env)
314
  if result.failed:
315
    msg = "Can't start Ganeti master: %s" % result.output
316
    logging.error(msg)
317
    _Fail(msg)
318

    
319

    
320
def DeactivateMasterIp():
321
  """Deactivate the master IP on this node.
322

323
  """
324
  # TODO: log and report back to the caller the error failures; we
325
  # need to decide in which case we fail the RPC for this
326

    
327
  # GetMasterInfo will raise an exception if not able to return data
328
  master_netdev, master_ip, _, family = GetMasterInfo()
329

    
330
  ipcls = netutils.IP4Address
331
  if family == netutils.IP6Address.family:
332
    ipcls = netutils.IP6Address
333

    
334
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
335
                         "%s/%d" % (master_ip, ipcls.iplen),
336
                         "dev", master_netdev])
337
  if result.failed:
338
    logging.error("Can't remove the master IP, error: %s", result.output)
339
    # but otherwise ignore the failure
340

    
341

    
342
def StopMasterDaemons():
343
  """Stop the master daemons on this node.
344

345
  Stop the master daemons (ganeti-masterd and ganeti-rapi) on this node.
346

347
  @rtype: None
348

349
  """
350
  # TODO: log and report back to the caller the error failures; we
351
  # need to decide in which case we fail the RPC for this
352

    
353
  result = utils.RunCmd([constants.DAEMON_UTIL, "stop-master"])
354
  if result.failed:
355
    logging.error("Could not stop Ganeti master, command %s had exitcode %s"
356
                  " and error %s",
357
                  result.cmd, result.exit_code, result.output)
358

    
359

    
360
def EtcHostsModify(mode, host, ip):
361
  """Modify a host entry in /etc/hosts.
362

363
  @param mode: The mode to operate. Either add or remove entry
364
  @param host: The host to operate on
365
  @param ip: The ip associated with the entry
366

367
  """
368
  if mode == constants.ETC_HOSTS_ADD:
369
    if not ip:
370
      RPCFail("Mode 'add' needs 'ip' parameter, but parameter not"
371
              " present")
372
    utils.AddHostToEtcHosts(host, ip)
373
  elif mode == constants.ETC_HOSTS_REMOVE:
374
    if ip:
375
      RPCFail("Mode 'remove' does not allow 'ip' parameter, but"
376
              " parameter is present")
377
    utils.RemoveHostFromEtcHosts(host)
378
  else:
379
    RPCFail("Mode not supported")
380

    
381

    
382
def LeaveCluster(modify_ssh_setup):
383
  """Cleans up and remove the current node.
384

385
  This function cleans up and prepares the current node to be removed
386
  from the cluster.
387

388
  If processing is successful, then it raises an
389
  L{errors.QuitGanetiException} which is used as a special case to
390
  shutdown the node daemon.
391

392
  @param modify_ssh_setup: boolean
393

394
  """
395
  _CleanDirectory(constants.DATA_DIR)
396
  _CleanDirectory(constants.CRYPTO_KEYS_DIR)
397
  JobQueuePurge()
398

    
399
  if modify_ssh_setup:
400
    try:
401
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
402

    
403
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
404

    
405
      utils.RemoveFile(priv_key)
406
      utils.RemoveFile(pub_key)
407
    except errors.OpExecError:
408
      logging.exception("Error while processing ssh files")
409

    
410
  try:
411
    utils.RemoveFile(constants.CONFD_HMAC_KEY)
412
    utils.RemoveFile(constants.RAPI_CERT_FILE)
413
    utils.RemoveFile(constants.SPICE_CERT_FILE)
414
    utils.RemoveFile(constants.SPICE_CACERT_FILE)
415
    utils.RemoveFile(constants.NODED_CERT_FILE)
416
  except: # pylint: disable=W0702
417
    logging.exception("Error while removing cluster secrets")
418

    
419
  result = utils.RunCmd([constants.DAEMON_UTIL, "stop", constants.CONFD])
420
  if result.failed:
421
    logging.error("Command %s failed with exitcode %s and error %s",
422
                  result.cmd, result.exit_code, result.output)
423

    
424
  # Raise a custom exception (handled in ganeti-noded)
425
  raise errors.QuitGanetiException(True, "Shutdown scheduled")
426

    
427

    
428
def GetNodeInfo(vgname, hypervisor_type):
429
  """Gives back a hash with different information about the node.
430

431
  @type vgname: C{string}
432
  @param vgname: the name of the volume group to ask for disk space information
433
  @type hypervisor_type: C{str}
434
  @param hypervisor_type: the name of the hypervisor to ask for
435
      memory information
436
  @rtype: C{dict}
437
  @return: dictionary with the following keys:
438
      - vg_size is the size of the configured volume group in MiB
439
      - vg_free is the free size of the volume group in MiB
440
      - memory_dom0 is the memory allocated for domain0 in MiB
441
      - memory_free is the currently available (free) ram in MiB
442
      - memory_total is the total number of ram in MiB
443
      - hv_version: the hypervisor version, if available
444

445
  """
446
  outputarray = {}
447

    
448
  if vgname is not None:
449
    vginfo = bdev.LogicalVolume.GetVGInfo([vgname])
450
    vg_free = vg_size = None
451
    if vginfo:
452
      vg_free = int(round(vginfo[0][0], 0))
453
      vg_size = int(round(vginfo[0][1], 0))
454
    outputarray["vg_size"] = vg_size
455
    outputarray["vg_free"] = vg_free
456

    
457
  if hypervisor_type is not None:
458
    hyper = hypervisor.GetHypervisor(hypervisor_type)
459
    hyp_info = hyper.GetNodeInfo()
460
    if hyp_info is not None:
461
      outputarray.update(hyp_info)
462

    
463
  outputarray["bootid"] = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
464

    
465
  return outputarray
466

    
467

    
468
def VerifyNode(what, cluster_name):
469
  """Verify the status of the local node.
470

471
  Based on the input L{what} parameter, various checks are done on the
472
  local node.
473

474
  If the I{filelist} key is present, this list of
475
  files is checksummed and the file/checksum pairs are returned.
476

477
  If the I{nodelist} key is present, we check that we have
478
  connectivity via ssh with the target nodes (and check the hostname
479
  report).
480

481
  If the I{node-net-test} key is present, we check that we have
482
  connectivity to the given nodes via both primary IP and, if
483
  applicable, secondary IPs.
484

485
  @type what: C{dict}
486
  @param what: a dictionary of things to check:
487
      - filelist: list of files for which to compute checksums
488
      - nodelist: list of nodes we should check ssh communication with
489
      - node-net-test: list of nodes we should check node daemon port
490
        connectivity with
491
      - hypervisor: list with hypervisors to run the verify for
492
  @rtype: dict
493
  @return: a dictionary with the same keys as the input dict, and
494
      values representing the result of the checks
495

496
  """
497
  result = {}
498
  my_name = netutils.Hostname.GetSysName()
499
  port = netutils.GetDaemonPort(constants.NODED)
500
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
501

    
502
  if constants.NV_HYPERVISOR in what and vm_capable:
503
    result[constants.NV_HYPERVISOR] = tmp = {}
504
    for hv_name in what[constants.NV_HYPERVISOR]:
505
      try:
506
        val = hypervisor.GetHypervisor(hv_name).Verify()
507
      except errors.HypervisorError, err:
508
        val = "Error while checking hypervisor: %s" % str(err)
509
      tmp[hv_name] = val
510

    
511
  if constants.NV_HVPARAMS in what and vm_capable:
512
    result[constants.NV_HVPARAMS] = tmp = []
513
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
514
      try:
515
        logging.info("Validating hv %s, %s", hv_name, hvparms)
516
        hypervisor.GetHypervisor(hv_name).ValidateParameters(hvparms)
517
      except errors.HypervisorError, err:
518
        tmp.append((source, hv_name, str(err)))
519

    
520
  if constants.NV_FILELIST in what:
521
    result[constants.NV_FILELIST] = utils.FingerprintFiles(
522
      what[constants.NV_FILELIST])
523

    
524
  if constants.NV_NODELIST in what:
525
    result[constants.NV_NODELIST] = tmp = {}
526
    random.shuffle(what[constants.NV_NODELIST])
527
    for node in what[constants.NV_NODELIST]:
528
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
529
      if not success:
530
        tmp[node] = message
531

    
532
  if constants.NV_NODENETTEST in what:
533
    result[constants.NV_NODENETTEST] = tmp = {}
534
    my_pip = my_sip = None
535
    for name, pip, sip in what[constants.NV_NODENETTEST]:
536
      if name == my_name:
537
        my_pip = pip
538
        my_sip = sip
539
        break
540
    if not my_pip:
541
      tmp[my_name] = ("Can't find my own primary/secondary IP"
542
                      " in the node list")
543
    else:
544
      for name, pip, sip in what[constants.NV_NODENETTEST]:
545
        fail = []
546
        if not netutils.TcpPing(pip, port, source=my_pip):
547
          fail.append("primary")
548
        if sip != pip:
549
          if not netutils.TcpPing(sip, port, source=my_sip):
550
            fail.append("secondary")
551
        if fail:
552
          tmp[name] = ("failure using the %s interface(s)" %
553
                       " and ".join(fail))
554

    
555
  if constants.NV_MASTERIP in what:
556
    # FIXME: add checks on incoming data structures (here and in the
557
    # rest of the function)
558
    master_name, master_ip = what[constants.NV_MASTERIP]
559
    if master_name == my_name:
560
      source = constants.IP4_ADDRESS_LOCALHOST
561
    else:
562
      source = None
563
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
564
                                                  source=source)
565

    
566
  if constants.NV_OOB_PATHS in what:
567
    result[constants.NV_OOB_PATHS] = tmp = []
568
    for path in what[constants.NV_OOB_PATHS]:
569
      try:
570
        st = os.stat(path)
571
      except OSError, err:
572
        tmp.append("error stating out of band helper: %s" % err)
573
      else:
574
        if stat.S_ISREG(st.st_mode):
575
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
576
            tmp.append(None)
577
          else:
578
            tmp.append("out of band helper %s is not executable" % path)
579
        else:
580
          tmp.append("out of band helper %s is not a file" % path)
581

    
582
  if constants.NV_LVLIST in what and vm_capable:
583
    try:
584
      val = GetVolumeList(utils.ListVolumeGroups().keys())
585
    except RPCFail, err:
586
      val = str(err)
587
    result[constants.NV_LVLIST] = val
588

    
589
  if constants.NV_INSTANCELIST in what and vm_capable:
590
    # GetInstanceList can fail
591
    try:
592
      val = GetInstanceList(what[constants.NV_INSTANCELIST])
593
    except RPCFail, err:
594
      val = str(err)
595
    result[constants.NV_INSTANCELIST] = val
596

    
597
  if constants.NV_VGLIST in what and vm_capable:
598
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
599

    
600
  if constants.NV_PVLIST in what and vm_capable:
601
    result[constants.NV_PVLIST] = \
602
      bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
603
                                   filter_allocatable=False)
604

    
605
  if constants.NV_VERSION in what:
606
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
607
                                    constants.RELEASE_VERSION)
608

    
609
  if constants.NV_HVINFO in what and vm_capable:
610
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
611
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
612

    
613
  if constants.NV_DRBDLIST in what and vm_capable:
614
    try:
615
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
616
    except errors.BlockDeviceError, err:
617
      logging.warning("Can't get used minors list", exc_info=True)
618
      used_minors = str(err)
619
    result[constants.NV_DRBDLIST] = used_minors
620

    
621
  if constants.NV_DRBDHELPER in what and vm_capable:
622
    status = True
623
    try:
624
      payload = bdev.BaseDRBD.GetUsermodeHelper()
625
    except errors.BlockDeviceError, err:
626
      logging.error("Can't get DRBD usermode helper: %s", str(err))
627
      status = False
628
      payload = str(err)
629
    result[constants.NV_DRBDHELPER] = (status, payload)
630

    
631
  if constants.NV_NODESETUP in what:
632
    result[constants.NV_NODESETUP] = tmpr = []
633
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
634
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
635
                  " under /sys, missing required directories /sys/block"
636
                  " and /sys/class/net")
637
    if (not os.path.isdir("/proc/sys") or
638
        not os.path.isfile("/proc/sysrq-trigger")):
639
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
640
                  " under /proc, missing required directory /proc/sys and"
641
                  " the file /proc/sysrq-trigger")
642

    
643
  if constants.NV_TIME in what:
644
    result[constants.NV_TIME] = utils.SplitTime(time.time())
645

    
646
  if constants.NV_OSLIST in what and vm_capable:
647
    result[constants.NV_OSLIST] = DiagnoseOS()
648

    
649
  if constants.NV_BRIDGES in what and vm_capable:
650
    result[constants.NV_BRIDGES] = [bridge
651
                                    for bridge in what[constants.NV_BRIDGES]
652
                                    if not utils.BridgeExists(bridge)]
653
  return result
654

    
655

    
656
def GetBlockDevSizes(devices):
657
  """Return the size of the given block devices
658

659
  @type devices: list
660
  @param devices: list of block device nodes to query
661
  @rtype: dict
662
  @return:
663
    dictionary of all block devices under /dev (key). The value is their
664
    size in MiB.
665

666
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
667

668
  """
669
  DEV_PREFIX = "/dev/"
670
  blockdevs = {}
671

    
672
  for devpath in devices:
673
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
674
      continue
675

    
676
    try:
677
      st = os.stat(devpath)
678
    except EnvironmentError, err:
679
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
680
      continue
681

    
682
    if stat.S_ISBLK(st.st_mode):
683
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
684
      if result.failed:
685
        # We don't want to fail, just do not list this device as available
686
        logging.warning("Cannot get size for block device %s", devpath)
687
        continue
688

    
689
      size = int(result.stdout) / (1024 * 1024)
690
      blockdevs[devpath] = size
691
  return blockdevs
692

    
693

    
694
def GetVolumeList(vg_names):
695
  """Compute list of logical volumes and their size.
696

697
  @type vg_names: list
698
  @param vg_names: the volume groups whose LVs we should list, or
699
      empty for all volume groups
700
  @rtype: dict
701
  @return:
702
      dictionary of all partions (key) with value being a tuple of
703
      their size (in MiB), inactive and online status::
704

705
        {'xenvg/test1': ('20.06', True, True)}
706

707
      in case of errors, a string is returned with the error
708
      details.
709

710
  """
711
  lvs = {}
712
  sep = "|"
713
  if not vg_names:
714
    vg_names = []
715
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
716
                         "--separator=%s" % sep,
717
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
718
  if result.failed:
719
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
720

    
721
  for line in result.stdout.splitlines():
722
    line = line.strip()
723
    match = _LVSLINE_REGEX.match(line)
724
    if not match:
725
      logging.error("Invalid line returned from lvs output: '%s'", line)
726
      continue
727
    vg_name, name, size, attr = match.groups()
728
    inactive = attr[4] == "-"
729
    online = attr[5] == "o"
730
    virtual = attr[0] == "v"
731
    if virtual:
732
      # we don't want to report such volumes as existing, since they
733
      # don't really hold data
734
      continue
735
    lvs[vg_name + "/" + name] = (size, inactive, online)
736

    
737
  return lvs
738

    
739

    
740
def ListVolumeGroups():
741
  """List the volume groups and their size.
742

743
  @rtype: dict
744
  @return: dictionary with keys volume name and values the
745
      size of the volume
746

747
  """
748
  return utils.ListVolumeGroups()
749

    
750

    
751
def NodeVolumes():
752
  """List all volumes on this node.
753

754
  @rtype: list
755
  @return:
756
    A list of dictionaries, each having four keys:
757
      - name: the logical volume name,
758
      - size: the size of the logical volume
759
      - dev: the physical device on which the LV lives
760
      - vg: the volume group to which it belongs
761

762
    In case of errors, we return an empty list and log the
763
    error.
764

765
    Note that since a logical volume can live on multiple physical
766
    volumes, the resulting list might include a logical volume
767
    multiple times.
768

769
  """
770
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
771
                         "--separator=|",
772
                         "--options=lv_name,lv_size,devices,vg_name"])
773
  if result.failed:
774
    _Fail("Failed to list logical volumes, lvs output: %s",
775
          result.output)
776

    
777
  def parse_dev(dev):
778
    return dev.split("(")[0]
779

    
780
  def handle_dev(dev):
781
    return [parse_dev(x) for x in dev.split(",")]
782

    
783
  def map_line(line):
784
    line = [v.strip() for v in line]
785
    return [{"name": line[0], "size": line[1],
786
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
787

    
788
  all_devs = []
789
  for line in result.stdout.splitlines():
790
    if line.count("|") >= 3:
791
      all_devs.extend(map_line(line.split("|")))
792
    else:
793
      logging.warning("Strange line in the output from lvs: '%s'", line)
794
  return all_devs
795

    
796

    
797
def BridgesExist(bridges_list):
798
  """Check if a list of bridges exist on the current node.
799

800
  @rtype: boolean
801
  @return: C{True} if all of them exist, C{False} otherwise
802

803
  """
804
  missing = []
805
  for bridge in bridges_list:
806
    if not utils.BridgeExists(bridge):
807
      missing.append(bridge)
808

    
809
  if missing:
810
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
811

    
812

    
813
def GetInstanceList(hypervisor_list):
814
  """Provides a list of instances.
815

816
  @type hypervisor_list: list
817
  @param hypervisor_list: the list of hypervisors to query information
818

819
  @rtype: list
820
  @return: a list of all running instances on the current node
821
    - instance1.example.com
822
    - instance2.example.com
823

824
  """
825
  results = []
826
  for hname in hypervisor_list:
827
    try:
828
      names = hypervisor.GetHypervisor(hname).ListInstances()
829
      results.extend(names)
830
    except errors.HypervisorError, err:
831
      _Fail("Error enumerating instances (hypervisor %s): %s",
832
            hname, err, exc=True)
833

    
834
  return results
835

    
836

    
837
def GetInstanceInfo(instance, hname):
838
  """Gives back the information about an instance as a dictionary.
839

840
  @type instance: string
841
  @param instance: the instance name
842
  @type hname: string
843
  @param hname: the hypervisor type of the instance
844

845
  @rtype: dict
846
  @return: dictionary with the following keys:
847
      - memory: memory size of instance (int)
848
      - state: xen state of instance (string)
849
      - time: cpu time of instance (float)
850

851
  """
852
  output = {}
853

    
854
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
855
  if iinfo is not None:
856
    output["memory"] = iinfo[2]
857
    output["state"] = iinfo[4]
858
    output["time"] = iinfo[5]
859

    
860
  return output
861

    
862

    
863
def GetInstanceMigratable(instance):
864
  """Gives whether an instance can be migrated.
865

866
  @type instance: L{objects.Instance}
867
  @param instance: object representing the instance to be checked.
868

869
  @rtype: tuple
870
  @return: tuple of (result, description) where:
871
      - result: whether the instance can be migrated or not
872
      - description: a description of the issue, if relevant
873

874
  """
875
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
876
  iname = instance.name
877
  if iname not in hyper.ListInstances():
878
    _Fail("Instance %s is not running", iname)
879

    
880
  for idx in range(len(instance.disks)):
881
    link_name = _GetBlockDevSymlinkPath(iname, idx)
882
    if not os.path.islink(link_name):
883
      logging.warning("Instance %s is missing symlink %s for disk %d",
884
                      iname, link_name, idx)
885

    
886

    
887
def GetAllInstancesInfo(hypervisor_list):
888
  """Gather data about all instances.
889

890
  This is the equivalent of L{GetInstanceInfo}, except that it
891
  computes data for all instances at once, thus being faster if one
892
  needs data about more than one instance.
893

894
  @type hypervisor_list: list
895
  @param hypervisor_list: list of hypervisors to query for instance data
896

897
  @rtype: dict
898
  @return: dictionary of instance: data, with data having the following keys:
899
      - memory: memory size of instance (int)
900
      - state: xen state of instance (string)
901
      - time: cpu time of instance (float)
902
      - vcpus: the number of vcpus
903

904
  """
905
  output = {}
906

    
907
  for hname in hypervisor_list:
908
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
909
    if iinfo:
910
      for name, _, memory, vcpus, state, times in iinfo:
911
        value = {
912
          "memory": memory,
913
          "vcpus": vcpus,
914
          "state": state,
915
          "time": times,
916
          }
917
        if name in output:
918
          # we only check static parameters, like memory and vcpus,
919
          # and not state and time which can change between the
920
          # invocations of the different hypervisors
921
          for key in "memory", "vcpus":
922
            if value[key] != output[name][key]:
923
              _Fail("Instance %s is running twice"
924
                    " with different parameters", name)
925
        output[name] = value
926

    
927
  return output
928

    
929

    
930
def _InstanceLogName(kind, os_name, instance, component):
931
  """Compute the OS log filename for a given instance and operation.
932

933
  The instance name and os name are passed in as strings since not all
934
  operations have these as part of an instance object.
935

936
  @type kind: string
937
  @param kind: the operation type (e.g. add, import, etc.)
938
  @type os_name: string
939
  @param os_name: the os name
940
  @type instance: string
941
  @param instance: the name of the instance being imported/added/etc.
942
  @type component: string or None
943
  @param component: the name of the component of the instance being
944
      transferred
945

946
  """
947
  # TODO: Use tempfile.mkstemp to create unique filename
948
  if component:
949
    assert "/" not in component
950
    c_msg = "-%s" % component
951
  else:
952
    c_msg = ""
953
  base = ("%s-%s-%s%s-%s.log" %
954
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
955
  return utils.PathJoin(constants.LOG_OS_DIR, base)
956

    
957

    
958
def InstanceOsAdd(instance, reinstall, debug):
959
  """Add an OS to an instance.
960

961
  @type instance: L{objects.Instance}
962
  @param instance: Instance whose OS is to be installed
963
  @type reinstall: boolean
964
  @param reinstall: whether this is an instance reinstall
965
  @type debug: integer
966
  @param debug: debug level, passed to the OS scripts
967
  @rtype: None
968

969
  """
970
  inst_os = OSFromDisk(instance.os)
971

    
972
  create_env = OSEnvironment(instance, inst_os, debug)
973
  if reinstall:
974
    create_env["INSTANCE_REINSTALL"] = "1"
975

    
976
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
977

    
978
  result = utils.RunCmd([inst_os.create_script], env=create_env,
979
                        cwd=inst_os.path, output=logfile, reset_env=True)
980
  if result.failed:
981
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
982
                  " output: %s", result.cmd, result.fail_reason, logfile,
983
                  result.output)
984
    lines = [utils.SafeEncode(val)
985
             for val in utils.TailFile(logfile, lines=20)]
986
    _Fail("OS create script failed (%s), last lines in the"
987
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
988

    
989

    
990
def RunRenameInstance(instance, old_name, debug):
991
  """Run the OS rename script for an instance.
992

993
  @type instance: L{objects.Instance}
994
  @param instance: Instance whose OS is to be installed
995
  @type old_name: string
996
  @param old_name: previous instance name
997
  @type debug: integer
998
  @param debug: debug level, passed to the OS scripts
999
  @rtype: boolean
1000
  @return: the success of the operation
1001

1002
  """
1003
  inst_os = OSFromDisk(instance.os)
1004

    
1005
  rename_env = OSEnvironment(instance, inst_os, debug)
1006
  rename_env["OLD_INSTANCE_NAME"] = old_name
1007

    
1008
  logfile = _InstanceLogName("rename", instance.os,
1009
                             "%s-%s" % (old_name, instance.name), None)
1010

    
1011
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1012
                        cwd=inst_os.path, output=logfile, reset_env=True)
1013

    
1014
  if result.failed:
1015
    logging.error("os create command '%s' returned error: %s output: %s",
1016
                  result.cmd, result.fail_reason, result.output)
1017
    lines = [utils.SafeEncode(val)
1018
             for val in utils.TailFile(logfile, lines=20)]
1019
    _Fail("OS rename script failed (%s), last lines in the"
1020
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1021

    
1022

    
1023
def _GetBlockDevSymlinkPath(instance_name, idx):
1024
  return utils.PathJoin(constants.DISK_LINKS_DIR, "%s%s%d" %
1025
                        (instance_name, constants.DISK_SEPARATOR, idx))
1026

    
1027

    
1028
def _SymlinkBlockDev(instance_name, device_path, idx):
1029
  """Set up symlinks to a instance's block device.
1030

1031
  This is an auxiliary function run when an instance is start (on the primary
1032
  node) or when an instance is migrated (on the target node).
1033

1034

1035
  @param instance_name: the name of the target instance
1036
  @param device_path: path of the physical block device, on the node
1037
  @param idx: the disk index
1038
  @return: absolute path to the disk's symlink
1039

1040
  """
1041
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1042
  try:
1043
    os.symlink(device_path, link_name)
1044
  except OSError, err:
1045
    if err.errno == errno.EEXIST:
1046
      if (not os.path.islink(link_name) or
1047
          os.readlink(link_name) != device_path):
1048
        os.remove(link_name)
1049
        os.symlink(device_path, link_name)
1050
    else:
1051
      raise
1052

    
1053
  return link_name
1054

    
1055

    
1056
def _RemoveBlockDevLinks(instance_name, disks):
1057
  """Remove the block device symlinks belonging to the given instance.
1058

1059
  """
1060
  for idx, _ in enumerate(disks):
1061
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1062
    if os.path.islink(link_name):
1063
      try:
1064
        os.remove(link_name)
1065
      except OSError:
1066
        logging.exception("Can't remove symlink '%s'", link_name)
1067

    
1068

    
1069
def _GatherAndLinkBlockDevs(instance):
1070
  """Set up an instance's block device(s).
1071

1072
  This is run on the primary node at instance startup. The block
1073
  devices must be already assembled.
1074

1075
  @type instance: L{objects.Instance}
1076
  @param instance: the instance whose disks we shoul assemble
1077
  @rtype: list
1078
  @return: list of (disk_object, device_path)
1079

1080
  """
1081
  block_devices = []
1082
  for idx, disk in enumerate(instance.disks):
1083
    device = _RecursiveFindBD(disk)
1084
    if device is None:
1085
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1086
                                    str(disk))
1087
    device.Open()
1088
    try:
1089
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1090
    except OSError, e:
1091
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1092
                                    e.strerror)
1093

    
1094
    block_devices.append((disk, link_name))
1095

    
1096
  return block_devices
1097

    
1098

    
1099
def StartInstance(instance, startup_paused):
1100
  """Start an instance.
1101

1102
  @type instance: L{objects.Instance}
1103
  @param instance: the instance object
1104
  @type startup_paused: bool
1105
  @param instance: pause instance at startup?
1106
  @rtype: None
1107

1108
  """
1109
  running_instances = GetInstanceList([instance.hypervisor])
1110

    
1111
  if instance.name in running_instances:
1112
    logging.info("Instance %s already running, not starting", instance.name)
1113
    return
1114

    
1115
  try:
1116
    block_devices = _GatherAndLinkBlockDevs(instance)
1117
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1118
    hyper.StartInstance(instance, block_devices, startup_paused)
1119
  except errors.BlockDeviceError, err:
1120
    _Fail("Block device error: %s", err, exc=True)
1121
  except errors.HypervisorError, err:
1122
    _RemoveBlockDevLinks(instance.name, instance.disks)
1123
    _Fail("Hypervisor error: %s", err, exc=True)
1124

    
1125

    
1126
def InstanceShutdown(instance, timeout):
1127
  """Shut an instance down.
1128

1129
  @note: this functions uses polling with a hardcoded timeout.
1130

1131
  @type instance: L{objects.Instance}
1132
  @param instance: the instance object
1133
  @type timeout: integer
1134
  @param timeout: maximum timeout for soft shutdown
1135
  @rtype: None
1136

1137
  """
1138
  hv_name = instance.hypervisor
1139
  hyper = hypervisor.GetHypervisor(hv_name)
1140
  iname = instance.name
1141

    
1142
  if instance.name not in hyper.ListInstances():
1143
    logging.info("Instance %s not running, doing nothing", iname)
1144
    return
1145

    
1146
  class _TryShutdown:
1147
    def __init__(self):
1148
      self.tried_once = False
1149

    
1150
    def __call__(self):
1151
      if iname not in hyper.ListInstances():
1152
        return
1153

    
1154
      try:
1155
        hyper.StopInstance(instance, retry=self.tried_once)
1156
      except errors.HypervisorError, err:
1157
        if iname not in hyper.ListInstances():
1158
          # if the instance is no longer existing, consider this a
1159
          # success and go to cleanup
1160
          return
1161

    
1162
        _Fail("Failed to stop instance %s: %s", iname, err)
1163

    
1164
      self.tried_once = True
1165

    
1166
      raise utils.RetryAgain()
1167

    
1168
  try:
1169
    utils.Retry(_TryShutdown(), 5, timeout)
1170
  except utils.RetryTimeout:
1171
    # the shutdown did not succeed
1172
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1173

    
1174
    try:
1175
      hyper.StopInstance(instance, force=True)
1176
    except errors.HypervisorError, err:
1177
      if iname in hyper.ListInstances():
1178
        # only raise an error if the instance still exists, otherwise
1179
        # the error could simply be "instance ... unknown"!
1180
        _Fail("Failed to force stop instance %s: %s", iname, err)
1181

    
1182
    time.sleep(1)
1183

    
1184
    if iname in hyper.ListInstances():
1185
      _Fail("Could not shutdown instance %s even by destroy", iname)
1186

    
1187
  try:
1188
    hyper.CleanupInstance(instance.name)
1189
  except errors.HypervisorError, err:
1190
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1191

    
1192
  _RemoveBlockDevLinks(iname, instance.disks)
1193

    
1194

    
1195
def InstanceReboot(instance, reboot_type, shutdown_timeout):
1196
  """Reboot an instance.
1197

1198
  @type instance: L{objects.Instance}
1199
  @param instance: the instance object to reboot
1200
  @type reboot_type: str
1201
  @param reboot_type: the type of reboot, one the following
1202
    constants:
1203
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1204
        instance OS, do not recreate the VM
1205
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1206
        restart the VM (at the hypervisor level)
1207
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1208
        not accepted here, since that mode is handled differently, in
1209
        cmdlib, and translates into full stop and start of the
1210
        instance (instead of a call_instance_reboot RPC)
1211
  @type shutdown_timeout: integer
1212
  @param shutdown_timeout: maximum timeout for soft shutdown
1213
  @rtype: None
1214

1215
  """
1216
  running_instances = GetInstanceList([instance.hypervisor])
1217

    
1218
  if instance.name not in running_instances:
1219
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1220

    
1221
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1222
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1223
    try:
1224
      hyper.RebootInstance(instance)
1225
    except errors.HypervisorError, err:
1226
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1227
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1228
    try:
1229
      InstanceShutdown(instance, shutdown_timeout)
1230
      return StartInstance(instance, False)
1231
    except errors.HypervisorError, err:
1232
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1233
  else:
1234
    _Fail("Invalid reboot_type received: %s", reboot_type)
1235

    
1236

    
1237
def MigrationInfo(instance):
1238
  """Gather information about an instance to be migrated.
1239

1240
  @type instance: L{objects.Instance}
1241
  @param instance: the instance definition
1242

1243
  """
1244
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1245
  try:
1246
    info = hyper.MigrationInfo(instance)
1247
  except errors.HypervisorError, err:
1248
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1249
  return info
1250

    
1251

    
1252
def AcceptInstance(instance, info, target):
1253
  """Prepare the node to accept an instance.
1254

1255
  @type instance: L{objects.Instance}
1256
  @param instance: the instance definition
1257
  @type info: string/data (opaque)
1258
  @param info: migration information, from the source node
1259
  @type target: string
1260
  @param target: target host (usually ip), on this node
1261

1262
  """
1263
  # TODO: why is this required only for DTS_EXT_MIRROR?
1264
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1265
    # Create the symlinks, as the disks are not active
1266
    # in any way
1267
    try:
1268
      _GatherAndLinkBlockDevs(instance)
1269
    except errors.BlockDeviceError, err:
1270
      _Fail("Block device error: %s", err, exc=True)
1271

    
1272
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1273
  try:
1274
    hyper.AcceptInstance(instance, info, target)
1275
  except errors.HypervisorError, err:
1276
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1277
      _RemoveBlockDevLinks(instance.name, instance.disks)
1278
    _Fail("Failed to accept instance: %s", err, exc=True)
1279

    
1280

    
1281
def FinalizeMigrationDst(instance, info, success):
1282
  """Finalize any preparation to accept an instance.
1283

1284
  @type instance: L{objects.Instance}
1285
  @param instance: the instance definition
1286
  @type info: string/data (opaque)
1287
  @param info: migration information, from the source node
1288
  @type success: boolean
1289
  @param success: whether the migration was a success or a failure
1290

1291
  """
1292
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1293
  try:
1294
    hyper.FinalizeMigrationDst(instance, info, success)
1295
  except errors.HypervisorError, err:
1296
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1297

    
1298

    
1299
def MigrateInstance(instance, target, live):
1300
  """Migrates an instance to another node.
1301

1302
  @type instance: L{objects.Instance}
1303
  @param instance: the instance definition
1304
  @type target: string
1305
  @param target: the target node name
1306
  @type live: boolean
1307
  @param live: whether the migration should be done live or not (the
1308
      interpretation of this parameter is left to the hypervisor)
1309
  @raise RPCFail: if migration fails for some reason
1310

1311
  """
1312
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1313

    
1314
  try:
1315
    hyper.MigrateInstance(instance, target, live)
1316
  except errors.HypervisorError, err:
1317
    _Fail("Failed to migrate instance: %s", err, exc=True)
1318

    
1319

    
1320
def FinalizeMigrationSource(instance, success, live):
1321
  """Finalize the instance migration on the source node.
1322

1323
  @type instance: L{objects.Instance}
1324
  @param instance: the instance definition of the migrated instance
1325
  @type success: bool
1326
  @param success: whether the migration succeeded or not
1327
  @type live: bool
1328
  @param live: whether the user requested a live migration or not
1329
  @raise RPCFail: If the execution fails for some reason
1330

1331
  """
1332
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1333

    
1334
  try:
1335
    hyper.FinalizeMigrationSource(instance, success, live)
1336
  except Exception, err:  # pylint: disable=W0703
1337
    _Fail("Failed to finalize the migration on the source node: %s", err,
1338
          exc=True)
1339

    
1340

    
1341
def GetMigrationStatus(instance):
1342
  """Get the migration status
1343

1344
  @type instance: L{objects.Instance}
1345
  @param instance: the instance that is being migrated
1346
  @rtype: L{objects.MigrationStatus}
1347
  @return: the status of the current migration (one of
1348
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1349
           progress info that can be retrieved from the hypervisor
1350
  @raise RPCFail: If the migration status cannot be retrieved
1351

1352
  """
1353
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1354
  try:
1355
    return hyper.GetMigrationStatus(instance)
1356
  except Exception, err:  # pylint: disable=W0703
1357
    _Fail("Failed to get migration status: %s", err, exc=True)
1358

    
1359

    
1360
def BlockdevCreate(disk, size, owner, on_primary, info):
1361
  """Creates a block device for an instance.
1362

1363
  @type disk: L{objects.Disk}
1364
  @param disk: the object describing the disk we should create
1365
  @type size: int
1366
  @param size: the size of the physical underlying device, in MiB
1367
  @type owner: str
1368
  @param owner: the name of the instance for which disk is created,
1369
      used for device cache data
1370
  @type on_primary: boolean
1371
  @param on_primary:  indicates if it is the primary node or not
1372
  @type info: string
1373
  @param info: string that will be sent to the physical device
1374
      creation, used for example to set (LVM) tags on LVs
1375

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

1380
  """
1381
  # TODO: remove the obsolete "size" argument
1382
  # pylint: disable=W0613
1383
  clist = []
1384
  if disk.children:
1385
    for child in disk.children:
1386
      try:
1387
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1388
      except errors.BlockDeviceError, err:
1389
        _Fail("Can't assemble device %s: %s", child, err)
1390
      if on_primary or disk.AssembleOnSecondary():
1391
        # we need the children open in case the device itself has to
1392
        # be assembled
1393
        try:
1394
          # pylint: disable=E1103
1395
          crdev.Open()
1396
        except errors.BlockDeviceError, err:
1397
          _Fail("Can't make child '%s' read-write: %s", child, err)
1398
      clist.append(crdev)
1399

    
1400
  try:
1401
    device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
1402
  except errors.BlockDeviceError, err:
1403
    _Fail("Can't create block device: %s", err)
1404

    
1405
  if on_primary or disk.AssembleOnSecondary():
1406
    try:
1407
      device.Assemble()
1408
    except errors.BlockDeviceError, err:
1409
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1410
    device.SetSyncSpeed(constants.SYNC_SPEED)
1411
    if on_primary or disk.OpenOnSecondary():
1412
      try:
1413
        device.Open(force=True)
1414
      except errors.BlockDeviceError, err:
1415
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1416
    DevCacheManager.UpdateCache(device.dev_path, owner,
1417
                                on_primary, disk.iv_name)
1418

    
1419
  device.SetInfo(info)
1420

    
1421
  return device.unique_id
1422

    
1423

    
1424
def _WipeDevice(path, offset, size):
1425
  """This function actually wipes the device.
1426

1427
  @param path: The path to the device to wipe
1428
  @param offset: The offset in MiB in the file
1429
  @param size: The size in MiB to write
1430

1431
  """
1432
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1433
         "bs=%d" % constants.WIPE_BLOCK_SIZE, "oflag=direct", "of=%s" % path,
1434
         "count=%d" % size]
1435
  result = utils.RunCmd(cmd)
1436

    
1437
  if result.failed:
1438
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1439
          result.fail_reason, result.output)
1440

    
1441

    
1442
def BlockdevWipe(disk, offset, size):
1443
  """Wipes a block device.
1444

1445
  @type disk: L{objects.Disk}
1446
  @param disk: the disk object we want to wipe
1447
  @type offset: int
1448
  @param offset: The offset in MiB in the file
1449
  @type size: int
1450
  @param size: The size in MiB to write
1451

1452
  """
1453
  try:
1454
    rdev = _RecursiveFindBD(disk)
1455
  except errors.BlockDeviceError:
1456
    rdev = None
1457

    
1458
  if not rdev:
1459
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1460

    
1461
  # Do cross verify some of the parameters
1462
  if offset > rdev.size:
1463
    _Fail("Offset is bigger than device size")
1464
  if (offset + size) > rdev.size:
1465
    _Fail("The provided offset and size to wipe is bigger than device size")
1466

    
1467
  _WipeDevice(rdev.dev_path, offset, size)
1468

    
1469

    
1470
def BlockdevPauseResumeSync(disks, pause):
1471
  """Pause or resume the sync of the block device.
1472

1473
  @type disks: list of L{objects.Disk}
1474
  @param disks: the disks object we want to pause/resume
1475
  @type pause: bool
1476
  @param pause: Wheater to pause or resume
1477

1478
  """
1479
  success = []
1480
  for disk in disks:
1481
    try:
1482
      rdev = _RecursiveFindBD(disk)
1483
    except errors.BlockDeviceError:
1484
      rdev = None
1485

    
1486
    if not rdev:
1487
      success.append((False, ("Cannot change sync for device %s:"
1488
                              " device not found" % disk.iv_name)))
1489
      continue
1490

    
1491
    result = rdev.PauseResumeSync(pause)
1492

    
1493
    if result:
1494
      success.append((result, None))
1495
    else:
1496
      if pause:
1497
        msg = "Pause"
1498
      else:
1499
        msg = "Resume"
1500
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1501

    
1502
  return success
1503

    
1504

    
1505
def BlockdevRemove(disk):
1506
  """Remove a block device.
1507

1508
  @note: This is intended to be called recursively.
1509

1510
  @type disk: L{objects.Disk}
1511
  @param disk: the disk object we should remove
1512
  @rtype: boolean
1513
  @return: the success of the operation
1514

1515
  """
1516
  msgs = []
1517
  try:
1518
    rdev = _RecursiveFindBD(disk)
1519
  except errors.BlockDeviceError, err:
1520
    # probably can't attach
1521
    logging.info("Can't attach to device %s in remove", disk)
1522
    rdev = None
1523
  if rdev is not None:
1524
    r_path = rdev.dev_path
1525
    try:
1526
      rdev.Remove()
1527
    except errors.BlockDeviceError, err:
1528
      msgs.append(str(err))
1529
    if not msgs:
1530
      DevCacheManager.RemoveCache(r_path)
1531

    
1532
  if disk.children:
1533
    for child in disk.children:
1534
      try:
1535
        BlockdevRemove(child)
1536
      except RPCFail, err:
1537
        msgs.append(str(err))
1538

    
1539
  if msgs:
1540
    _Fail("; ".join(msgs))
1541

    
1542

    
1543
def _RecursiveAssembleBD(disk, owner, as_primary):
1544
  """Activate a block device for an instance.
1545

1546
  This is run on the primary and secondary nodes for an instance.
1547

1548
  @note: this function is called recursively.
1549

1550
  @type disk: L{objects.Disk}
1551
  @param disk: the disk we try to assemble
1552
  @type owner: str
1553
  @param owner: the name of the instance which owns the disk
1554
  @type as_primary: boolean
1555
  @param as_primary: if we should make the block device
1556
      read/write
1557

1558
  @return: the assembled device or None (in case no device
1559
      was assembled)
1560
  @raise errors.BlockDeviceError: in case there is an error
1561
      during the activation of the children or the device
1562
      itself
1563

1564
  """
1565
  children = []
1566
  if disk.children:
1567
    mcn = disk.ChildrenNeeded()
1568
    if mcn == -1:
1569
      mcn = 0 # max number of Nones allowed
1570
    else:
1571
      mcn = len(disk.children) - mcn # max number of Nones
1572
    for chld_disk in disk.children:
1573
      try:
1574
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1575
      except errors.BlockDeviceError, err:
1576
        if children.count(None) >= mcn:
1577
          raise
1578
        cdev = None
1579
        logging.error("Error in child activation (but continuing): %s",
1580
                      str(err))
1581
      children.append(cdev)
1582

    
1583
  if as_primary or disk.AssembleOnSecondary():
1584
    r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
1585
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1586
    result = r_dev
1587
    if as_primary or disk.OpenOnSecondary():
1588
      r_dev.Open()
1589
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1590
                                as_primary, disk.iv_name)
1591

    
1592
  else:
1593
    result = True
1594
  return result
1595

    
1596

    
1597
def BlockdevAssemble(disk, owner, as_primary, idx):
1598
  """Activate a block device for an instance.
1599

1600
  This is a wrapper over _RecursiveAssembleBD.
1601

1602
  @rtype: str or boolean
1603
  @return: a C{/dev/...} path for primary nodes, and
1604
      C{True} for secondary nodes
1605

1606
  """
1607
  try:
1608
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1609
    if isinstance(result, bdev.BlockDev):
1610
      # pylint: disable=E1103
1611
      result = result.dev_path
1612
      if as_primary:
1613
        _SymlinkBlockDev(owner, result, idx)
1614
  except errors.BlockDeviceError, err:
1615
    _Fail("Error while assembling disk: %s", err, exc=True)
1616
  except OSError, err:
1617
    _Fail("Error while symlinking disk: %s", err, exc=True)
1618

    
1619
  return result
1620

    
1621

    
1622
def BlockdevShutdown(disk):
1623
  """Shut down a block device.
1624

1625
  First, if the device is assembled (Attach() is successful), then
1626
  the device is shutdown. Then the children of the device are
1627
  shutdown.
1628

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

1633
  @type disk: L{objects.Disk}
1634
  @param disk: the description of the disk we should
1635
      shutdown
1636
  @rtype: None
1637

1638
  """
1639
  msgs = []
1640
  r_dev = _RecursiveFindBD(disk)
1641
  if r_dev is not None:
1642
    r_path = r_dev.dev_path
1643
    try:
1644
      r_dev.Shutdown()
1645
      DevCacheManager.RemoveCache(r_path)
1646
    except errors.BlockDeviceError, err:
1647
      msgs.append(str(err))
1648

    
1649
  if disk.children:
1650
    for child in disk.children:
1651
      try:
1652
        BlockdevShutdown(child)
1653
      except RPCFail, err:
1654
        msgs.append(str(err))
1655

    
1656
  if msgs:
1657
    _Fail("; ".join(msgs))
1658

    
1659

    
1660
def BlockdevAddchildren(parent_cdev, new_cdevs):
1661
  """Extend a mirrored block device.
1662

1663
  @type parent_cdev: L{objects.Disk}
1664
  @param parent_cdev: the disk to which we should add children
1665
  @type new_cdevs: list of L{objects.Disk}
1666
  @param new_cdevs: the list of children which we should add
1667
  @rtype: None
1668

1669
  """
1670
  parent_bdev = _RecursiveFindBD(parent_cdev)
1671
  if parent_bdev is None:
1672
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1673
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1674
  if new_bdevs.count(None) > 0:
1675
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1676
  parent_bdev.AddChildren(new_bdevs)
1677

    
1678

    
1679
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1680
  """Shrink a mirrored block device.
1681

1682
  @type parent_cdev: L{objects.Disk}
1683
  @param parent_cdev: the disk from which we should remove children
1684
  @type new_cdevs: list of L{objects.Disk}
1685
  @param new_cdevs: the list of children which we should remove
1686
  @rtype: None
1687

1688
  """
1689
  parent_bdev = _RecursiveFindBD(parent_cdev)
1690
  if parent_bdev is None:
1691
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1692
  devs = []
1693
  for disk in new_cdevs:
1694
    rpath = disk.StaticDevPath()
1695
    if rpath is None:
1696
      bd = _RecursiveFindBD(disk)
1697
      if bd is None:
1698
        _Fail("Can't find device %s while removing children", disk)
1699
      else:
1700
        devs.append(bd.dev_path)
1701
    else:
1702
      if not utils.IsNormAbsPath(rpath):
1703
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
1704
      devs.append(rpath)
1705
  parent_bdev.RemoveChildren(devs)
1706

    
1707

    
1708
def BlockdevGetmirrorstatus(disks):
1709
  """Get the mirroring status of a list of devices.
1710

1711
  @type disks: list of L{objects.Disk}
1712
  @param disks: the list of disks which we should query
1713
  @rtype: disk
1714
  @return: List of L{objects.BlockDevStatus}, one for each disk
1715
  @raise errors.BlockDeviceError: if any of the disks cannot be
1716
      found
1717

1718
  """
1719
  stats = []
1720
  for dsk in disks:
1721
    rbd = _RecursiveFindBD(dsk)
1722
    if rbd is None:
1723
      _Fail("Can't find device %s", dsk)
1724

    
1725
    stats.append(rbd.CombinedSyncStatus())
1726

    
1727
  return stats
1728

    
1729

    
1730
def BlockdevGetmirrorstatusMulti(disks):
1731
  """Get the mirroring status of a list of devices.
1732

1733
  @type disks: list of L{objects.Disk}
1734
  @param disks: the list of disks which we should query
1735
  @rtype: disk
1736
  @return: List of tuples, (bool, status), one for each disk; bool denotes
1737
    success/failure, status is L{objects.BlockDevStatus} on success, string
1738
    otherwise
1739

1740
  """
1741
  result = []
1742
  for disk in disks:
1743
    try:
1744
      rbd = _RecursiveFindBD(disk)
1745
      if rbd is None:
1746
        result.append((False, "Can't find device %s" % disk))
1747
        continue
1748

    
1749
      status = rbd.CombinedSyncStatus()
1750
    except errors.BlockDeviceError, err:
1751
      logging.exception("Error while getting disk status")
1752
      result.append((False, str(err)))
1753
    else:
1754
      result.append((True, status))
1755

    
1756
  assert len(disks) == len(result)
1757

    
1758
  return result
1759

    
1760

    
1761
def _RecursiveFindBD(disk):
1762
  """Check if a device is activated.
1763

1764
  If so, return information about the real device.
1765

1766
  @type disk: L{objects.Disk}
1767
  @param disk: the disk object we need to find
1768

1769
  @return: None if the device can't be found,
1770
      otherwise the device instance
1771

1772
  """
1773
  children = []
1774
  if disk.children:
1775
    for chdisk in disk.children:
1776
      children.append(_RecursiveFindBD(chdisk))
1777

    
1778
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1779

    
1780

    
1781
def _OpenRealBD(disk):
1782
  """Opens the underlying block device of a disk.
1783

1784
  @type disk: L{objects.Disk}
1785
  @param disk: the disk object we want to open
1786

1787
  """
1788
  real_disk = _RecursiveFindBD(disk)
1789
  if real_disk is None:
1790
    _Fail("Block device '%s' is not set up", disk)
1791

    
1792
  real_disk.Open()
1793

    
1794
  return real_disk
1795

    
1796

    
1797
def BlockdevFind(disk):
1798
  """Check if a device is activated.
1799

1800
  If it is, return information about the real device.
1801

1802
  @type disk: L{objects.Disk}
1803
  @param disk: the disk to find
1804
  @rtype: None or objects.BlockDevStatus
1805
  @return: None if the disk cannot be found, otherwise a the current
1806
           information
1807

1808
  """
1809
  try:
1810
    rbd = _RecursiveFindBD(disk)
1811
  except errors.BlockDeviceError, err:
1812
    _Fail("Failed to find device: %s", err, exc=True)
1813

    
1814
  if rbd is None:
1815
    return None
1816

    
1817
  return rbd.GetSyncStatus()
1818

    
1819

    
1820
def BlockdevGetsize(disks):
1821
  """Computes the size of the given disks.
1822

1823
  If a disk is not found, returns None instead.
1824

1825
  @type disks: list of L{objects.Disk}
1826
  @param disks: the list of disk to compute the size for
1827
  @rtype: list
1828
  @return: list with elements None if the disk cannot be found,
1829
      otherwise the size
1830

1831
  """
1832
  result = []
1833
  for cf in disks:
1834
    try:
1835
      rbd = _RecursiveFindBD(cf)
1836
    except errors.BlockDeviceError:
1837
      result.append(None)
1838
      continue
1839
    if rbd is None:
1840
      result.append(None)
1841
    else:
1842
      result.append(rbd.GetActualSize())
1843
  return result
1844

    
1845

    
1846
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
1847
  """Export a block device to a remote node.
1848

1849
  @type disk: L{objects.Disk}
1850
  @param disk: the description of the disk to export
1851
  @type dest_node: str
1852
  @param dest_node: the destination node to export to
1853
  @type dest_path: str
1854
  @param dest_path: the destination path on the target node
1855
  @type cluster_name: str
1856
  @param cluster_name: the cluster name, needed for SSH hostalias
1857
  @rtype: None
1858

1859
  """
1860
  real_disk = _OpenRealBD(disk)
1861

    
1862
  # the block size on the read dd is 1MiB to match our units
1863
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
1864
                               "dd if=%s bs=1048576 count=%s",
1865
                               real_disk.dev_path, str(disk.size))
1866

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

    
1876
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1877
                                                   constants.GANETI_RUNAS,
1878
                                                   destcmd)
1879

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

    
1883
  result = utils.RunCmd(["bash", "-c", command])
1884

    
1885
  if result.failed:
1886
    _Fail("Disk copy command '%s' returned error: %s"
1887
          " output: %s", command, result.fail_reason, result.output)
1888

    
1889

    
1890
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1891
  """Write a file to the filesystem.
1892

1893
  This allows the master to overwrite(!) a file. It will only perform
1894
  the operation if the file belongs to a list of configuration files.
1895

1896
  @type file_name: str
1897
  @param file_name: the target file name
1898
  @type data: str
1899
  @param data: the new contents of the file
1900
  @type mode: int
1901
  @param mode: the mode to give the file (can be None)
1902
  @type uid: string
1903
  @param uid: the owner of the file
1904
  @type gid: string
1905
  @param gid: the group of the file
1906
  @type atime: float
1907
  @param atime: the atime to set on the file (can be None)
1908
  @type mtime: float
1909
  @param mtime: the mtime to set on the file (can be None)
1910
  @rtype: None
1911

1912
  """
1913
  if not os.path.isabs(file_name):
1914
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
1915

    
1916
  if file_name not in _ALLOWED_UPLOAD_FILES:
1917
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
1918
          file_name)
1919

    
1920
  raw_data = _Decompress(data)
1921

    
1922
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
1923
    _Fail("Invalid username/groupname type")
1924

    
1925
  getents = runtime.GetEnts()
1926
  uid = getents.LookupUser(uid)
1927
  gid = getents.LookupGroup(gid)
1928

    
1929
  utils.SafeWriteFile(file_name, None,
1930
                      data=raw_data, mode=mode, uid=uid, gid=gid,
1931
                      atime=atime, mtime=mtime)
1932

    
1933

    
1934
def RunOob(oob_program, command, node, timeout):
1935
  """Executes oob_program with given command on given node.
1936

1937
  @param oob_program: The path to the executable oob_program
1938
  @param command: The command to invoke on oob_program
1939
  @param node: The node given as an argument to the program
1940
  @param timeout: Timeout after which we kill the oob program
1941

1942
  @return: stdout
1943
  @raise RPCFail: If execution fails for some reason
1944

1945
  """
1946
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
1947

    
1948
  if result.failed:
1949
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
1950
          result.fail_reason, result.output)
1951

    
1952
  return result.stdout
1953

    
1954

    
1955
def WriteSsconfFiles(values):
1956
  """Update all ssconf files.
1957

1958
  Wrapper around the SimpleStore.WriteFiles.
1959

1960
  """
1961
  ssconf.SimpleStore().WriteFiles(values)
1962

    
1963

    
1964
def _ErrnoOrStr(err):
1965
  """Format an EnvironmentError exception.
1966

1967
  If the L{err} argument has an errno attribute, it will be looked up
1968
  and converted into a textual C{E...} description. Otherwise the
1969
  string representation of the error will be returned.
1970

1971
  @type err: L{EnvironmentError}
1972
  @param err: the exception to format
1973

1974
  """
1975
  if hasattr(err, "errno"):
1976
    detail = errno.errorcode[err.errno]
1977
  else:
1978
    detail = str(err)
1979
  return detail
1980

    
1981

    
1982
def _OSOndiskAPIVersion(os_dir):
1983
  """Compute and return the API version of a given OS.
1984

1985
  This function will try to read the API version of the OS residing in
1986
  the 'os_dir' directory.
1987

1988
  @type os_dir: str
1989
  @param os_dir: the directory in which we should look for the OS
1990
  @rtype: tuple
1991
  @return: tuple (status, data) with status denoting the validity and
1992
      data holding either the vaid versions or an error message
1993

1994
  """
1995
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
1996

    
1997
  try:
1998
    st = os.stat(api_file)
1999
  except EnvironmentError, err:
2000
    return False, ("Required file '%s' not found under path %s: %s" %
2001
                   (constants.OS_API_FILE, os_dir, _ErrnoOrStr(err)))
2002

    
2003
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2004
    return False, ("File '%s' in %s is not a regular file" %
2005
                   (constants.OS_API_FILE, os_dir))
2006

    
2007
  try:
2008
    api_versions = utils.ReadFile(api_file).splitlines()
2009
  except EnvironmentError, err:
2010
    return False, ("Error while reading the API version file at %s: %s" %
2011
                   (api_file, _ErrnoOrStr(err)))
2012

    
2013
  try:
2014
    api_versions = [int(version.strip()) for version in api_versions]
2015
  except (TypeError, ValueError), err:
2016
    return False, ("API version(s) can't be converted to integer: %s" %
2017
                   str(err))
2018

    
2019
  return True, api_versions
2020

    
2021

    
2022
def DiagnoseOS(top_dirs=None):
2023
  """Compute the validity for all OSes.
2024

2025
  @type top_dirs: list
2026
  @param top_dirs: the list of directories in which to
2027
      search (if not given defaults to
2028
      L{constants.OS_SEARCH_PATH})
2029
  @rtype: list of L{objects.OS}
2030
  @return: a list of tuples (name, path, status, diagnose, variants,
2031
      parameters, api_version) for all (potential) OSes under all
2032
      search paths, where:
2033
          - name is the (potential) OS name
2034
          - path is the full path to the OS
2035
          - status True/False is the validity of the OS
2036
          - diagnose is the error message for an invalid OS, otherwise empty
2037
          - variants is a list of supported OS variants, if any
2038
          - parameters is a list of (name, help) parameters, if any
2039
          - api_version is a list of support OS API versions
2040

2041
  """
2042
  if top_dirs is None:
2043
    top_dirs = constants.OS_SEARCH_PATH
2044

    
2045
  result = []
2046
  for dir_name in top_dirs:
2047
    if os.path.isdir(dir_name):
2048
      try:
2049
        f_names = utils.ListVisibleFiles(dir_name)
2050
      except EnvironmentError, err:
2051
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2052
        break
2053
      for name in f_names:
2054
        os_path = utils.PathJoin(dir_name, name)
2055
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2056
        if status:
2057
          diagnose = ""
2058
          variants = os_inst.supported_variants
2059
          parameters = os_inst.supported_parameters
2060
          api_versions = os_inst.api_versions
2061
        else:
2062
          diagnose = os_inst
2063
          variants = parameters = api_versions = []
2064
        result.append((name, os_path, status, diagnose, variants,
2065
                       parameters, api_versions))
2066

    
2067
  return result
2068

    
2069

    
2070
def _TryOSFromDisk(name, base_dir=None):
2071
  """Create an OS instance from disk.
2072

2073
  This function will return an OS instance if the given name is a
2074
  valid OS name.
2075

2076
  @type base_dir: string
2077
  @keyword base_dir: Base directory containing OS installations.
2078
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2079
  @rtype: tuple
2080
  @return: success and either the OS instance if we find a valid one,
2081
      or error message
2082

2083
  """
2084
  if base_dir is None:
2085
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
2086
  else:
2087
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2088

    
2089
  if os_dir is None:
2090
    return False, "Directory for OS %s not found in search path" % name
2091

    
2092
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2093
  if not status:
2094
    # push the error up
2095
    return status, api_versions
2096

    
2097
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2098
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2099
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2100

    
2101
  # OS Files dictionary, we will populate it with the absolute path
2102
  # names; if the value is True, then it is a required file, otherwise
2103
  # an optional one
2104
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2105

    
2106
  if max(api_versions) >= constants.OS_API_V15:
2107
    os_files[constants.OS_VARIANTS_FILE] = False
2108

    
2109
  if max(api_versions) >= constants.OS_API_V20:
2110
    os_files[constants.OS_PARAMETERS_FILE] = True
2111
  else:
2112
    del os_files[constants.OS_SCRIPT_VERIFY]
2113

    
2114
  for (filename, required) in os_files.items():
2115
    os_files[filename] = utils.PathJoin(os_dir, filename)
2116

    
2117
    try:
2118
      st = os.stat(os_files[filename])
2119
    except EnvironmentError, err:
2120
      if err.errno == errno.ENOENT and not required:
2121
        del os_files[filename]
2122
        continue
2123
      return False, ("File '%s' under path '%s' is missing (%s)" %
2124
                     (filename, os_dir, _ErrnoOrStr(err)))
2125

    
2126
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2127
      return False, ("File '%s' under path '%s' is not a regular file" %
2128
                     (filename, os_dir))
2129

    
2130
    if filename in constants.OS_SCRIPTS:
2131
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2132
        return False, ("File '%s' under path '%s' is not executable" %
2133
                       (filename, os_dir))
2134

    
2135
  variants = []
2136
  if constants.OS_VARIANTS_FILE in os_files:
2137
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2138
    try:
2139
      variants = utils.ReadFile(variants_file).splitlines()
2140
    except EnvironmentError, err:
2141
      # we accept missing files, but not other errors
2142
      if err.errno != errno.ENOENT:
2143
        return False, ("Error while reading the OS variants file at %s: %s" %
2144
                       (variants_file, _ErrnoOrStr(err)))
2145

    
2146
  parameters = []
2147
  if constants.OS_PARAMETERS_FILE in os_files:
2148
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2149
    try:
2150
      parameters = utils.ReadFile(parameters_file).splitlines()
2151
    except EnvironmentError, err:
2152
      return False, ("Error while reading the OS parameters file at %s: %s" %
2153
                     (parameters_file, _ErrnoOrStr(err)))
2154
    parameters = [v.split(None, 1) for v in parameters]
2155

    
2156
  os_obj = objects.OS(name=name, path=os_dir,
2157
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2158
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2159
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2160
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2161
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2162
                                                 None),
2163
                      supported_variants=variants,
2164
                      supported_parameters=parameters,
2165
                      api_versions=api_versions)
2166
  return True, os_obj
2167

    
2168

    
2169
def OSFromDisk(name, base_dir=None):
2170
  """Create an OS instance from disk.
2171

2172
  This function will return an OS instance if the given name is a
2173
  valid OS name. Otherwise, it will raise an appropriate
2174
  L{RPCFail} exception, detailing why this is not a valid OS.
2175

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

2179
  @type base_dir: string
2180
  @keyword base_dir: Base directory containing OS installations.
2181
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2182
  @rtype: L{objects.OS}
2183
  @return: the OS instance if we find a valid one
2184
  @raise RPCFail: if we don't find a valid OS
2185

2186
  """
2187
  name_only = objects.OS.GetName(name)
2188
  status, payload = _TryOSFromDisk(name_only, base_dir)
2189

    
2190
  if not status:
2191
    _Fail(payload)
2192

    
2193
  return payload
2194

    
2195

    
2196
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2197
  """Calculate the basic environment for an os script.
2198

2199
  @type os_name: str
2200
  @param os_name: full operating system name (including variant)
2201
  @type inst_os: L{objects.OS}
2202
  @param inst_os: operating system for which the environment is being built
2203
  @type os_params: dict
2204
  @param os_params: the OS parameters
2205
  @type debug: integer
2206
  @param debug: debug level (0 or 1, for OS Api 10)
2207
  @rtype: dict
2208
  @return: dict of environment variables
2209
  @raise errors.BlockDeviceError: if the block device
2210
      cannot be found
2211

2212
  """
2213
  result = {}
2214
  api_version = \
2215
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2216
  result["OS_API_VERSION"] = "%d" % api_version
2217
  result["OS_NAME"] = inst_os.name
2218
  result["DEBUG_LEVEL"] = "%d" % debug
2219

    
2220
  # OS variants
2221
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2222
    variant = objects.OS.GetVariant(os_name)
2223
    if not variant:
2224
      variant = inst_os.supported_variants[0]
2225
  else:
2226
    variant = ""
2227
  result["OS_VARIANT"] = variant
2228

    
2229
  # OS params
2230
  for pname, pvalue in os_params.items():
2231
    result["OSP_%s" % pname.upper()] = pvalue
2232

    
2233
  return result
2234

    
2235

    
2236
def OSEnvironment(instance, inst_os, debug=0):
2237
  """Calculate the environment for an os script.
2238

2239
  @type instance: L{objects.Instance}
2240
  @param instance: target instance for the os script run
2241
  @type inst_os: L{objects.OS}
2242
  @param inst_os: operating system for which the environment is being built
2243
  @type debug: integer
2244
  @param debug: debug level (0 or 1, for OS Api 10)
2245
  @rtype: dict
2246
  @return: dict of environment variables
2247
  @raise errors.BlockDeviceError: if the block device
2248
      cannot be found
2249

2250
  """
2251
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2252

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

    
2256
  result["HYPERVISOR"] = instance.hypervisor
2257
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2258
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2259
  result["INSTANCE_SECONDARY_NODES"] = \
2260
      ("%s" % " ".join(instance.secondary_nodes))
2261

    
2262
  # Disks
2263
  for idx, disk in enumerate(instance.disks):
2264
    real_disk = _OpenRealBD(disk)
2265
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2266
    result["DISK_%d_ACCESS" % idx] = disk.mode
2267
    if constants.HV_DISK_TYPE in instance.hvparams:
2268
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2269
        instance.hvparams[constants.HV_DISK_TYPE]
2270
    if disk.dev_type in constants.LDS_BLOCK:
2271
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2272
    elif disk.dev_type == constants.LD_FILE:
2273
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2274
        "file:%s" % disk.physical_id[0]
2275

    
2276
  # NICs
2277
  for idx, nic in enumerate(instance.nics):
2278
    result["NIC_%d_MAC" % idx] = nic.mac
2279
    if nic.ip:
2280
      result["NIC_%d_IP" % idx] = nic.ip
2281
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2282
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2283
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2284
    if nic.nicparams[constants.NIC_LINK]:
2285
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2286
    if constants.HV_NIC_TYPE in instance.hvparams:
2287
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2288
        instance.hvparams[constants.HV_NIC_TYPE]
2289

    
2290
  # HV/BE params
2291
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2292
    for key, value in source.items():
2293
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2294

    
2295
  return result
2296

    
2297

    
2298
def BlockdevGrow(disk, amount, dryrun):
2299
  """Grow a stack of block devices.
2300

2301
  This function is called recursively, with the childrens being the
2302
  first ones to resize.
2303

2304
  @type disk: L{objects.Disk}
2305
  @param disk: the disk to be grown
2306
  @type amount: integer
2307
  @param amount: the amount (in mebibytes) to grow with
2308
  @type dryrun: boolean
2309
  @param dryrun: whether to execute the operation in simulation mode
2310
      only, without actually increasing the size
2311
  @rtype: (status, result)
2312
  @return: a tuple with the status of the operation (True/False), and
2313
      the errors message if status is False
2314

2315
  """
2316
  r_dev = _RecursiveFindBD(disk)
2317
  if r_dev is None:
2318
    _Fail("Cannot find block device %s", disk)
2319

    
2320
  try:
2321
    r_dev.Grow(amount, dryrun)
2322
  except errors.BlockDeviceError, err:
2323
    _Fail("Failed to grow block device: %s", err, exc=True)
2324

    
2325

    
2326
def BlockdevSnapshot(disk):
2327
  """Create a snapshot copy of a block device.
2328

2329
  This function is called recursively, and the snapshot is actually created
2330
  just for the leaf lvm backend device.
2331

2332
  @type disk: L{objects.Disk}
2333
  @param disk: the disk to be snapshotted
2334
  @rtype: string
2335
  @return: snapshot disk ID as (vg, lv)
2336

2337
  """
2338
  if disk.dev_type == constants.LD_DRBD8:
2339
    if not disk.children:
2340
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2341
            disk.unique_id)
2342
    return BlockdevSnapshot(disk.children[0])
2343
  elif disk.dev_type == constants.LD_LV:
2344
    r_dev = _RecursiveFindBD(disk)
2345
    if r_dev is not None:
2346
      # FIXME: choose a saner value for the snapshot size
2347
      # let's stay on the safe side and ask for the full size, for now
2348
      return r_dev.Snapshot(disk.size)
2349
    else:
2350
      _Fail("Cannot find block device %s", disk)
2351
  else:
2352
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2353
          disk.unique_id, disk.dev_type)
2354

    
2355

    
2356
def FinalizeExport(instance, snap_disks):
2357
  """Write out the export configuration information.
2358

2359
  @type instance: L{objects.Instance}
2360
  @param instance: the instance which we export, used for
2361
      saving configuration
2362
  @type snap_disks: list of L{objects.Disk}
2363
  @param snap_disks: list of snapshot block devices, which
2364
      will be used to get the actual name of the dump file
2365

2366
  @rtype: None
2367

2368
  """
2369
  destdir = utils.PathJoin(constants.EXPORT_DIR, instance.name + ".new")
2370
  finaldestdir = utils.PathJoin(constants.EXPORT_DIR, instance.name)
2371

    
2372
  config = objects.SerializableConfigParser()
2373

    
2374
  config.add_section(constants.INISECT_EXP)
2375
  config.set(constants.INISECT_EXP, "version", "0")
2376
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2377
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2378
  config.set(constants.INISECT_EXP, "os", instance.os)
2379
  config.set(constants.INISECT_EXP, "compression", "none")
2380

    
2381
  config.add_section(constants.INISECT_INS)
2382
  config.set(constants.INISECT_INS, "name", instance.name)
2383
  config.set(constants.INISECT_INS, "memory", "%d" %
2384
             instance.beparams[constants.BE_MEMORY])
2385
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2386
             instance.beparams[constants.BE_VCPUS])
2387
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2388
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2389
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2390

    
2391
  nic_total = 0
2392
  for nic_count, nic in enumerate(instance.nics):
2393
    nic_total += 1
2394
    config.set(constants.INISECT_INS, "nic%d_mac" %
2395
               nic_count, "%s" % nic.mac)
2396
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2397
    for param in constants.NICS_PARAMETER_TYPES:
2398
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2399
                 "%s" % nic.nicparams.get(param, None))
2400
  # TODO: redundant: on load can read nics until it doesn't exist
2401
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2402

    
2403
  disk_total = 0
2404
  for disk_count, disk in enumerate(snap_disks):
2405
    if disk:
2406
      disk_total += 1
2407
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2408
                 ("%s" % disk.iv_name))
2409
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2410
                 ("%s" % disk.physical_id[1]))
2411
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2412
                 ("%d" % disk.size))
2413

    
2414
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2415

    
2416
  # New-style hypervisor/backend parameters
2417

    
2418
  config.add_section(constants.INISECT_HYP)
2419
  for name, value in instance.hvparams.items():
2420
    if name not in constants.HVC_GLOBALS:
2421
      config.set(constants.INISECT_HYP, name, str(value))
2422

    
2423
  config.add_section(constants.INISECT_BEP)
2424
  for name, value in instance.beparams.items():
2425
    config.set(constants.INISECT_BEP, name, str(value))
2426

    
2427
  config.add_section(constants.INISECT_OSP)
2428
  for name, value in instance.osparams.items():
2429
    config.set(constants.INISECT_OSP, name, str(value))
2430

    
2431
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2432
                  data=config.Dumps())
2433
  shutil.rmtree(finaldestdir, ignore_errors=True)
2434
  shutil.move(destdir, finaldestdir)
2435

    
2436

    
2437
def ExportInfo(dest):
2438
  """Get export configuration information.
2439

2440
  @type dest: str
2441
  @param dest: directory containing the export
2442

2443
  @rtype: L{objects.SerializableConfigParser}
2444
  @return: a serializable config file containing the
2445
      export info
2446

2447
  """
2448
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2449

    
2450
  config = objects.SerializableConfigParser()
2451
  config.read(cff)
2452

    
2453
  if (not config.has_section(constants.INISECT_EXP) or
2454
      not config.has_section(constants.INISECT_INS)):
2455
    _Fail("Export info file doesn't have the required fields")
2456

    
2457
  return config.Dumps()
2458

    
2459

    
2460
def ListExports():
2461
  """Return a list of exports currently available on this machine.
2462

2463
  @rtype: list
2464
  @return: list of the exports
2465

2466
  """
2467
  if os.path.isdir(constants.EXPORT_DIR):
2468
    return sorted(utils.ListVisibleFiles(constants.EXPORT_DIR))
2469
  else:
2470
    _Fail("No exports directory")
2471

    
2472

    
2473
def RemoveExport(export):
2474
  """Remove an existing export from the node.
2475

2476
  @type export: str
2477
  @param export: the name of the export to remove
2478
  @rtype: None
2479

2480
  """
2481
  target = utils.PathJoin(constants.EXPORT_DIR, export)
2482

    
2483
  try:
2484
    shutil.rmtree(target)
2485
  except EnvironmentError, err:
2486
    _Fail("Error while removing the export: %s", err, exc=True)
2487

    
2488

    
2489
def BlockdevRename(devlist):
2490
  """Rename a list of block devices.
2491

2492
  @type devlist: list of tuples
2493
  @param devlist: list of tuples of the form  (disk,
2494
      new_logical_id, new_physical_id); disk is an
2495
      L{objects.Disk} object describing the current disk,
2496
      and new logical_id/physical_id is the name we
2497
      rename it to
2498
  @rtype: boolean
2499
  @return: True if all renames succeeded, False otherwise
2500

2501
  """
2502
  msgs = []
2503
  result = True
2504
  for disk, unique_id in devlist:
2505
    dev = _RecursiveFindBD(disk)
2506
    if dev is None:
2507
      msgs.append("Can't find device %s in rename" % str(disk))
2508
      result = False
2509
      continue
2510
    try:
2511
      old_rpath = dev.dev_path
2512
      dev.Rename(unique_id)
2513
      new_rpath = dev.dev_path
2514
      if old_rpath != new_rpath:
2515
        DevCacheManager.RemoveCache(old_rpath)
2516
        # FIXME: we should add the new cache information here, like:
2517
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2518
        # but we don't have the owner here - maybe parse from existing
2519
        # cache? for now, we only lose lvm data when we rename, which
2520
        # is less critical than DRBD or MD
2521
    except errors.BlockDeviceError, err:
2522
      msgs.append("Can't rename device '%s' to '%s': %s" %
2523
                  (dev, unique_id, err))
2524
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2525
      result = False
2526
  if not result:
2527
    _Fail("; ".join(msgs))
2528

    
2529

    
2530
def _TransformFileStorageDir(fs_dir):
2531
  """Checks whether given file_storage_dir is valid.
2532

2533
  Checks wheter the given fs_dir is within the cluster-wide default
2534
  file_storage_dir or the shared_file_storage_dir, which are stored in
2535
  SimpleStore. Only paths under those directories are allowed.
2536

2537
  @type fs_dir: str
2538
  @param fs_dir: the path to check
2539

2540
  @return: the normalized path if valid, None otherwise
2541

2542
  """
2543
  if not constants.ENABLE_FILE_STORAGE:
2544
    _Fail("File storage disabled at configure time")
2545
  cfg = _GetConfig()
2546
  fs_dir = os.path.normpath(fs_dir)
2547
  base_fstore = cfg.GetFileStorageDir()
2548
  base_shared = cfg.GetSharedFileStorageDir()
2549
  if not (utils.IsBelowDir(base_fstore, fs_dir) or
2550
          utils.IsBelowDir(base_shared, fs_dir)):
2551
    _Fail("File storage directory '%s' is not under base file"
2552
          " storage directory '%s' or shared storage directory '%s'",
2553
          fs_dir, base_fstore, base_shared)
2554
  return fs_dir
2555

    
2556

    
2557
def CreateFileStorageDir(file_storage_dir):
2558
  """Create file storage directory.
2559

2560
  @type file_storage_dir: str
2561
  @param file_storage_dir: directory to create
2562

2563
  @rtype: tuple
2564
  @return: tuple with first element a boolean indicating wheter dir
2565
      creation was successful or not
2566

2567
  """
2568
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2569
  if os.path.exists(file_storage_dir):
2570
    if not os.path.isdir(file_storage_dir):
2571
      _Fail("Specified storage dir '%s' is not a directory",
2572
            file_storage_dir)
2573
  else:
2574
    try:
2575
      os.makedirs(file_storage_dir, 0750)
2576
    except OSError, err:
2577
      _Fail("Cannot create file storage directory '%s': %s",
2578
            file_storage_dir, err, exc=True)
2579

    
2580

    
2581
def RemoveFileStorageDir(file_storage_dir):
2582
  """Remove file storage directory.
2583

2584
  Remove it only if it's empty. If not log an error and return.
2585

2586
  @type file_storage_dir: str
2587
  @param file_storage_dir: the directory we should cleanup
2588
  @rtype: tuple (success,)
2589
  @return: tuple of one element, C{success}, denoting
2590
      whether the operation was successful
2591

2592
  """
2593
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2594
  if os.path.exists(file_storage_dir):
2595
    if not os.path.isdir(file_storage_dir):
2596
      _Fail("Specified Storage directory '%s' is not a directory",
2597
            file_storage_dir)
2598
    # deletes dir only if empty, otherwise we want to fail the rpc call
2599
    try:
2600
      os.rmdir(file_storage_dir)
2601
    except OSError, err:
2602
      _Fail("Cannot remove file storage directory '%s': %s",
2603
            file_storage_dir, err)
2604

    
2605

    
2606
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2607
  """Rename the file storage directory.
2608

2609
  @type old_file_storage_dir: str
2610
  @param old_file_storage_dir: the current path
2611
  @type new_file_storage_dir: str
2612
  @param new_file_storage_dir: the name we should rename to
2613
  @rtype: tuple (success,)
2614
  @return: tuple of one element, C{success}, denoting
2615
      whether the operation was successful
2616

2617
  """
2618
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2619
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2620
  if not os.path.exists(new_file_storage_dir):
2621
    if os.path.isdir(old_file_storage_dir):
2622
      try:
2623
        os.rename(old_file_storage_dir, new_file_storage_dir)
2624
      except OSError, err:
2625
        _Fail("Cannot rename '%s' to '%s': %s",
2626
              old_file_storage_dir, new_file_storage_dir, err)
2627
    else:
2628
      _Fail("Specified storage dir '%s' is not a directory",
2629
            old_file_storage_dir)
2630
  else:
2631
    if os.path.exists(old_file_storage_dir):
2632
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2633
            old_file_storage_dir, new_file_storage_dir)
2634

    
2635

    
2636
def _EnsureJobQueueFile(file_name):
2637
  """Checks whether the given filename is in the queue directory.
2638

2639
  @type file_name: str
2640
  @param file_name: the file name we should check
2641
  @rtype: None
2642
  @raises RPCFail: if the file is not valid
2643

2644
  """
2645
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2646
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2647

    
2648
  if not result:
2649
    _Fail("Passed job queue file '%s' does not belong to"
2650
          " the queue directory '%s'", file_name, queue_dir)
2651

    
2652

    
2653
def JobQueueUpdate(file_name, content):
2654
  """Updates a file in the queue directory.
2655

2656
  This is just a wrapper over L{utils.io.WriteFile}, with proper
2657
  checking.
2658

2659
  @type file_name: str
2660
  @param file_name: the job file name
2661
  @type content: str
2662
  @param content: the new job contents
2663
  @rtype: boolean
2664
  @return: the success of the operation
2665

2666
  """
2667
  _EnsureJobQueueFile(file_name)
2668
  getents = runtime.GetEnts()
2669

    
2670
  # Write and replace the file atomically
2671
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
2672
                  gid=getents.masterd_gid)
2673

    
2674

    
2675
def JobQueueRename(old, new):
2676
  """Renames a job queue file.
2677

2678
  This is just a wrapper over os.rename with proper checking.
2679

2680
  @type old: str
2681
  @param old: the old (actual) file name
2682
  @type new: str
2683
  @param new: the desired file name
2684
  @rtype: tuple
2685
  @return: the success of the operation and payload
2686

2687
  """
2688
  _EnsureJobQueueFile(old)
2689
  _EnsureJobQueueFile(new)
2690

    
2691
  utils.RenameFile(old, new, mkdir=True)
2692

    
2693

    
2694
def BlockdevClose(instance_name, disks):
2695
  """Closes the given block devices.
2696

2697
  This means they will be switched to secondary mode (in case of
2698
  DRBD).
2699

2700
  @param instance_name: if the argument is not empty, the symlinks
2701
      of this instance will be removed
2702
  @type disks: list of L{objects.Disk}
2703
  @param disks: the list of disks to be closed
2704
  @rtype: tuple (success, message)
2705
  @return: a tuple of success and message, where success
2706
      indicates the succes of the operation, and message
2707
      which will contain the error details in case we
2708
      failed
2709

2710
  """
2711
  bdevs = []
2712
  for cf in disks:
2713
    rd = _RecursiveFindBD(cf)
2714
    if rd is None:
2715
      _Fail("Can't find device %s", cf)
2716
    bdevs.append(rd)
2717

    
2718
  msg = []
2719
  for rd in bdevs:
2720
    try:
2721
      rd.Close()
2722
    except errors.BlockDeviceError, err:
2723
      msg.append(str(err))
2724
  if msg:
2725
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2726
  else:
2727
    if instance_name:
2728
      _RemoveBlockDevLinks(instance_name, disks)
2729

    
2730

    
2731
def ValidateHVParams(hvname, hvparams):
2732
  """Validates the given hypervisor parameters.
2733

2734
  @type hvname: string
2735
  @param hvname: the hypervisor name
2736
  @type hvparams: dict
2737
  @param hvparams: the hypervisor parameters to be validated
2738
  @rtype: None
2739

2740
  """
2741
  try:
2742
    hv_type = hypervisor.GetHypervisor(hvname)
2743
    hv_type.ValidateParameters(hvparams)
2744
  except errors.HypervisorError, err:
2745
    _Fail(str(err), log=False)
2746

    
2747

    
2748
def _CheckOSPList(os_obj, parameters):
2749
  """Check whether a list of parameters is supported by the OS.
2750

2751
  @type os_obj: L{objects.OS}
2752
  @param os_obj: OS object to check
2753
  @type parameters: list
2754
  @param parameters: the list of parameters to check
2755

2756
  """
2757
  supported = [v[0] for v in os_obj.supported_parameters]
2758
  delta = frozenset(parameters).difference(supported)
2759
  if delta:
2760
    _Fail("The following parameters are not supported"
2761
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
2762

    
2763

    
2764
def ValidateOS(required, osname, checks, osparams):
2765
  """Validate the given OS' parameters.
2766

2767
  @type required: boolean
2768
  @param required: whether absence of the OS should translate into
2769
      failure or not
2770
  @type osname: string
2771
  @param osname: the OS to be validated
2772
  @type checks: list
2773
  @param checks: list of the checks to run (currently only 'parameters')
2774
  @type osparams: dict
2775
  @param osparams: dictionary with OS parameters
2776
  @rtype: boolean
2777
  @return: True if the validation passed, or False if the OS was not
2778
      found and L{required} was false
2779

2780
  """
2781
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
2782
    _Fail("Unknown checks required for OS %s: %s", osname,
2783
          set(checks).difference(constants.OS_VALIDATE_CALLS))
2784

    
2785
  name_only = objects.OS.GetName(osname)
2786
  status, tbv = _TryOSFromDisk(name_only, None)
2787

    
2788
  if not status:
2789
    if required:
2790
      _Fail(tbv)
2791
    else:
2792
      return False
2793

    
2794
  if max(tbv.api_versions) < constants.OS_API_V20:
2795
    return True
2796

    
2797
  if constants.OS_VALIDATE_PARAMETERS in checks:
2798
    _CheckOSPList(tbv, osparams.keys())
2799

    
2800
  validate_env = OSCoreEnv(osname, tbv, osparams)
2801
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
2802
                        cwd=tbv.path, reset_env=True)
2803
  if result.failed:
2804
    logging.error("os validate command '%s' returned error: %s output: %s",
2805
                  result.cmd, result.fail_reason, result.output)
2806
    _Fail("OS validation script failed (%s), output: %s",
2807
          result.fail_reason, result.output, log=False)
2808

    
2809
  return True
2810

    
2811

    
2812
def DemoteFromMC():
2813
  """Demotes the current node from master candidate role.
2814

2815
  """
2816
  # try to ensure we're not the master by mistake
2817
  master, myself = ssconf.GetMasterAndMyself()
2818
  if master == myself:
2819
    _Fail("ssconf status shows I'm the master node, will not demote")
2820

    
2821
  result = utils.RunCmd([constants.DAEMON_UTIL, "check", constants.MASTERD])
2822
  if not result.failed:
2823
    _Fail("The master daemon is running, will not demote")
2824

    
2825
  try:
2826
    if os.path.isfile(constants.CLUSTER_CONF_FILE):
2827
      utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2828
  except EnvironmentError, err:
2829
    if err.errno != errno.ENOENT:
2830
      _Fail("Error while backing up cluster file: %s", err, exc=True)
2831

    
2832
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2833

    
2834

    
2835
def _GetX509Filenames(cryptodir, name):
2836
  """Returns the full paths for the private key and certificate.
2837

2838
  """
2839
  return (utils.PathJoin(cryptodir, name),
2840
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
2841
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
2842

    
2843

    
2844
def CreateX509Certificate(validity, cryptodir=constants.CRYPTO_KEYS_DIR):
2845
  """Creates a new X509 certificate for SSL/TLS.
2846

2847
  @type validity: int
2848
  @param validity: Validity in seconds
2849
  @rtype: tuple; (string, string)
2850
  @return: Certificate name and public part
2851

2852
  """
2853
  (key_pem, cert_pem) = \
2854
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
2855
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
2856

    
2857
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
2858
                              prefix="x509-%s-" % utils.TimestampForFilename())
2859
  try:
2860
    name = os.path.basename(cert_dir)
2861
    assert len(name) > 5
2862

    
2863
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2864

    
2865
    utils.WriteFile(key_file, mode=0400, data=key_pem)
2866
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
2867

    
2868
    # Never return private key as it shouldn't leave the node
2869
    return (name, cert_pem)
2870
  except Exception:
2871
    shutil.rmtree(cert_dir, ignore_errors=True)
2872
    raise
2873

    
2874

    
2875
def RemoveX509Certificate(name, cryptodir=constants.CRYPTO_KEYS_DIR):
2876
  """Removes a X509 certificate.
2877

2878
  @type name: string
2879
  @param name: Certificate name
2880

2881
  """
2882
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2883

    
2884
  utils.RemoveFile(key_file)
2885
  utils.RemoveFile(cert_file)
2886

    
2887
  try:
2888
    os.rmdir(cert_dir)
2889
  except EnvironmentError, err:
2890
    _Fail("Cannot remove certificate directory '%s': %s",
2891
          cert_dir, err)
2892

    
2893

    
2894
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
2895
  """Returns the command for the requested input/output.
2896

2897
  @type instance: L{objects.Instance}
2898
  @param instance: The instance object
2899
  @param mode: Import/export mode
2900
  @param ieio: Input/output type
2901
  @param ieargs: Input/output arguments
2902

2903
  """
2904
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
2905

    
2906
  env = None
2907
  prefix = None
2908
  suffix = None
2909
  exp_size = None
2910

    
2911
  if ieio == constants.IEIO_FILE:
2912
    (filename, ) = ieargs
2913

    
2914
    if not utils.IsNormAbsPath(filename):
2915
      _Fail("Path '%s' is not normalized or absolute", filename)
2916

    
2917
    real_filename = os.path.realpath(filename)
2918
    directory = os.path.dirname(real_filename)
2919

    
2920
    if not utils.IsBelowDir(constants.EXPORT_DIR, real_filename):
2921
      _Fail("File '%s' is not under exports directory '%s': %s",
2922
            filename, constants.EXPORT_DIR, real_filename)
2923

    
2924
    # Create directory
2925
    utils.Makedirs(directory, mode=0750)
2926

    
2927
    quoted_filename = utils.ShellQuote(filename)
2928

    
2929
    if mode == constants.IEM_IMPORT:
2930
      suffix = "> %s" % quoted_filename
2931
    elif mode == constants.IEM_EXPORT:
2932
      suffix = "< %s" % quoted_filename
2933

    
2934
      # Retrieve file size
2935
      try:
2936
        st = os.stat(filename)
2937
      except EnvironmentError, err:
2938
        logging.error("Can't stat(2) %s: %s", filename, err)
2939
      else:
2940
        exp_size = utils.BytesToMebibyte(st.st_size)
2941

    
2942
  elif ieio == constants.IEIO_RAW_DISK:
2943
    (disk, ) = ieargs
2944

    
2945
    real_disk = _OpenRealBD(disk)
2946

    
2947
    if mode == constants.IEM_IMPORT:
2948
      # we set here a smaller block size as, due to transport buffering, more
2949
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
2950
      # is not already there or we pass a wrong path; we use notrunc to no
2951
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
2952
      # much memory; this means that at best, we flush every 64k, which will
2953
      # not be very fast
2954
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
2955
                                    " bs=%s oflag=dsync"),
2956
                                    real_disk.dev_path,
2957
                                    str(64 * 1024))
2958

    
2959
    elif mode == constants.IEM_EXPORT:
2960
      # the block size on the read dd is 1MiB to match our units
2961
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
2962
                                   real_disk.dev_path,
2963
                                   str(1024 * 1024), # 1 MB
2964
                                   str(disk.size))
2965
      exp_size = disk.size
2966

    
2967
  elif ieio == constants.IEIO_SCRIPT:
2968
    (disk, disk_index, ) = ieargs
2969

    
2970
    assert isinstance(disk_index, (int, long))
2971

    
2972
    real_disk = _OpenRealBD(disk)
2973

    
2974
    inst_os = OSFromDisk(instance.os)
2975
    env = OSEnvironment(instance, inst_os)
2976

    
2977
    if mode == constants.IEM_IMPORT:
2978
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
2979
      env["IMPORT_INDEX"] = str(disk_index)
2980
      script = inst_os.import_script
2981

    
2982
    elif mode == constants.IEM_EXPORT:
2983
      env["EXPORT_DEVICE"] = real_disk.dev_path
2984
      env["EXPORT_INDEX"] = str(disk_index)
2985
      script = inst_os.export_script
2986

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

    
2990
    if mode == constants.IEM_IMPORT:
2991
      suffix = "| %s" % script_cmd
2992

    
2993
    elif mode == constants.IEM_EXPORT:
2994
      prefix = "%s |" % script_cmd
2995

    
2996
    # Let script predict size
2997
    exp_size = constants.IE_CUSTOM_SIZE
2998

    
2999
  else:
3000
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3001

    
3002
  return (env, prefix, suffix, exp_size)
3003

    
3004

    
3005
def _CreateImportExportStatusDir(prefix):
3006
  """Creates status directory for import/export.
3007

3008
  """
3009
  return tempfile.mkdtemp(dir=constants.IMPORT_EXPORT_DIR,
3010
                          prefix=("%s-%s-" %
3011
                                  (prefix, utils.TimestampForFilename())))
3012

    
3013

    
3014
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3015
                            ieio, ieioargs):
3016
  """Starts an import or export daemon.
3017

3018
  @param mode: Import/output mode
3019
  @type opts: L{objects.ImportExportOptions}
3020
  @param opts: Daemon options
3021
  @type host: string
3022
  @param host: Remote host for export (None for import)
3023
  @type port: int
3024
  @param port: Remote port for export (None for import)
3025
  @type instance: L{objects.Instance}
3026
  @param instance: Instance object
3027
  @type component: string
3028
  @param component: which part of the instance is transferred now,
3029
      e.g. 'disk/0'
3030
  @param ieio: Input/output type
3031
  @param ieioargs: Input/output arguments
3032

3033
  """
3034
  if mode == constants.IEM_IMPORT:
3035
    prefix = "import"
3036

    
3037
    if not (host is None and port is None):
3038
      _Fail("Can not specify host or port on import")
3039

    
3040
  elif mode == constants.IEM_EXPORT:
3041
    prefix = "export"
3042

    
3043
    if host is None or port is None:
3044
      _Fail("Host and port must be specified for an export")
3045

    
3046
  else:
3047
    _Fail("Invalid mode %r", mode)
3048

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

    
3052
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3053
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3054

    
3055
  if opts.key_name is None:
3056
    # Use server.pem
3057
    key_path = constants.NODED_CERT_FILE
3058
    cert_path = constants.NODED_CERT_FILE
3059
    assert opts.ca_pem is None
3060
  else:
3061
    (_, key_path, cert_path) = _GetX509Filenames(constants.CRYPTO_KEYS_DIR,
3062
                                                 opts.key_name)
3063
    assert opts.ca_pem is not None
3064

    
3065
  for i in [key_path, cert_path]:
3066
    if not os.path.exists(i):
3067
      _Fail("File '%s' does not exist" % i)
3068

    
3069
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3070
  try:
3071
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3072
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3073
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3074

    
3075
    if opts.ca_pem is None:
3076
      # Use server.pem
3077
      ca = utils.ReadFile(constants.NODED_CERT_FILE)
3078
    else:
3079
      ca = opts.ca_pem
3080

    
3081
    # Write CA file
3082
    utils.WriteFile(ca_file, data=ca, mode=0400)
3083

    
3084
    cmd = [
3085
      constants.IMPORT_EXPORT_DAEMON,
3086
      status_file, mode,
3087
      "--key=%s" % key_path,
3088
      "--cert=%s" % cert_path,
3089
      "--ca=%s" % ca_file,
3090
      ]
3091

    
3092
    if host:
3093
      cmd.append("--host=%s" % host)
3094

    
3095
    if port:
3096
      cmd.append("--port=%s" % port)
3097

    
3098
    if opts.ipv6:
3099
      cmd.append("--ipv6")
3100
    else:
3101
      cmd.append("--ipv4")
3102

    
3103
    if opts.compress:
3104
      cmd.append("--compress=%s" % opts.compress)
3105

    
3106
    if opts.magic:
3107
      cmd.append("--magic=%s" % opts.magic)
3108

    
3109
    if exp_size is not None:
3110
      cmd.append("--expected-size=%s" % exp_size)
3111

    
3112
    if cmd_prefix:
3113
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3114

    
3115
    if cmd_suffix:
3116
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3117

    
3118
    if mode == constants.IEM_EXPORT:
3119
      # Retry connection a few times when connecting to remote peer
3120
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3121
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3122
    elif opts.connect_timeout is not None:
3123
      assert mode == constants.IEM_IMPORT
3124
      # Overall timeout for establishing connection while listening
3125
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3126

    
3127
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3128

    
3129
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3130
    # support for receiving a file descriptor for output
3131
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3132
                      output=logfile)
3133

    
3134
    # The import/export name is simply the status directory name
3135
    return os.path.basename(status_dir)
3136

    
3137
  except Exception:
3138
    shutil.rmtree(status_dir, ignore_errors=True)
3139
    raise
3140

    
3141

    
3142
def GetImportExportStatus(names):
3143
  """Returns import/export daemon status.
3144

3145
  @type names: sequence
3146
  @param names: List of names
3147
  @rtype: List of dicts
3148
  @return: Returns a list of the state of each named import/export or None if a
3149
           status couldn't be read
3150

3151
  """
3152
  result = []
3153

    
3154
  for name in names:
3155
    status_file = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name,
3156
                                 _IES_STATUS_FILE)
3157

    
3158
    try:
3159
      data = utils.ReadFile(status_file)
3160
    except EnvironmentError, err:
3161
      if err.errno != errno.ENOENT:
3162
        raise
3163
      data = None
3164

    
3165
    if not data:
3166
      result.append(None)
3167
      continue
3168

    
3169
    result.append(serializer.LoadJson(data))
3170

    
3171
  return result
3172

    
3173

    
3174
def AbortImportExport(name):
3175
  """Sends SIGTERM to a running import/export daemon.
3176

3177
  """
3178
  logging.info("Abort import/export %s", name)
3179

    
3180
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3181
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3182

    
3183
  if pid:
3184
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3185
                 name, pid)
3186
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3187

    
3188

    
3189
def CleanupImportExport(name):
3190
  """Cleanup after an import or export.
3191

3192
  If the import/export daemon is still running it's killed. Afterwards the
3193
  whole status directory is removed.
3194

3195
  """
3196
  logging.info("Finalizing import/export %s", name)
3197

    
3198
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3199

    
3200
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3201

    
3202
  if pid:
3203
    logging.info("Import/export %s is still running with PID %s",
3204
                 name, pid)
3205
    utils.KillProcess(pid, waitpid=False)
3206

    
3207
  shutil.rmtree(status_dir, ignore_errors=True)
3208

    
3209

    
3210
def _FindDisks(nodes_ip, disks):
3211
  """Sets the physical ID on disks and returns the block devices.
3212

3213
  """
3214
  # set the correct physical ID
3215
  my_name = netutils.Hostname.GetSysName()
3216
  for cf in disks:
3217
    cf.SetPhysicalID(my_name, nodes_ip)
3218

    
3219
  bdevs = []
3220

    
3221
  for cf in disks:
3222
    rd = _RecursiveFindBD(cf)
3223
    if rd is None:
3224
      _Fail("Can't find device %s", cf)
3225
    bdevs.append(rd)
3226
  return bdevs
3227

    
3228

    
3229
def DrbdDisconnectNet(nodes_ip, disks):
3230
  """Disconnects the network on a list of drbd devices.
3231

3232
  """
3233
  bdevs = _FindDisks(nodes_ip, disks)
3234

    
3235
  # disconnect disks
3236
  for rd in bdevs:
3237
    try:
3238
      rd.DisconnectNet()
3239
    except errors.BlockDeviceError, err:
3240
      _Fail("Can't change network configuration to standalone mode: %s",
3241
            err, exc=True)
3242

    
3243

    
3244
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3245
  """Attaches the network on a list of drbd devices.
3246

3247
  """
3248
  bdevs = _FindDisks(nodes_ip, disks)
3249

    
3250
  if multimaster:
3251
    for idx, rd in enumerate(bdevs):
3252
      try:
3253
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3254
      except EnvironmentError, err:
3255
        _Fail("Can't create symlink: %s", err)
3256
  # reconnect disks, switch to new master configuration and if
3257
  # needed primary mode
3258
  for rd in bdevs:
3259
    try:
3260
      rd.AttachNet(multimaster)
3261
    except errors.BlockDeviceError, err:
3262
      _Fail("Can't change network configuration: %s", err)
3263

    
3264
  # wait until the disks are connected; we need to retry the re-attach
3265
  # if the device becomes standalone, as this might happen if the one
3266
  # node disconnects and reconnects in a different mode before the
3267
  # other node reconnects; in this case, one or both of the nodes will
3268
  # decide it has wrong configuration and switch to standalone
3269

    
3270
  def _Attach():
3271
    all_connected = True
3272

    
3273
    for rd in bdevs:
3274
      stats = rd.GetProcStatus()
3275

    
3276
      all_connected = (all_connected and
3277
                       (stats.is_connected or stats.is_in_resync))
3278

    
3279
      if stats.is_standalone:
3280
        # peer had different config info and this node became
3281
        # standalone, even though this should not happen with the
3282
        # new staged way of changing disk configs
3283
        try:
3284
          rd.AttachNet(multimaster)
3285
        except errors.BlockDeviceError, err:
3286
          _Fail("Can't change network configuration: %s", err)
3287

    
3288
    if not all_connected:
3289
      raise utils.RetryAgain()
3290

    
3291
  try:
3292
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3293
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3294
  except utils.RetryTimeout:
3295
    _Fail("Timeout in disk reconnecting")
3296

    
3297
  if multimaster:
3298
    # change to primary mode
3299
    for rd in bdevs:
3300
      try:
3301
        rd.Open()
3302
      except errors.BlockDeviceError, err:
3303
        _Fail("Can't change to primary mode: %s", err)
3304

    
3305

    
3306
def DrbdWaitSync(nodes_ip, disks):
3307
  """Wait until DRBDs have synchronized.
3308

3309
  """
3310
  def _helper(rd):
3311
    stats = rd.GetProcStatus()
3312
    if not (stats.is_connected or stats.is_in_resync):
3313
      raise utils.RetryAgain()
3314
    return stats
3315

    
3316
  bdevs = _FindDisks(nodes_ip, disks)
3317

    
3318
  min_resync = 100
3319
  alldone = True
3320
  for rd in bdevs:
3321
    try:
3322
      # poll each second for 15 seconds
3323
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3324
    except utils.RetryTimeout:
3325
      stats = rd.GetProcStatus()
3326
      # last check
3327
      if not (stats.is_connected or stats.is_in_resync):
3328
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3329
    alldone = alldone and (not stats.is_in_resync)
3330
    if stats.sync_percent is not None:
3331
      min_resync = min(min_resync, stats.sync_percent)
3332

    
3333
  return (alldone, min_resync)
3334

    
3335

    
3336
def GetDrbdUsermodeHelper():
3337
  """Returns DRBD usermode helper currently configured.
3338

3339
  """
3340
  try:
3341
    return bdev.BaseDRBD.GetUsermodeHelper()
3342
  except errors.BlockDeviceError, err:
3343
    _Fail(str(err))
3344

    
3345

    
3346
def PowercycleNode(hypervisor_type):
3347
  """Hard-powercycle the node.
3348

3349
  Because we need to return first, and schedule the powercycle in the
3350
  background, we won't be able to report failures nicely.
3351

3352
  """
3353
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3354
  try:
3355
    pid = os.fork()
3356
  except OSError:
3357
    # if we can't fork, we'll pretend that we're in the child process
3358
    pid = 0
3359
  if pid > 0:
3360
    return "Reboot scheduled in 5 seconds"
3361
  # ensure the child is running on ram
3362
  try:
3363
    utils.Mlockall()
3364
  except Exception: # pylint: disable=W0703
3365
    pass
3366
  time.sleep(5)
3367
  hyper.PowercycleNode()
3368

    
3369

    
3370
class HooksRunner(object):
3371
  """Hook runner.
3372

3373
  This class is instantiated on the node side (ganeti-noded) and not
3374
  on the master side.
3375

3376
  """
3377
  def __init__(self, hooks_base_dir=None):
3378
    """Constructor for hooks runner.
3379

3380
    @type hooks_base_dir: str or None
3381
    @param hooks_base_dir: if not None, this overrides the
3382
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
3383

3384
    """
3385
    if hooks_base_dir is None:
3386
      hooks_base_dir = constants.HOOKS_BASE_DIR
3387
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3388
    # constant
3389
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
3390

    
3391
  def RunHooks(self, hpath, phase, env):
3392
    """Run the scripts in the hooks directory.
3393

3394
    @type hpath: str
3395
    @param hpath: the path to the hooks directory which
3396
        holds the scripts
3397
    @type phase: str
3398
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
3399
        L{constants.HOOKS_PHASE_POST}
3400
    @type env: dict
3401
    @param env: dictionary with the environment for the hook
3402
    @rtype: list
3403
    @return: list of 3-element tuples:
3404
      - script path
3405
      - script result, either L{constants.HKR_SUCCESS} or
3406
        L{constants.HKR_FAIL}
3407
      - output of the script
3408

3409
    @raise errors.ProgrammerError: for invalid input
3410
        parameters
3411

3412
    """
3413
    if phase == constants.HOOKS_PHASE_PRE:
3414
      suffix = "pre"
3415
    elif phase == constants.HOOKS_PHASE_POST:
3416
      suffix = "post"
3417
    else:
3418
      _Fail("Unknown hooks phase '%s'", phase)
3419

    
3420
    subdir = "%s-%s.d" % (hpath, suffix)
3421
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3422

    
3423
    results = []
3424

    
3425
    if not os.path.isdir(dir_name):
3426
      # for non-existing/non-dirs, we simply exit instead of logging a
3427
      # warning at every operation
3428
      return results
3429

    
3430
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3431

    
3432
    for (relname, relstatus, runresult)  in runparts_results:
3433
      if relstatus == constants.RUNPARTS_SKIP:
3434
        rrval = constants.HKR_SKIP
3435
        output = ""
3436
      elif relstatus == constants.RUNPARTS_ERR:
3437
        rrval = constants.HKR_FAIL
3438
        output = "Hook script execution error: %s" % runresult
3439
      elif relstatus == constants.RUNPARTS_RUN:
3440
        if runresult.failed:
3441
          rrval = constants.HKR_FAIL
3442
        else:
3443
          rrval = constants.HKR_SUCCESS
3444
        output = utils.SafeEncode(runresult.output.strip())
3445
      results.append(("%s/%s" % (subdir, relname), rrval, output))
3446

    
3447
    return results
3448

    
3449

    
3450
class IAllocatorRunner(object):
3451
  """IAllocator runner.
3452

3453
  This class is instantiated on the node side (ganeti-noded) and not on
3454
  the master side.
3455

3456
  """
3457
  @staticmethod
3458
  def Run(name, idata):
3459
    """Run an iallocator script.
3460

3461
    @type name: str
3462
    @param name: the iallocator script name
3463
    @type idata: str
3464
    @param idata: the allocator input data
3465

3466
    @rtype: tuple
3467
    @return: two element tuple of:
3468
       - status
3469
       - either error message or stdout of allocator (for success)
3470

3471
    """
3472
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
3473
                                  os.path.isfile)
3474
    if alloc_script is None:
3475
      _Fail("iallocator module '%s' not found in the search path", name)
3476

    
3477
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
3478
    try:
3479
      os.write(fd, idata)
3480
      os.close(fd)
3481
      result = utils.RunCmd([alloc_script, fin_name])
3482
      if result.failed:
3483
        _Fail("iallocator module '%s' failed: %s, output '%s'",
3484
              name, result.fail_reason, result.output)
3485
    finally:
3486
      os.unlink(fin_name)
3487

    
3488
    return result.stdout
3489

    
3490

    
3491
class DevCacheManager(object):
3492
  """Simple class for managing a cache of block device information.
3493

3494
  """
3495
  _DEV_PREFIX = "/dev/"
3496
  _ROOT_DIR = constants.BDEV_CACHE_DIR
3497

    
3498
  @classmethod
3499
  def _ConvertPath(cls, dev_path):
3500
    """Converts a /dev/name path to the cache file name.
3501

3502
    This replaces slashes with underscores and strips the /dev
3503
    prefix. It then returns the full path to the cache file.
3504

3505
    @type dev_path: str
3506
    @param dev_path: the C{/dev/} path name
3507
    @rtype: str
3508
    @return: the converted path name
3509

3510
    """
3511
    if dev_path.startswith(cls._DEV_PREFIX):
3512
      dev_path = dev_path[len(cls._DEV_PREFIX):]
3513
    dev_path = dev_path.replace("/", "_")
3514
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
3515
    return fpath
3516

    
3517
  @classmethod
3518
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
3519
    """Updates the cache information for a given device.
3520

3521
    @type dev_path: str
3522
    @param dev_path: the pathname of the device
3523
    @type owner: str
3524
    @param owner: the owner (instance name) of the device
3525
    @type on_primary: bool
3526
    @param on_primary: whether this is the primary
3527
        node nor not
3528
    @type iv_name: str
3529
    @param iv_name: the instance-visible name of the
3530
        device, as in objects.Disk.iv_name
3531

3532
    @rtype: None
3533

3534
    """
3535
    if dev_path is None:
3536
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
3537
      return
3538
    fpath = cls._ConvertPath(dev_path)
3539
    if on_primary:
3540
      state = "primary"
3541
    else:
3542
      state = "secondary"
3543
    if iv_name is None:
3544
      iv_name = "not_visible"
3545
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
3546
    try:
3547
      utils.WriteFile(fpath, data=fdata)
3548
    except EnvironmentError, err:
3549
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
3550

    
3551
  @classmethod
3552
  def RemoveCache(cls, dev_path):
3553
    """Remove data for a dev_path.
3554

3555
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
3556
    path name and logging.
3557

3558
    @type dev_path: str
3559
    @param dev_path: the pathname of the device
3560

3561
    @rtype: None
3562

3563
    """
3564
    if dev_path is None:
3565
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
3566
      return
3567
    fpath = cls._ConvertPath(dev_path)
3568
    try:
3569
      utils.RemoveFile(fpath)
3570
    except EnvironmentError, err:
3571
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)