Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ c06e0c83

History | View | Annotate | Download (106.4 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 FinalizeMigration(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.FinalizeMigration(instance, info, success)
1295
  except errors.HypervisorError, err:
1296
    _Fail("Failed to finalize migration: %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
  @rtype: tuple
1310
  @return: a tuple of (success, msg) where:
1311
      - succes is a boolean denoting the success/failure of the operation
1312
      - msg is a string with details in case of failure
1313

1314
  """
1315
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1316

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

    
1322

    
1323
def BlockdevCreate(disk, size, owner, on_primary, info):
1324
  """Creates a block device for an instance.
1325

1326
  @type disk: L{objects.Disk}
1327
  @param disk: the object describing the disk we should create
1328
  @type size: int
1329
  @param size: the size of the physical underlying device, in MiB
1330
  @type owner: str
1331
  @param owner: the name of the instance for which disk is created,
1332
      used for device cache data
1333
  @type on_primary: boolean
1334
  @param on_primary:  indicates if it is the primary node or not
1335
  @type info: string
1336
  @param info: string that will be sent to the physical device
1337
      creation, used for example to set (LVM) tags on LVs
1338

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

1343
  """
1344
  # TODO: remove the obsolete "size" argument
1345
  # pylint: disable=W0613
1346
  clist = []
1347
  if disk.children:
1348
    for child in disk.children:
1349
      try:
1350
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1351
      except errors.BlockDeviceError, err:
1352
        _Fail("Can't assemble device %s: %s", child, err)
1353
      if on_primary or disk.AssembleOnSecondary():
1354
        # we need the children open in case the device itself has to
1355
        # be assembled
1356
        try:
1357
          # pylint: disable=E1103
1358
          crdev.Open()
1359
        except errors.BlockDeviceError, err:
1360
          _Fail("Can't make child '%s' read-write: %s", child, err)
1361
      clist.append(crdev)
1362

    
1363
  try:
1364
    device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
1365
  except errors.BlockDeviceError, err:
1366
    _Fail("Can't create block device: %s", err)
1367

    
1368
  if on_primary or disk.AssembleOnSecondary():
1369
    try:
1370
      device.Assemble()
1371
    except errors.BlockDeviceError, err:
1372
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1373
    device.SetSyncSpeed(constants.SYNC_SPEED)
1374
    if on_primary or disk.OpenOnSecondary():
1375
      try:
1376
        device.Open(force=True)
1377
      except errors.BlockDeviceError, err:
1378
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1379
    DevCacheManager.UpdateCache(device.dev_path, owner,
1380
                                on_primary, disk.iv_name)
1381

    
1382
  device.SetInfo(info)
1383

    
1384
  return device.unique_id
1385

    
1386

    
1387
def _WipeDevice(path, offset, size):
1388
  """This function actually wipes the device.
1389

1390
  @param path: The path to the device to wipe
1391
  @param offset: The offset in MiB in the file
1392
  @param size: The size in MiB to write
1393

1394
  """
1395
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1396
         "bs=%d" % constants.WIPE_BLOCK_SIZE, "oflag=direct", "of=%s" % path,
1397
         "count=%d" % size]
1398
  result = utils.RunCmd(cmd)
1399

    
1400
  if result.failed:
1401
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1402
          result.fail_reason, result.output)
1403

    
1404

    
1405
def BlockdevWipe(disk, offset, size):
1406
  """Wipes a block device.
1407

1408
  @type disk: L{objects.Disk}
1409
  @param disk: the disk object we want to wipe
1410
  @type offset: int
1411
  @param offset: The offset in MiB in the file
1412
  @type size: int
1413
  @param size: The size in MiB to write
1414

1415
  """
1416
  try:
1417
    rdev = _RecursiveFindBD(disk)
1418
  except errors.BlockDeviceError:
1419
    rdev = None
1420

    
1421
  if not rdev:
1422
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1423

    
1424
  # Do cross verify some of the parameters
1425
  if offset > rdev.size:
1426
    _Fail("Offset is bigger than device size")
1427
  if (offset + size) > rdev.size:
1428
    _Fail("The provided offset and size to wipe is bigger than device size")
1429

    
1430
  _WipeDevice(rdev.dev_path, offset, size)
1431

    
1432

    
1433
def BlockdevPauseResumeSync(disks, pause):
1434
  """Pause or resume the sync of the block device.
1435

1436
  @type disks: list of L{objects.Disk}
1437
  @param disks: the disks object we want to pause/resume
1438
  @type pause: bool
1439
  @param pause: Wheater to pause or resume
1440

1441
  """
1442
  success = []
1443
  for disk in disks:
1444
    try:
1445
      rdev = _RecursiveFindBD(disk)
1446
    except errors.BlockDeviceError:
1447
      rdev = None
1448

    
1449
    if not rdev:
1450
      success.append((False, ("Cannot change sync for device %s:"
1451
                              " device not found" % disk.iv_name)))
1452
      continue
1453

    
1454
    result = rdev.PauseResumeSync(pause)
1455

    
1456
    if result:
1457
      success.append((result, None))
1458
    else:
1459
      if pause:
1460
        msg = "Pause"
1461
      else:
1462
        msg = "Resume"
1463
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1464

    
1465
  return success
1466

    
1467

    
1468
def BlockdevRemove(disk):
1469
  """Remove a block device.
1470

1471
  @note: This is intended to be called recursively.
1472

1473
  @type disk: L{objects.Disk}
1474
  @param disk: the disk object we should remove
1475
  @rtype: boolean
1476
  @return: the success of the operation
1477

1478
  """
1479
  msgs = []
1480
  try:
1481
    rdev = _RecursiveFindBD(disk)
1482
  except errors.BlockDeviceError, err:
1483
    # probably can't attach
1484
    logging.info("Can't attach to device %s in remove", disk)
1485
    rdev = None
1486
  if rdev is not None:
1487
    r_path = rdev.dev_path
1488
    try:
1489
      rdev.Remove()
1490
    except errors.BlockDeviceError, err:
1491
      msgs.append(str(err))
1492
    if not msgs:
1493
      DevCacheManager.RemoveCache(r_path)
1494

    
1495
  if disk.children:
1496
    for child in disk.children:
1497
      try:
1498
        BlockdevRemove(child)
1499
      except RPCFail, err:
1500
        msgs.append(str(err))
1501

    
1502
  if msgs:
1503
    _Fail("; ".join(msgs))
1504

    
1505

    
1506
def _RecursiveAssembleBD(disk, owner, as_primary):
1507
  """Activate a block device for an instance.
1508

1509
  This is run on the primary and secondary nodes for an instance.
1510

1511
  @note: this function is called recursively.
1512

1513
  @type disk: L{objects.Disk}
1514
  @param disk: the disk we try to assemble
1515
  @type owner: str
1516
  @param owner: the name of the instance which owns the disk
1517
  @type as_primary: boolean
1518
  @param as_primary: if we should make the block device
1519
      read/write
1520

1521
  @return: the assembled device or None (in case no device
1522
      was assembled)
1523
  @raise errors.BlockDeviceError: in case there is an error
1524
      during the activation of the children or the device
1525
      itself
1526

1527
  """
1528
  children = []
1529
  if disk.children:
1530
    mcn = disk.ChildrenNeeded()
1531
    if mcn == -1:
1532
      mcn = 0 # max number of Nones allowed
1533
    else:
1534
      mcn = len(disk.children) - mcn # max number of Nones
1535
    for chld_disk in disk.children:
1536
      try:
1537
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1538
      except errors.BlockDeviceError, err:
1539
        if children.count(None) >= mcn:
1540
          raise
1541
        cdev = None
1542
        logging.error("Error in child activation (but continuing): %s",
1543
                      str(err))
1544
      children.append(cdev)
1545

    
1546
  if as_primary or disk.AssembleOnSecondary():
1547
    r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
1548
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1549
    result = r_dev
1550
    if as_primary or disk.OpenOnSecondary():
1551
      r_dev.Open()
1552
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1553
                                as_primary, disk.iv_name)
1554

    
1555
  else:
1556
    result = True
1557
  return result
1558

    
1559

    
1560
def BlockdevAssemble(disk, owner, as_primary, idx):
1561
  """Activate a block device for an instance.
1562

1563
  This is a wrapper over _RecursiveAssembleBD.
1564

1565
  @rtype: str or boolean
1566
  @return: a C{/dev/...} path for primary nodes, and
1567
      C{True} for secondary nodes
1568

1569
  """
1570
  try:
1571
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1572
    if isinstance(result, bdev.BlockDev):
1573
      # pylint: disable=E1103
1574
      result = result.dev_path
1575
      if as_primary:
1576
        _SymlinkBlockDev(owner, result, idx)
1577
  except errors.BlockDeviceError, err:
1578
    _Fail("Error while assembling disk: %s", err, exc=True)
1579
  except OSError, err:
1580
    _Fail("Error while symlinking disk: %s", err, exc=True)
1581

    
1582
  return result
1583

    
1584

    
1585
def BlockdevShutdown(disk):
1586
  """Shut down a block device.
1587

1588
  First, if the device is assembled (Attach() is successful), then
1589
  the device is shutdown. Then the children of the device are
1590
  shutdown.
1591

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

1596
  @type disk: L{objects.Disk}
1597
  @param disk: the description of the disk we should
1598
      shutdown
1599
  @rtype: None
1600

1601
  """
1602
  msgs = []
1603
  r_dev = _RecursiveFindBD(disk)
1604
  if r_dev is not None:
1605
    r_path = r_dev.dev_path
1606
    try:
1607
      r_dev.Shutdown()
1608
      DevCacheManager.RemoveCache(r_path)
1609
    except errors.BlockDeviceError, err:
1610
      msgs.append(str(err))
1611

    
1612
  if disk.children:
1613
    for child in disk.children:
1614
      try:
1615
        BlockdevShutdown(child)
1616
      except RPCFail, err:
1617
        msgs.append(str(err))
1618

    
1619
  if msgs:
1620
    _Fail("; ".join(msgs))
1621

    
1622

    
1623
def BlockdevAddchildren(parent_cdev, new_cdevs):
1624
  """Extend a mirrored block device.
1625

1626
  @type parent_cdev: L{objects.Disk}
1627
  @param parent_cdev: the disk to which we should add children
1628
  @type new_cdevs: list of L{objects.Disk}
1629
  @param new_cdevs: the list of children which we should add
1630
  @rtype: None
1631

1632
  """
1633
  parent_bdev = _RecursiveFindBD(parent_cdev)
1634
  if parent_bdev is None:
1635
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1636
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1637
  if new_bdevs.count(None) > 0:
1638
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1639
  parent_bdev.AddChildren(new_bdevs)
1640

    
1641

    
1642
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1643
  """Shrink a mirrored block device.
1644

1645
  @type parent_cdev: L{objects.Disk}
1646
  @param parent_cdev: the disk from which we should remove children
1647
  @type new_cdevs: list of L{objects.Disk}
1648
  @param new_cdevs: the list of children which we should remove
1649
  @rtype: None
1650

1651
  """
1652
  parent_bdev = _RecursiveFindBD(parent_cdev)
1653
  if parent_bdev is None:
1654
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1655
  devs = []
1656
  for disk in new_cdevs:
1657
    rpath = disk.StaticDevPath()
1658
    if rpath is None:
1659
      bd = _RecursiveFindBD(disk)
1660
      if bd is None:
1661
        _Fail("Can't find device %s while removing children", disk)
1662
      else:
1663
        devs.append(bd.dev_path)
1664
    else:
1665
      if not utils.IsNormAbsPath(rpath):
1666
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
1667
      devs.append(rpath)
1668
  parent_bdev.RemoveChildren(devs)
1669

    
1670

    
1671
def BlockdevGetmirrorstatus(disks):
1672
  """Get the mirroring status of a list of devices.
1673

1674
  @type disks: list of L{objects.Disk}
1675
  @param disks: the list of disks which we should query
1676
  @rtype: disk
1677
  @return: List of L{objects.BlockDevStatus}, one for each disk
1678
  @raise errors.BlockDeviceError: if any of the disks cannot be
1679
      found
1680

1681
  """
1682
  stats = []
1683
  for dsk in disks:
1684
    rbd = _RecursiveFindBD(dsk)
1685
    if rbd is None:
1686
      _Fail("Can't find device %s", dsk)
1687

    
1688
    stats.append(rbd.CombinedSyncStatus())
1689

    
1690
  return stats
1691

    
1692

    
1693
def BlockdevGetmirrorstatusMulti(disks):
1694
  """Get the mirroring status of a list of devices.
1695

1696
  @type disks: list of L{objects.Disk}
1697
  @param disks: the list of disks which we should query
1698
  @rtype: disk
1699
  @return: List of tuples, (bool, status), one for each disk; bool denotes
1700
    success/failure, status is L{objects.BlockDevStatus} on success, string
1701
    otherwise
1702

1703
  """
1704
  result = []
1705
  for disk in disks:
1706
    try:
1707
      rbd = _RecursiveFindBD(disk)
1708
      if rbd is None:
1709
        result.append((False, "Can't find device %s" % disk))
1710
        continue
1711

    
1712
      status = rbd.CombinedSyncStatus()
1713
    except errors.BlockDeviceError, err:
1714
      logging.exception("Error while getting disk status")
1715
      result.append((False, str(err)))
1716
    else:
1717
      result.append((True, status))
1718

    
1719
  assert len(disks) == len(result)
1720

    
1721
  return result
1722

    
1723

    
1724
def _RecursiveFindBD(disk):
1725
  """Check if a device is activated.
1726

1727
  If so, return information about the real device.
1728

1729
  @type disk: L{objects.Disk}
1730
  @param disk: the disk object we need to find
1731

1732
  @return: None if the device can't be found,
1733
      otherwise the device instance
1734

1735
  """
1736
  children = []
1737
  if disk.children:
1738
    for chdisk in disk.children:
1739
      children.append(_RecursiveFindBD(chdisk))
1740

    
1741
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1742

    
1743

    
1744
def _OpenRealBD(disk):
1745
  """Opens the underlying block device of a disk.
1746

1747
  @type disk: L{objects.Disk}
1748
  @param disk: the disk object we want to open
1749

1750
  """
1751
  real_disk = _RecursiveFindBD(disk)
1752
  if real_disk is None:
1753
    _Fail("Block device '%s' is not set up", disk)
1754

    
1755
  real_disk.Open()
1756

    
1757
  return real_disk
1758

    
1759

    
1760
def BlockdevFind(disk):
1761
  """Check if a device is activated.
1762

1763
  If it is, return information about the real device.
1764

1765
  @type disk: L{objects.Disk}
1766
  @param disk: the disk to find
1767
  @rtype: None or objects.BlockDevStatus
1768
  @return: None if the disk cannot be found, otherwise a the current
1769
           information
1770

1771
  """
1772
  try:
1773
    rbd = _RecursiveFindBD(disk)
1774
  except errors.BlockDeviceError, err:
1775
    _Fail("Failed to find device: %s", err, exc=True)
1776

    
1777
  if rbd is None:
1778
    return None
1779

    
1780
  return rbd.GetSyncStatus()
1781

    
1782

    
1783
def BlockdevGetsize(disks):
1784
  """Computes the size of the given disks.
1785

1786
  If a disk is not found, returns None instead.
1787

1788
  @type disks: list of L{objects.Disk}
1789
  @param disks: the list of disk to compute the size for
1790
  @rtype: list
1791
  @return: list with elements None if the disk cannot be found,
1792
      otherwise the size
1793

1794
  """
1795
  result = []
1796
  for cf in disks:
1797
    try:
1798
      rbd = _RecursiveFindBD(cf)
1799
    except errors.BlockDeviceError:
1800
      result.append(None)
1801
      continue
1802
    if rbd is None:
1803
      result.append(None)
1804
    else:
1805
      result.append(rbd.GetActualSize())
1806
  return result
1807

    
1808

    
1809
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
1810
  """Export a block device to a remote node.
1811

1812
  @type disk: L{objects.Disk}
1813
  @param disk: the description of the disk to export
1814
  @type dest_node: str
1815
  @param dest_node: the destination node to export to
1816
  @type dest_path: str
1817
  @param dest_path: the destination path on the target node
1818
  @type cluster_name: str
1819
  @param cluster_name: the cluster name, needed for SSH hostalias
1820
  @rtype: None
1821

1822
  """
1823
  real_disk = _OpenRealBD(disk)
1824

    
1825
  # the block size on the read dd is 1MiB to match our units
1826
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
1827
                               "dd if=%s bs=1048576 count=%s",
1828
                               real_disk.dev_path, str(disk.size))
1829

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

    
1839
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1840
                                                   constants.GANETI_RUNAS,
1841
                                                   destcmd)
1842

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

    
1846
  result = utils.RunCmd(["bash", "-c", command])
1847

    
1848
  if result.failed:
1849
    _Fail("Disk copy command '%s' returned error: %s"
1850
          " output: %s", command, result.fail_reason, result.output)
1851

    
1852

    
1853
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1854
  """Write a file to the filesystem.
1855

1856
  This allows the master to overwrite(!) a file. It will only perform
1857
  the operation if the file belongs to a list of configuration files.
1858

1859
  @type file_name: str
1860
  @param file_name: the target file name
1861
  @type data: str
1862
  @param data: the new contents of the file
1863
  @type mode: int
1864
  @param mode: the mode to give the file (can be None)
1865
  @type uid: string
1866
  @param uid: the owner of the file
1867
  @type gid: string
1868
  @param gid: the group of the file
1869
  @type atime: float
1870
  @param atime: the atime to set on the file (can be None)
1871
  @type mtime: float
1872
  @param mtime: the mtime to set on the file (can be None)
1873
  @rtype: None
1874

1875
  """
1876
  if not os.path.isabs(file_name):
1877
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
1878

    
1879
  if file_name not in _ALLOWED_UPLOAD_FILES:
1880
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
1881
          file_name)
1882

    
1883
  raw_data = _Decompress(data)
1884

    
1885
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
1886
    _Fail("Invalid username/groupname type")
1887

    
1888
  getents = runtime.GetEnts()
1889
  uid = getents.LookupUser(uid)
1890
  gid = getents.LookupGroup(gid)
1891

    
1892
  utils.SafeWriteFile(file_name, None,
1893
                      data=raw_data, mode=mode, uid=uid, gid=gid,
1894
                      atime=atime, mtime=mtime)
1895

    
1896

    
1897
def RunOob(oob_program, command, node, timeout):
1898
  """Executes oob_program with given command on given node.
1899

1900
  @param oob_program: The path to the executable oob_program
1901
  @param command: The command to invoke on oob_program
1902
  @param node: The node given as an argument to the program
1903
  @param timeout: Timeout after which we kill the oob program
1904

1905
  @return: stdout
1906
  @raise RPCFail: If execution fails for some reason
1907

1908
  """
1909
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
1910

    
1911
  if result.failed:
1912
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
1913
          result.fail_reason, result.output)
1914

    
1915
  return result.stdout
1916

    
1917

    
1918
def WriteSsconfFiles(values):
1919
  """Update all ssconf files.
1920

1921
  Wrapper around the SimpleStore.WriteFiles.
1922

1923
  """
1924
  ssconf.SimpleStore().WriteFiles(values)
1925

    
1926

    
1927
def _ErrnoOrStr(err):
1928
  """Format an EnvironmentError exception.
1929

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

1934
  @type err: L{EnvironmentError}
1935
  @param err: the exception to format
1936

1937
  """
1938
  if hasattr(err, "errno"):
1939
    detail = errno.errorcode[err.errno]
1940
  else:
1941
    detail = str(err)
1942
  return detail
1943

    
1944

    
1945
def _OSOndiskAPIVersion(os_dir):
1946
  """Compute and return the API version of a given OS.
1947

1948
  This function will try to read the API version of the OS residing in
1949
  the 'os_dir' directory.
1950

1951
  @type os_dir: str
1952
  @param os_dir: the directory in which we should look for the OS
1953
  @rtype: tuple
1954
  @return: tuple (status, data) with status denoting the validity and
1955
      data holding either the vaid versions or an error message
1956

1957
  """
1958
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
1959

    
1960
  try:
1961
    st = os.stat(api_file)
1962
  except EnvironmentError, err:
1963
    return False, ("Required file '%s' not found under path %s: %s" %
1964
                   (constants.OS_API_FILE, os_dir, _ErrnoOrStr(err)))
1965

    
1966
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1967
    return False, ("File '%s' in %s is not a regular file" %
1968
                   (constants.OS_API_FILE, os_dir))
1969

    
1970
  try:
1971
    api_versions = utils.ReadFile(api_file).splitlines()
1972
  except EnvironmentError, err:
1973
    return False, ("Error while reading the API version file at %s: %s" %
1974
                   (api_file, _ErrnoOrStr(err)))
1975

    
1976
  try:
1977
    api_versions = [int(version.strip()) for version in api_versions]
1978
  except (TypeError, ValueError), err:
1979
    return False, ("API version(s) can't be converted to integer: %s" %
1980
                   str(err))
1981

    
1982
  return True, api_versions
1983

    
1984

    
1985
def DiagnoseOS(top_dirs=None):
1986
  """Compute the validity for all OSes.
1987

1988
  @type top_dirs: list
1989
  @param top_dirs: the list of directories in which to
1990
      search (if not given defaults to
1991
      L{constants.OS_SEARCH_PATH})
1992
  @rtype: list of L{objects.OS}
1993
  @return: a list of tuples (name, path, status, diagnose, variants,
1994
      parameters, api_version) for all (potential) OSes under all
1995
      search paths, where:
1996
          - name is the (potential) OS name
1997
          - path is the full path to the OS
1998
          - status True/False is the validity of the OS
1999
          - diagnose is the error message for an invalid OS, otherwise empty
2000
          - variants is a list of supported OS variants, if any
2001
          - parameters is a list of (name, help) parameters, if any
2002
          - api_version is a list of support OS API versions
2003

2004
  """
2005
  if top_dirs is None:
2006
    top_dirs = constants.OS_SEARCH_PATH
2007

    
2008
  result = []
2009
  for dir_name in top_dirs:
2010
    if os.path.isdir(dir_name):
2011
      try:
2012
        f_names = utils.ListVisibleFiles(dir_name)
2013
      except EnvironmentError, err:
2014
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2015
        break
2016
      for name in f_names:
2017
        os_path = utils.PathJoin(dir_name, name)
2018
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2019
        if status:
2020
          diagnose = ""
2021
          variants = os_inst.supported_variants
2022
          parameters = os_inst.supported_parameters
2023
          api_versions = os_inst.api_versions
2024
        else:
2025
          diagnose = os_inst
2026
          variants = parameters = api_versions = []
2027
        result.append((name, os_path, status, diagnose, variants,
2028
                       parameters, api_versions))
2029

    
2030
  return result
2031

    
2032

    
2033
def _TryOSFromDisk(name, base_dir=None):
2034
  """Create an OS instance from disk.
2035

2036
  This function will return an OS instance if the given name is a
2037
  valid OS name.
2038

2039
  @type base_dir: string
2040
  @keyword base_dir: Base directory containing OS installations.
2041
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2042
  @rtype: tuple
2043
  @return: success and either the OS instance if we find a valid one,
2044
      or error message
2045

2046
  """
2047
  if base_dir is None:
2048
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
2049
  else:
2050
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2051

    
2052
  if os_dir is None:
2053
    return False, "Directory for OS %s not found in search path" % name
2054

    
2055
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2056
  if not status:
2057
    # push the error up
2058
    return status, api_versions
2059

    
2060
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2061
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2062
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2063

    
2064
  # OS Files dictionary, we will populate it with the absolute path
2065
  # names; if the value is True, then it is a required file, otherwise
2066
  # an optional one
2067
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2068

    
2069
  if max(api_versions) >= constants.OS_API_V15:
2070
    os_files[constants.OS_VARIANTS_FILE] = False
2071

    
2072
  if max(api_versions) >= constants.OS_API_V20:
2073
    os_files[constants.OS_PARAMETERS_FILE] = True
2074
  else:
2075
    del os_files[constants.OS_SCRIPT_VERIFY]
2076

    
2077
  for (filename, required) in os_files.items():
2078
    os_files[filename] = utils.PathJoin(os_dir, filename)
2079

    
2080
    try:
2081
      st = os.stat(os_files[filename])
2082
    except EnvironmentError, err:
2083
      if err.errno == errno.ENOENT and not required:
2084
        del os_files[filename]
2085
        continue
2086
      return False, ("File '%s' under path '%s' is missing (%s)" %
2087
                     (filename, os_dir, _ErrnoOrStr(err)))
2088

    
2089
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2090
      return False, ("File '%s' under path '%s' is not a regular file" %
2091
                     (filename, os_dir))
2092

    
2093
    if filename in constants.OS_SCRIPTS:
2094
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2095
        return False, ("File '%s' under path '%s' is not executable" %
2096
                       (filename, os_dir))
2097

    
2098
  variants = []
2099
  if constants.OS_VARIANTS_FILE in os_files:
2100
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2101
    try:
2102
      variants = utils.ReadFile(variants_file).splitlines()
2103
    except EnvironmentError, err:
2104
      # we accept missing files, but not other errors
2105
      if err.errno != errno.ENOENT:
2106
        return False, ("Error while reading the OS variants file at %s: %s" %
2107
                       (variants_file, _ErrnoOrStr(err)))
2108

    
2109
  parameters = []
2110
  if constants.OS_PARAMETERS_FILE in os_files:
2111
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2112
    try:
2113
      parameters = utils.ReadFile(parameters_file).splitlines()
2114
    except EnvironmentError, err:
2115
      return False, ("Error while reading the OS parameters file at %s: %s" %
2116
                     (parameters_file, _ErrnoOrStr(err)))
2117
    parameters = [v.split(None, 1) for v in parameters]
2118

    
2119
  os_obj = objects.OS(name=name, path=os_dir,
2120
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2121
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2122
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2123
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2124
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2125
                                                 None),
2126
                      supported_variants=variants,
2127
                      supported_parameters=parameters,
2128
                      api_versions=api_versions)
2129
  return True, os_obj
2130

    
2131

    
2132
def OSFromDisk(name, base_dir=None):
2133
  """Create an OS instance from disk.
2134

2135
  This function will return an OS instance if the given name is a
2136
  valid OS name. Otherwise, it will raise an appropriate
2137
  L{RPCFail} exception, detailing why this is not a valid OS.
2138

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

2142
  @type base_dir: string
2143
  @keyword base_dir: Base directory containing OS installations.
2144
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2145
  @rtype: L{objects.OS}
2146
  @return: the OS instance if we find a valid one
2147
  @raise RPCFail: if we don't find a valid OS
2148

2149
  """
2150
  name_only = objects.OS.GetName(name)
2151
  status, payload = _TryOSFromDisk(name_only, base_dir)
2152

    
2153
  if not status:
2154
    _Fail(payload)
2155

    
2156
  return payload
2157

    
2158

    
2159
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2160
  """Calculate the basic environment for an os script.
2161

2162
  @type os_name: str
2163
  @param os_name: full operating system name (including variant)
2164
  @type inst_os: L{objects.OS}
2165
  @param inst_os: operating system for which the environment is being built
2166
  @type os_params: dict
2167
  @param os_params: the OS parameters
2168
  @type debug: integer
2169
  @param debug: debug level (0 or 1, for OS Api 10)
2170
  @rtype: dict
2171
  @return: dict of environment variables
2172
  @raise errors.BlockDeviceError: if the block device
2173
      cannot be found
2174

2175
  """
2176
  result = {}
2177
  api_version = \
2178
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2179
  result["OS_API_VERSION"] = "%d" % api_version
2180
  result["OS_NAME"] = inst_os.name
2181
  result["DEBUG_LEVEL"] = "%d" % debug
2182

    
2183
  # OS variants
2184
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2185
    variant = objects.OS.GetVariant(os_name)
2186
    if not variant:
2187
      variant = inst_os.supported_variants[0]
2188
  else:
2189
    variant = ""
2190
  result["OS_VARIANT"] = variant
2191

    
2192
  # OS params
2193
  for pname, pvalue in os_params.items():
2194
    result["OSP_%s" % pname.upper()] = pvalue
2195

    
2196
  return result
2197

    
2198

    
2199
def OSEnvironment(instance, inst_os, debug=0):
2200
  """Calculate the environment for an os script.
2201

2202
  @type instance: L{objects.Instance}
2203
  @param instance: target instance for the os script run
2204
  @type inst_os: L{objects.OS}
2205
  @param inst_os: operating system for which the environment is being built
2206
  @type debug: integer
2207
  @param debug: debug level (0 or 1, for OS Api 10)
2208
  @rtype: dict
2209
  @return: dict of environment variables
2210
  @raise errors.BlockDeviceError: if the block device
2211
      cannot be found
2212

2213
  """
2214
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2215

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

    
2219
  result["HYPERVISOR"] = instance.hypervisor
2220
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2221
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2222
  result["INSTANCE_SECONDARY_NODES"] = \
2223
      ("%s" % " ".join(instance.secondary_nodes))
2224

    
2225
  # Disks
2226
  for idx, disk in enumerate(instance.disks):
2227
    real_disk = _OpenRealBD(disk)
2228
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2229
    result["DISK_%d_ACCESS" % idx] = disk.mode
2230
    if constants.HV_DISK_TYPE in instance.hvparams:
2231
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2232
        instance.hvparams[constants.HV_DISK_TYPE]
2233
    if disk.dev_type in constants.LDS_BLOCK:
2234
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2235
    elif disk.dev_type == constants.LD_FILE:
2236
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2237
        "file:%s" % disk.physical_id[0]
2238

    
2239
  # NICs
2240
  for idx, nic in enumerate(instance.nics):
2241
    result["NIC_%d_MAC" % idx] = nic.mac
2242
    if nic.ip:
2243
      result["NIC_%d_IP" % idx] = nic.ip
2244
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2245
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2246
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2247
    if nic.nicparams[constants.NIC_LINK]:
2248
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2249
    if constants.HV_NIC_TYPE in instance.hvparams:
2250
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2251
        instance.hvparams[constants.HV_NIC_TYPE]
2252

    
2253
  # HV/BE params
2254
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2255
    for key, value in source.items():
2256
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2257

    
2258
  return result
2259

    
2260

    
2261
def BlockdevGrow(disk, amount, dryrun):
2262
  """Grow a stack of block devices.
2263

2264
  This function is called recursively, with the childrens being the
2265
  first ones to resize.
2266

2267
  @type disk: L{objects.Disk}
2268
  @param disk: the disk to be grown
2269
  @type amount: integer
2270
  @param amount: the amount (in mebibytes) to grow with
2271
  @type dryrun: boolean
2272
  @param dryrun: whether to execute the operation in simulation mode
2273
      only, without actually increasing the size
2274
  @rtype: (status, result)
2275
  @return: a tuple with the status of the operation (True/False), and
2276
      the errors message if status is False
2277

2278
  """
2279
  r_dev = _RecursiveFindBD(disk)
2280
  if r_dev is None:
2281
    _Fail("Cannot find block device %s", disk)
2282

    
2283
  try:
2284
    r_dev.Grow(amount, dryrun)
2285
  except errors.BlockDeviceError, err:
2286
    _Fail("Failed to grow block device: %s", err, exc=True)
2287

    
2288

    
2289
def BlockdevSnapshot(disk):
2290
  """Create a snapshot copy of a block device.
2291

2292
  This function is called recursively, and the snapshot is actually created
2293
  just for the leaf lvm backend device.
2294

2295
  @type disk: L{objects.Disk}
2296
  @param disk: the disk to be snapshotted
2297
  @rtype: string
2298
  @return: snapshot disk ID as (vg, lv)
2299

2300
  """
2301
  if disk.dev_type == constants.LD_DRBD8:
2302
    if not disk.children:
2303
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2304
            disk.unique_id)
2305
    return BlockdevSnapshot(disk.children[0])
2306
  elif disk.dev_type == constants.LD_LV:
2307
    r_dev = _RecursiveFindBD(disk)
2308
    if r_dev is not None:
2309
      # FIXME: choose a saner value for the snapshot size
2310
      # let's stay on the safe side and ask for the full size, for now
2311
      return r_dev.Snapshot(disk.size)
2312
    else:
2313
      _Fail("Cannot find block device %s", disk)
2314
  else:
2315
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2316
          disk.unique_id, disk.dev_type)
2317

    
2318

    
2319
def FinalizeExport(instance, snap_disks):
2320
  """Write out the export configuration information.
2321

2322
  @type instance: L{objects.Instance}
2323
  @param instance: the instance which we export, used for
2324
      saving configuration
2325
  @type snap_disks: list of L{objects.Disk}
2326
  @param snap_disks: list of snapshot block devices, which
2327
      will be used to get the actual name of the dump file
2328

2329
  @rtype: None
2330

2331
  """
2332
  destdir = utils.PathJoin(constants.EXPORT_DIR, instance.name + ".new")
2333
  finaldestdir = utils.PathJoin(constants.EXPORT_DIR, instance.name)
2334

    
2335
  config = objects.SerializableConfigParser()
2336

    
2337
  config.add_section(constants.INISECT_EXP)
2338
  config.set(constants.INISECT_EXP, "version", "0")
2339
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2340
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2341
  config.set(constants.INISECT_EXP, "os", instance.os)
2342
  config.set(constants.INISECT_EXP, "compression", "none")
2343

    
2344
  config.add_section(constants.INISECT_INS)
2345
  config.set(constants.INISECT_INS, "name", instance.name)
2346
  config.set(constants.INISECT_INS, "memory", "%d" %
2347
             instance.beparams[constants.BE_MEMORY])
2348
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2349
             instance.beparams[constants.BE_VCPUS])
2350
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2351
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2352
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2353

    
2354
  nic_total = 0
2355
  for nic_count, nic in enumerate(instance.nics):
2356
    nic_total += 1
2357
    config.set(constants.INISECT_INS, "nic%d_mac" %
2358
               nic_count, "%s" % nic.mac)
2359
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2360
    for param in constants.NICS_PARAMETER_TYPES:
2361
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2362
                 "%s" % nic.nicparams.get(param, None))
2363
  # TODO: redundant: on load can read nics until it doesn't exist
2364
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2365

    
2366
  disk_total = 0
2367
  for disk_count, disk in enumerate(snap_disks):
2368
    if disk:
2369
      disk_total += 1
2370
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2371
                 ("%s" % disk.iv_name))
2372
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2373
                 ("%s" % disk.physical_id[1]))
2374
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2375
                 ("%d" % disk.size))
2376

    
2377
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2378

    
2379
  # New-style hypervisor/backend parameters
2380

    
2381
  config.add_section(constants.INISECT_HYP)
2382
  for name, value in instance.hvparams.items():
2383
    if name not in constants.HVC_GLOBALS:
2384
      config.set(constants.INISECT_HYP, name, str(value))
2385

    
2386
  config.add_section(constants.INISECT_BEP)
2387
  for name, value in instance.beparams.items():
2388
    config.set(constants.INISECT_BEP, name, str(value))
2389

    
2390
  config.add_section(constants.INISECT_OSP)
2391
  for name, value in instance.osparams.items():
2392
    config.set(constants.INISECT_OSP, name, str(value))
2393

    
2394
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2395
                  data=config.Dumps())
2396
  shutil.rmtree(finaldestdir, ignore_errors=True)
2397
  shutil.move(destdir, finaldestdir)
2398

    
2399

    
2400
def ExportInfo(dest):
2401
  """Get export configuration information.
2402

2403
  @type dest: str
2404
  @param dest: directory containing the export
2405

2406
  @rtype: L{objects.SerializableConfigParser}
2407
  @return: a serializable config file containing the
2408
      export info
2409

2410
  """
2411
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2412

    
2413
  config = objects.SerializableConfigParser()
2414
  config.read(cff)
2415

    
2416
  if (not config.has_section(constants.INISECT_EXP) or
2417
      not config.has_section(constants.INISECT_INS)):
2418
    _Fail("Export info file doesn't have the required fields")
2419

    
2420
  return config.Dumps()
2421

    
2422

    
2423
def ListExports():
2424
  """Return a list of exports currently available on this machine.
2425

2426
  @rtype: list
2427
  @return: list of the exports
2428

2429
  """
2430
  if os.path.isdir(constants.EXPORT_DIR):
2431
    return sorted(utils.ListVisibleFiles(constants.EXPORT_DIR))
2432
  else:
2433
    _Fail("No exports directory")
2434

    
2435

    
2436
def RemoveExport(export):
2437
  """Remove an existing export from the node.
2438

2439
  @type export: str
2440
  @param export: the name of the export to remove
2441
  @rtype: None
2442

2443
  """
2444
  target = utils.PathJoin(constants.EXPORT_DIR, export)
2445

    
2446
  try:
2447
    shutil.rmtree(target)
2448
  except EnvironmentError, err:
2449
    _Fail("Error while removing the export: %s", err, exc=True)
2450

    
2451

    
2452
def BlockdevRename(devlist):
2453
  """Rename a list of block devices.
2454

2455
  @type devlist: list of tuples
2456
  @param devlist: list of tuples of the form  (disk,
2457
      new_logical_id, new_physical_id); disk is an
2458
      L{objects.Disk} object describing the current disk,
2459
      and new logical_id/physical_id is the name we
2460
      rename it to
2461
  @rtype: boolean
2462
  @return: True if all renames succeeded, False otherwise
2463

2464
  """
2465
  msgs = []
2466
  result = True
2467
  for disk, unique_id in devlist:
2468
    dev = _RecursiveFindBD(disk)
2469
    if dev is None:
2470
      msgs.append("Can't find device %s in rename" % str(disk))
2471
      result = False
2472
      continue
2473
    try:
2474
      old_rpath = dev.dev_path
2475
      dev.Rename(unique_id)
2476
      new_rpath = dev.dev_path
2477
      if old_rpath != new_rpath:
2478
        DevCacheManager.RemoveCache(old_rpath)
2479
        # FIXME: we should add the new cache information here, like:
2480
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2481
        # but we don't have the owner here - maybe parse from existing
2482
        # cache? for now, we only lose lvm data when we rename, which
2483
        # is less critical than DRBD or MD
2484
    except errors.BlockDeviceError, err:
2485
      msgs.append("Can't rename device '%s' to '%s': %s" %
2486
                  (dev, unique_id, err))
2487
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2488
      result = False
2489
  if not result:
2490
    _Fail("; ".join(msgs))
2491

    
2492

    
2493
def _TransformFileStorageDir(fs_dir):
2494
  """Checks whether given file_storage_dir is valid.
2495

2496
  Checks wheter the given fs_dir is within the cluster-wide default
2497
  file_storage_dir or the shared_file_storage_dir, which are stored in
2498
  SimpleStore. Only paths under those directories are allowed.
2499

2500
  @type fs_dir: str
2501
  @param fs_dir: the path to check
2502

2503
  @return: the normalized path if valid, None otherwise
2504

2505
  """
2506
  if not constants.ENABLE_FILE_STORAGE:
2507
    _Fail("File storage disabled at configure time")
2508
  cfg = _GetConfig()
2509
  fs_dir = os.path.normpath(fs_dir)
2510
  base_fstore = cfg.GetFileStorageDir()
2511
  base_shared = cfg.GetSharedFileStorageDir()
2512
  if not (utils.IsBelowDir(base_fstore, fs_dir) or
2513
          utils.IsBelowDir(base_shared, fs_dir)):
2514
    _Fail("File storage directory '%s' is not under base file"
2515
          " storage directory '%s' or shared storage directory '%s'",
2516
          fs_dir, base_fstore, base_shared)
2517
  return fs_dir
2518

    
2519

    
2520
def CreateFileStorageDir(file_storage_dir):
2521
  """Create file storage directory.
2522

2523
  @type file_storage_dir: str
2524
  @param file_storage_dir: directory to create
2525

2526
  @rtype: tuple
2527
  @return: tuple with first element a boolean indicating wheter dir
2528
      creation was successful or not
2529

2530
  """
2531
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2532
  if os.path.exists(file_storage_dir):
2533
    if not os.path.isdir(file_storage_dir):
2534
      _Fail("Specified storage dir '%s' is not a directory",
2535
            file_storage_dir)
2536
  else:
2537
    try:
2538
      os.makedirs(file_storage_dir, 0750)
2539
    except OSError, err:
2540
      _Fail("Cannot create file storage directory '%s': %s",
2541
            file_storage_dir, err, exc=True)
2542

    
2543

    
2544
def RemoveFileStorageDir(file_storage_dir):
2545
  """Remove file storage directory.
2546

2547
  Remove it only if it's empty. If not log an error and return.
2548

2549
  @type file_storage_dir: str
2550
  @param file_storage_dir: the directory we should cleanup
2551
  @rtype: tuple (success,)
2552
  @return: tuple of one element, C{success}, denoting
2553
      whether the operation was successful
2554

2555
  """
2556
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2557
  if os.path.exists(file_storage_dir):
2558
    if not os.path.isdir(file_storage_dir):
2559
      _Fail("Specified Storage directory '%s' is not a directory",
2560
            file_storage_dir)
2561
    # deletes dir only if empty, otherwise we want to fail the rpc call
2562
    try:
2563
      os.rmdir(file_storage_dir)
2564
    except OSError, err:
2565
      _Fail("Cannot remove file storage directory '%s': %s",
2566
            file_storage_dir, err)
2567

    
2568

    
2569
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2570
  """Rename the file storage directory.
2571

2572
  @type old_file_storage_dir: str
2573
  @param old_file_storage_dir: the current path
2574
  @type new_file_storage_dir: str
2575
  @param new_file_storage_dir: the name we should rename to
2576
  @rtype: tuple (success,)
2577
  @return: tuple of one element, C{success}, denoting
2578
      whether the operation was successful
2579

2580
  """
2581
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2582
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2583
  if not os.path.exists(new_file_storage_dir):
2584
    if os.path.isdir(old_file_storage_dir):
2585
      try:
2586
        os.rename(old_file_storage_dir, new_file_storage_dir)
2587
      except OSError, err:
2588
        _Fail("Cannot rename '%s' to '%s': %s",
2589
              old_file_storage_dir, new_file_storage_dir, err)
2590
    else:
2591
      _Fail("Specified storage dir '%s' is not a directory",
2592
            old_file_storage_dir)
2593
  else:
2594
    if os.path.exists(old_file_storage_dir):
2595
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2596
            old_file_storage_dir, new_file_storage_dir)
2597

    
2598

    
2599
def _EnsureJobQueueFile(file_name):
2600
  """Checks whether the given filename is in the queue directory.
2601

2602
  @type file_name: str
2603
  @param file_name: the file name we should check
2604
  @rtype: None
2605
  @raises RPCFail: if the file is not valid
2606

2607
  """
2608
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2609
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2610

    
2611
  if not result:
2612
    _Fail("Passed job queue file '%s' does not belong to"
2613
          " the queue directory '%s'", file_name, queue_dir)
2614

    
2615

    
2616
def JobQueueUpdate(file_name, content):
2617
  """Updates a file in the queue directory.
2618

2619
  This is just a wrapper over L{utils.io.WriteFile}, with proper
2620
  checking.
2621

2622
  @type file_name: str
2623
  @param file_name: the job file name
2624
  @type content: str
2625
  @param content: the new job contents
2626
  @rtype: boolean
2627
  @return: the success of the operation
2628

2629
  """
2630
  _EnsureJobQueueFile(file_name)
2631
  getents = runtime.GetEnts()
2632

    
2633
  # Write and replace the file atomically
2634
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
2635
                  gid=getents.masterd_gid)
2636

    
2637

    
2638
def JobQueueRename(old, new):
2639
  """Renames a job queue file.
2640

2641
  This is just a wrapper over os.rename with proper checking.
2642

2643
  @type old: str
2644
  @param old: the old (actual) file name
2645
  @type new: str
2646
  @param new: the desired file name
2647
  @rtype: tuple
2648
  @return: the success of the operation and payload
2649

2650
  """
2651
  _EnsureJobQueueFile(old)
2652
  _EnsureJobQueueFile(new)
2653

    
2654
  utils.RenameFile(old, new, mkdir=True)
2655

    
2656

    
2657
def BlockdevClose(instance_name, disks):
2658
  """Closes the given block devices.
2659

2660
  This means they will be switched to secondary mode (in case of
2661
  DRBD).
2662

2663
  @param instance_name: if the argument is not empty, the symlinks
2664
      of this instance will be removed
2665
  @type disks: list of L{objects.Disk}
2666
  @param disks: the list of disks to be closed
2667
  @rtype: tuple (success, message)
2668
  @return: a tuple of success and message, where success
2669
      indicates the succes of the operation, and message
2670
      which will contain the error details in case we
2671
      failed
2672

2673
  """
2674
  bdevs = []
2675
  for cf in disks:
2676
    rd = _RecursiveFindBD(cf)
2677
    if rd is None:
2678
      _Fail("Can't find device %s", cf)
2679
    bdevs.append(rd)
2680

    
2681
  msg = []
2682
  for rd in bdevs:
2683
    try:
2684
      rd.Close()
2685
    except errors.BlockDeviceError, err:
2686
      msg.append(str(err))
2687
  if msg:
2688
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2689
  else:
2690
    if instance_name:
2691
      _RemoveBlockDevLinks(instance_name, disks)
2692

    
2693

    
2694
def ValidateHVParams(hvname, hvparams):
2695
  """Validates the given hypervisor parameters.
2696

2697
  @type hvname: string
2698
  @param hvname: the hypervisor name
2699
  @type hvparams: dict
2700
  @param hvparams: the hypervisor parameters to be validated
2701
  @rtype: None
2702

2703
  """
2704
  try:
2705
    hv_type = hypervisor.GetHypervisor(hvname)
2706
    hv_type.ValidateParameters(hvparams)
2707
  except errors.HypervisorError, err:
2708
    _Fail(str(err), log=False)
2709

    
2710

    
2711
def _CheckOSPList(os_obj, parameters):
2712
  """Check whether a list of parameters is supported by the OS.
2713

2714
  @type os_obj: L{objects.OS}
2715
  @param os_obj: OS object to check
2716
  @type parameters: list
2717
  @param parameters: the list of parameters to check
2718

2719
  """
2720
  supported = [v[0] for v in os_obj.supported_parameters]
2721
  delta = frozenset(parameters).difference(supported)
2722
  if delta:
2723
    _Fail("The following parameters are not supported"
2724
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
2725

    
2726

    
2727
def ValidateOS(required, osname, checks, osparams):
2728
  """Validate the given OS' parameters.
2729

2730
  @type required: boolean
2731
  @param required: whether absence of the OS should translate into
2732
      failure or not
2733
  @type osname: string
2734
  @param osname: the OS to be validated
2735
  @type checks: list
2736
  @param checks: list of the checks to run (currently only 'parameters')
2737
  @type osparams: dict
2738
  @param osparams: dictionary with OS parameters
2739
  @rtype: boolean
2740
  @return: True if the validation passed, or False if the OS was not
2741
      found and L{required} was false
2742

2743
  """
2744
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
2745
    _Fail("Unknown checks required for OS %s: %s", osname,
2746
          set(checks).difference(constants.OS_VALIDATE_CALLS))
2747

    
2748
  name_only = objects.OS.GetName(osname)
2749
  status, tbv = _TryOSFromDisk(name_only, None)
2750

    
2751
  if not status:
2752
    if required:
2753
      _Fail(tbv)
2754
    else:
2755
      return False
2756

    
2757
  if max(tbv.api_versions) < constants.OS_API_V20:
2758
    return True
2759

    
2760
  if constants.OS_VALIDATE_PARAMETERS in checks:
2761
    _CheckOSPList(tbv, osparams.keys())
2762

    
2763
  validate_env = OSCoreEnv(osname, tbv, osparams)
2764
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
2765
                        cwd=tbv.path, reset_env=True)
2766
  if result.failed:
2767
    logging.error("os validate command '%s' returned error: %s output: %s",
2768
                  result.cmd, result.fail_reason, result.output)
2769
    _Fail("OS validation script failed (%s), output: %s",
2770
          result.fail_reason, result.output, log=False)
2771

    
2772
  return True
2773

    
2774

    
2775
def DemoteFromMC():
2776
  """Demotes the current node from master candidate role.
2777

2778
  """
2779
  # try to ensure we're not the master by mistake
2780
  master, myself = ssconf.GetMasterAndMyself()
2781
  if master == myself:
2782
    _Fail("ssconf status shows I'm the master node, will not demote")
2783

    
2784
  result = utils.RunCmd([constants.DAEMON_UTIL, "check", constants.MASTERD])
2785
  if not result.failed:
2786
    _Fail("The master daemon is running, will not demote")
2787

    
2788
  try:
2789
    if os.path.isfile(constants.CLUSTER_CONF_FILE):
2790
      utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2791
  except EnvironmentError, err:
2792
    if err.errno != errno.ENOENT:
2793
      _Fail("Error while backing up cluster file: %s", err, exc=True)
2794

    
2795
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2796

    
2797

    
2798
def _GetX509Filenames(cryptodir, name):
2799
  """Returns the full paths for the private key and certificate.
2800

2801
  """
2802
  return (utils.PathJoin(cryptodir, name),
2803
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
2804
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
2805

    
2806

    
2807
def CreateX509Certificate(validity, cryptodir=constants.CRYPTO_KEYS_DIR):
2808
  """Creates a new X509 certificate for SSL/TLS.
2809

2810
  @type validity: int
2811
  @param validity: Validity in seconds
2812
  @rtype: tuple; (string, string)
2813
  @return: Certificate name and public part
2814

2815
  """
2816
  (key_pem, cert_pem) = \
2817
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
2818
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
2819

    
2820
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
2821
                              prefix="x509-%s-" % utils.TimestampForFilename())
2822
  try:
2823
    name = os.path.basename(cert_dir)
2824
    assert len(name) > 5
2825

    
2826
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2827

    
2828
    utils.WriteFile(key_file, mode=0400, data=key_pem)
2829
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
2830

    
2831
    # Never return private key as it shouldn't leave the node
2832
    return (name, cert_pem)
2833
  except Exception:
2834
    shutil.rmtree(cert_dir, ignore_errors=True)
2835
    raise
2836

    
2837

    
2838
def RemoveX509Certificate(name, cryptodir=constants.CRYPTO_KEYS_DIR):
2839
  """Removes a X509 certificate.
2840

2841
  @type name: string
2842
  @param name: Certificate name
2843

2844
  """
2845
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2846

    
2847
  utils.RemoveFile(key_file)
2848
  utils.RemoveFile(cert_file)
2849

    
2850
  try:
2851
    os.rmdir(cert_dir)
2852
  except EnvironmentError, err:
2853
    _Fail("Cannot remove certificate directory '%s': %s",
2854
          cert_dir, err)
2855

    
2856

    
2857
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
2858
  """Returns the command for the requested input/output.
2859

2860
  @type instance: L{objects.Instance}
2861
  @param instance: The instance object
2862
  @param mode: Import/export mode
2863
  @param ieio: Input/output type
2864
  @param ieargs: Input/output arguments
2865

2866
  """
2867
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
2868

    
2869
  env = None
2870
  prefix = None
2871
  suffix = None
2872
  exp_size = None
2873

    
2874
  if ieio == constants.IEIO_FILE:
2875
    (filename, ) = ieargs
2876

    
2877
    if not utils.IsNormAbsPath(filename):
2878
      _Fail("Path '%s' is not normalized or absolute", filename)
2879

    
2880
    real_filename = os.path.realpath(filename)
2881
    directory = os.path.dirname(real_filename)
2882

    
2883
    if not utils.IsBelowDir(constants.EXPORT_DIR, real_filename):
2884
      _Fail("File '%s' is not under exports directory '%s': %s",
2885
            filename, constants.EXPORT_DIR, real_filename)
2886

    
2887
    # Create directory
2888
    utils.Makedirs(directory, mode=0750)
2889

    
2890
    quoted_filename = utils.ShellQuote(filename)
2891

    
2892
    if mode == constants.IEM_IMPORT:
2893
      suffix = "> %s" % quoted_filename
2894
    elif mode == constants.IEM_EXPORT:
2895
      suffix = "< %s" % quoted_filename
2896

    
2897
      # Retrieve file size
2898
      try:
2899
        st = os.stat(filename)
2900
      except EnvironmentError, err:
2901
        logging.error("Can't stat(2) %s: %s", filename, err)
2902
      else:
2903
        exp_size = utils.BytesToMebibyte(st.st_size)
2904

    
2905
  elif ieio == constants.IEIO_RAW_DISK:
2906
    (disk, ) = ieargs
2907

    
2908
    real_disk = _OpenRealBD(disk)
2909

    
2910
    if mode == constants.IEM_IMPORT:
2911
      # we set here a smaller block size as, due to transport buffering, more
2912
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
2913
      # is not already there or we pass a wrong path; we use notrunc to no
2914
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
2915
      # much memory; this means that at best, we flush every 64k, which will
2916
      # not be very fast
2917
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
2918
                                    " bs=%s oflag=dsync"),
2919
                                    real_disk.dev_path,
2920
                                    str(64 * 1024))
2921

    
2922
    elif mode == constants.IEM_EXPORT:
2923
      # the block size on the read dd is 1MiB to match our units
2924
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
2925
                                   real_disk.dev_path,
2926
                                   str(1024 * 1024), # 1 MB
2927
                                   str(disk.size))
2928
      exp_size = disk.size
2929

    
2930
  elif ieio == constants.IEIO_SCRIPT:
2931
    (disk, disk_index, ) = ieargs
2932

    
2933
    assert isinstance(disk_index, (int, long))
2934

    
2935
    real_disk = _OpenRealBD(disk)
2936

    
2937
    inst_os = OSFromDisk(instance.os)
2938
    env = OSEnvironment(instance, inst_os)
2939

    
2940
    if mode == constants.IEM_IMPORT:
2941
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
2942
      env["IMPORT_INDEX"] = str(disk_index)
2943
      script = inst_os.import_script
2944

    
2945
    elif mode == constants.IEM_EXPORT:
2946
      env["EXPORT_DEVICE"] = real_disk.dev_path
2947
      env["EXPORT_INDEX"] = str(disk_index)
2948
      script = inst_os.export_script
2949

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

    
2953
    if mode == constants.IEM_IMPORT:
2954
      suffix = "| %s" % script_cmd
2955

    
2956
    elif mode == constants.IEM_EXPORT:
2957
      prefix = "%s |" % script_cmd
2958

    
2959
    # Let script predict size
2960
    exp_size = constants.IE_CUSTOM_SIZE
2961

    
2962
  else:
2963
    _Fail("Invalid %s I/O mode %r", mode, ieio)
2964

    
2965
  return (env, prefix, suffix, exp_size)
2966

    
2967

    
2968
def _CreateImportExportStatusDir(prefix):
2969
  """Creates status directory for import/export.
2970

2971
  """
2972
  return tempfile.mkdtemp(dir=constants.IMPORT_EXPORT_DIR,
2973
                          prefix=("%s-%s-" %
2974
                                  (prefix, utils.TimestampForFilename())))
2975

    
2976

    
2977
def StartImportExportDaemon(mode, opts, host, port, instance, component,
2978
                            ieio, ieioargs):
2979
  """Starts an import or export daemon.
2980

2981
  @param mode: Import/output mode
2982
  @type opts: L{objects.ImportExportOptions}
2983
  @param opts: Daemon options
2984
  @type host: string
2985
  @param host: Remote host for export (None for import)
2986
  @type port: int
2987
  @param port: Remote port for export (None for import)
2988
  @type instance: L{objects.Instance}
2989
  @param instance: Instance object
2990
  @type component: string
2991
  @param component: which part of the instance is transferred now,
2992
      e.g. 'disk/0'
2993
  @param ieio: Input/output type
2994
  @param ieioargs: Input/output arguments
2995

2996
  """
2997
  if mode == constants.IEM_IMPORT:
2998
    prefix = "import"
2999

    
3000
    if not (host is None and port is None):
3001
      _Fail("Can not specify host or port on import")
3002

    
3003
  elif mode == constants.IEM_EXPORT:
3004
    prefix = "export"
3005

    
3006
    if host is None or port is None:
3007
      _Fail("Host and port must be specified for an export")
3008

    
3009
  else:
3010
    _Fail("Invalid mode %r", mode)
3011

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

    
3015
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3016
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3017

    
3018
  if opts.key_name is None:
3019
    # Use server.pem
3020
    key_path = constants.NODED_CERT_FILE
3021
    cert_path = constants.NODED_CERT_FILE
3022
    assert opts.ca_pem is None
3023
  else:
3024
    (_, key_path, cert_path) = _GetX509Filenames(constants.CRYPTO_KEYS_DIR,
3025
                                                 opts.key_name)
3026
    assert opts.ca_pem is not None
3027

    
3028
  for i in [key_path, cert_path]:
3029
    if not os.path.exists(i):
3030
      _Fail("File '%s' does not exist" % i)
3031

    
3032
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3033
  try:
3034
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3035
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3036
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3037

    
3038
    if opts.ca_pem is None:
3039
      # Use server.pem
3040
      ca = utils.ReadFile(constants.NODED_CERT_FILE)
3041
    else:
3042
      ca = opts.ca_pem
3043

    
3044
    # Write CA file
3045
    utils.WriteFile(ca_file, data=ca, mode=0400)
3046

    
3047
    cmd = [
3048
      constants.IMPORT_EXPORT_DAEMON,
3049
      status_file, mode,
3050
      "--key=%s" % key_path,
3051
      "--cert=%s" % cert_path,
3052
      "--ca=%s" % ca_file,
3053
      ]
3054

    
3055
    if host:
3056
      cmd.append("--host=%s" % host)
3057

    
3058
    if port:
3059
      cmd.append("--port=%s" % port)
3060

    
3061
    if opts.ipv6:
3062
      cmd.append("--ipv6")
3063
    else:
3064
      cmd.append("--ipv4")
3065

    
3066
    if opts.compress:
3067
      cmd.append("--compress=%s" % opts.compress)
3068

    
3069
    if opts.magic:
3070
      cmd.append("--magic=%s" % opts.magic)
3071

    
3072
    if exp_size is not None:
3073
      cmd.append("--expected-size=%s" % exp_size)
3074

    
3075
    if cmd_prefix:
3076
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3077

    
3078
    if cmd_suffix:
3079
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3080

    
3081
    if mode == constants.IEM_EXPORT:
3082
      # Retry connection a few times when connecting to remote peer
3083
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3084
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3085
    elif opts.connect_timeout is not None:
3086
      assert mode == constants.IEM_IMPORT
3087
      # Overall timeout for establishing connection while listening
3088
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3089

    
3090
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3091

    
3092
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3093
    # support for receiving a file descriptor for output
3094
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3095
                      output=logfile)
3096

    
3097
    # The import/export name is simply the status directory name
3098
    return os.path.basename(status_dir)
3099

    
3100
  except Exception:
3101
    shutil.rmtree(status_dir, ignore_errors=True)
3102
    raise
3103

    
3104

    
3105
def GetImportExportStatus(names):
3106
  """Returns import/export daemon status.
3107

3108
  @type names: sequence
3109
  @param names: List of names
3110
  @rtype: List of dicts
3111
  @return: Returns a list of the state of each named import/export or None if a
3112
           status couldn't be read
3113

3114
  """
3115
  result = []
3116

    
3117
  for name in names:
3118
    status_file = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name,
3119
                                 _IES_STATUS_FILE)
3120

    
3121
    try:
3122
      data = utils.ReadFile(status_file)
3123
    except EnvironmentError, err:
3124
      if err.errno != errno.ENOENT:
3125
        raise
3126
      data = None
3127

    
3128
    if not data:
3129
      result.append(None)
3130
      continue
3131

    
3132
    result.append(serializer.LoadJson(data))
3133

    
3134
  return result
3135

    
3136

    
3137
def AbortImportExport(name):
3138
  """Sends SIGTERM to a running import/export daemon.
3139

3140
  """
3141
  logging.info("Abort import/export %s", name)
3142

    
3143
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3144
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3145

    
3146
  if pid:
3147
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3148
                 name, pid)
3149
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3150

    
3151

    
3152
def CleanupImportExport(name):
3153
  """Cleanup after an import or export.
3154

3155
  If the import/export daemon is still running it's killed. Afterwards the
3156
  whole status directory is removed.
3157

3158
  """
3159
  logging.info("Finalizing import/export %s", name)
3160

    
3161
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3162

    
3163
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3164

    
3165
  if pid:
3166
    logging.info("Import/export %s is still running with PID %s",
3167
                 name, pid)
3168
    utils.KillProcess(pid, waitpid=False)
3169

    
3170
  shutil.rmtree(status_dir, ignore_errors=True)
3171

    
3172

    
3173
def _FindDisks(nodes_ip, disks):
3174
  """Sets the physical ID on disks and returns the block devices.
3175

3176
  """
3177
  # set the correct physical ID
3178
  my_name = netutils.Hostname.GetSysName()
3179
  for cf in disks:
3180
    cf.SetPhysicalID(my_name, nodes_ip)
3181

    
3182
  bdevs = []
3183

    
3184
  for cf in disks:
3185
    rd = _RecursiveFindBD(cf)
3186
    if rd is None:
3187
      _Fail("Can't find device %s", cf)
3188
    bdevs.append(rd)
3189
  return bdevs
3190

    
3191

    
3192
def DrbdDisconnectNet(nodes_ip, disks):
3193
  """Disconnects the network on a list of drbd devices.
3194

3195
  """
3196
  bdevs = _FindDisks(nodes_ip, disks)
3197

    
3198
  # disconnect disks
3199
  for rd in bdevs:
3200
    try:
3201
      rd.DisconnectNet()
3202
    except errors.BlockDeviceError, err:
3203
      _Fail("Can't change network configuration to standalone mode: %s",
3204
            err, exc=True)
3205

    
3206

    
3207
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3208
  """Attaches the network on a list of drbd devices.
3209

3210
  """
3211
  bdevs = _FindDisks(nodes_ip, disks)
3212

    
3213
  if multimaster:
3214
    for idx, rd in enumerate(bdevs):
3215
      try:
3216
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3217
      except EnvironmentError, err:
3218
        _Fail("Can't create symlink: %s", err)
3219
  # reconnect disks, switch to new master configuration and if
3220
  # needed primary mode
3221
  for rd in bdevs:
3222
    try:
3223
      rd.AttachNet(multimaster)
3224
    except errors.BlockDeviceError, err:
3225
      _Fail("Can't change network configuration: %s", err)
3226

    
3227
  # wait until the disks are connected; we need to retry the re-attach
3228
  # if the device becomes standalone, as this might happen if the one
3229
  # node disconnects and reconnects in a different mode before the
3230
  # other node reconnects; in this case, one or both of the nodes will
3231
  # decide it has wrong configuration and switch to standalone
3232

    
3233
  def _Attach():
3234
    all_connected = True
3235

    
3236
    for rd in bdevs:
3237
      stats = rd.GetProcStatus()
3238

    
3239
      all_connected = (all_connected and
3240
                       (stats.is_connected or stats.is_in_resync))
3241

    
3242
      if stats.is_standalone:
3243
        # peer had different config info and this node became
3244
        # standalone, even though this should not happen with the
3245
        # new staged way of changing disk configs
3246
        try:
3247
          rd.AttachNet(multimaster)
3248
        except errors.BlockDeviceError, err:
3249
          _Fail("Can't change network configuration: %s", err)
3250

    
3251
    if not all_connected:
3252
      raise utils.RetryAgain()
3253

    
3254
  try:
3255
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3256
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3257
  except utils.RetryTimeout:
3258
    _Fail("Timeout in disk reconnecting")
3259

    
3260
  if multimaster:
3261
    # change to primary mode
3262
    for rd in bdevs:
3263
      try:
3264
        rd.Open()
3265
      except errors.BlockDeviceError, err:
3266
        _Fail("Can't change to primary mode: %s", err)
3267

    
3268

    
3269
def DrbdWaitSync(nodes_ip, disks):
3270
  """Wait until DRBDs have synchronized.
3271

3272
  """
3273
  def _helper(rd):
3274
    stats = rd.GetProcStatus()
3275
    if not (stats.is_connected or stats.is_in_resync):
3276
      raise utils.RetryAgain()
3277
    return stats
3278

    
3279
  bdevs = _FindDisks(nodes_ip, disks)
3280

    
3281
  min_resync = 100
3282
  alldone = True
3283
  for rd in bdevs:
3284
    try:
3285
      # poll each second for 15 seconds
3286
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3287
    except utils.RetryTimeout:
3288
      stats = rd.GetProcStatus()
3289
      # last check
3290
      if not (stats.is_connected or stats.is_in_resync):
3291
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3292
    alldone = alldone and (not stats.is_in_resync)
3293
    if stats.sync_percent is not None:
3294
      min_resync = min(min_resync, stats.sync_percent)
3295

    
3296
  return (alldone, min_resync)
3297

    
3298

    
3299
def GetDrbdUsermodeHelper():
3300
  """Returns DRBD usermode helper currently configured.
3301

3302
  """
3303
  try:
3304
    return bdev.BaseDRBD.GetUsermodeHelper()
3305
  except errors.BlockDeviceError, err:
3306
    _Fail(str(err))
3307

    
3308

    
3309
def PowercycleNode(hypervisor_type):
3310
  """Hard-powercycle the node.
3311

3312
  Because we need to return first, and schedule the powercycle in the
3313
  background, we won't be able to report failures nicely.
3314

3315
  """
3316
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3317
  try:
3318
    pid = os.fork()
3319
  except OSError:
3320
    # if we can't fork, we'll pretend that we're in the child process
3321
    pid = 0
3322
  if pid > 0:
3323
    return "Reboot scheduled in 5 seconds"
3324
  # ensure the child is running on ram
3325
  try:
3326
    utils.Mlockall()
3327
  except Exception: # pylint: disable=W0703
3328
    pass
3329
  time.sleep(5)
3330
  hyper.PowercycleNode()
3331

    
3332

    
3333
class HooksRunner(object):
3334
  """Hook runner.
3335

3336
  This class is instantiated on the node side (ganeti-noded) and not
3337
  on the master side.
3338

3339
  """
3340
  def __init__(self, hooks_base_dir=None):
3341
    """Constructor for hooks runner.
3342

3343
    @type hooks_base_dir: str or None
3344
    @param hooks_base_dir: if not None, this overrides the
3345
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
3346

3347
    """
3348
    if hooks_base_dir is None:
3349
      hooks_base_dir = constants.HOOKS_BASE_DIR
3350
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3351
    # constant
3352
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
3353

    
3354
  def RunHooks(self, hpath, phase, env):
3355
    """Run the scripts in the hooks directory.
3356

3357
    @type hpath: str
3358
    @param hpath: the path to the hooks directory which
3359
        holds the scripts
3360
    @type phase: str
3361
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
3362
        L{constants.HOOKS_PHASE_POST}
3363
    @type env: dict
3364
    @param env: dictionary with the environment for the hook
3365
    @rtype: list
3366
    @return: list of 3-element tuples:
3367
      - script path
3368
      - script result, either L{constants.HKR_SUCCESS} or
3369
        L{constants.HKR_FAIL}
3370
      - output of the script
3371

3372
    @raise errors.ProgrammerError: for invalid input
3373
        parameters
3374

3375
    """
3376
    if phase == constants.HOOKS_PHASE_PRE:
3377
      suffix = "pre"
3378
    elif phase == constants.HOOKS_PHASE_POST:
3379
      suffix = "post"
3380
    else:
3381
      _Fail("Unknown hooks phase '%s'", phase)
3382

    
3383
    subdir = "%s-%s.d" % (hpath, suffix)
3384
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3385

    
3386
    results = []
3387

    
3388
    if not os.path.isdir(dir_name):
3389
      # for non-existing/non-dirs, we simply exit instead of logging a
3390
      # warning at every operation
3391
      return results
3392

    
3393
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3394

    
3395
    for (relname, relstatus, runresult)  in runparts_results:
3396
      if relstatus == constants.RUNPARTS_SKIP:
3397
        rrval = constants.HKR_SKIP
3398
        output = ""
3399
      elif relstatus == constants.RUNPARTS_ERR:
3400
        rrval = constants.HKR_FAIL
3401
        output = "Hook script execution error: %s" % runresult
3402
      elif relstatus == constants.RUNPARTS_RUN:
3403
        if runresult.failed:
3404
          rrval = constants.HKR_FAIL
3405
        else:
3406
          rrval = constants.HKR_SUCCESS
3407
        output = utils.SafeEncode(runresult.output.strip())
3408
      results.append(("%s/%s" % (subdir, relname), rrval, output))
3409

    
3410
    return results
3411

    
3412

    
3413
class IAllocatorRunner(object):
3414
  """IAllocator runner.
3415

3416
  This class is instantiated on the node side (ganeti-noded) and not on
3417
  the master side.
3418

3419
  """
3420
  @staticmethod
3421
  def Run(name, idata):
3422
    """Run an iallocator script.
3423

3424
    @type name: str
3425
    @param name: the iallocator script name
3426
    @type idata: str
3427
    @param idata: the allocator input data
3428

3429
    @rtype: tuple
3430
    @return: two element tuple of:
3431
       - status
3432
       - either error message or stdout of allocator (for success)
3433

3434
    """
3435
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
3436
                                  os.path.isfile)
3437
    if alloc_script is None:
3438
      _Fail("iallocator module '%s' not found in the search path", name)
3439

    
3440
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
3441
    try:
3442
      os.write(fd, idata)
3443
      os.close(fd)
3444
      result = utils.RunCmd([alloc_script, fin_name])
3445
      if result.failed:
3446
        _Fail("iallocator module '%s' failed: %s, output '%s'",
3447
              name, result.fail_reason, result.output)
3448
    finally:
3449
      os.unlink(fin_name)
3450

    
3451
    return result.stdout
3452

    
3453

    
3454
class DevCacheManager(object):
3455
  """Simple class for managing a cache of block device information.
3456

3457
  """
3458
  _DEV_PREFIX = "/dev/"
3459
  _ROOT_DIR = constants.BDEV_CACHE_DIR
3460

    
3461
  @classmethod
3462
  def _ConvertPath(cls, dev_path):
3463
    """Converts a /dev/name path to the cache file name.
3464

3465
    This replaces slashes with underscores and strips the /dev
3466
    prefix. It then returns the full path to the cache file.
3467

3468
    @type dev_path: str
3469
    @param dev_path: the C{/dev/} path name
3470
    @rtype: str
3471
    @return: the converted path name
3472

3473
    """
3474
    if dev_path.startswith(cls._DEV_PREFIX):
3475
      dev_path = dev_path[len(cls._DEV_PREFIX):]
3476
    dev_path = dev_path.replace("/", "_")
3477
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
3478
    return fpath
3479

    
3480
  @classmethod
3481
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
3482
    """Updates the cache information for a given device.
3483

3484
    @type dev_path: str
3485
    @param dev_path: the pathname of the device
3486
    @type owner: str
3487
    @param owner: the owner (instance name) of the device
3488
    @type on_primary: bool
3489
    @param on_primary: whether this is the primary
3490
        node nor not
3491
    @type iv_name: str
3492
    @param iv_name: the instance-visible name of the
3493
        device, as in objects.Disk.iv_name
3494

3495
    @rtype: None
3496

3497
    """
3498
    if dev_path is None:
3499
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
3500
      return
3501
    fpath = cls._ConvertPath(dev_path)
3502
    if on_primary:
3503
      state = "primary"
3504
    else:
3505
      state = "secondary"
3506
    if iv_name is None:
3507
      iv_name = "not_visible"
3508
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
3509
    try:
3510
      utils.WriteFile(fpath, data=fdata)
3511
    except EnvironmentError, err:
3512
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
3513

    
3514
  @classmethod
3515
  def RemoveCache(cls, dev_path):
3516
    """Remove data for a dev_path.
3517

3518
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
3519
    path name and logging.
3520

3521
    @type dev_path: str
3522
    @param dev_path: the pathname of the device
3523

3524
    @rtype: None
3525

3526
    """
3527
    if dev_path is None:
3528
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
3529
      return
3530
    fpath = cls._ConvertPath(dev_path)
3531
    try:
3532
      utils.RemoveFile(fpath)
3533
    except EnvironmentError, err:
3534
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)