Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ cb6a0296

History | View | Annotate | Download (100.1 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010 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-msg=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

    
80
class RPCFail(Exception):
81
  """Class denoting RPC failure.
82

83
  Its argument is the error message.
84

85
  """
86

    
87

    
88
def _Fail(msg, *args, **kwargs):
89
  """Log an error and the raise an RPCFail exception.
90

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

96
  @type msg: string
97
  @param msg: the text of the exception
98
  @raise RPCFail
99

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

    
110

    
111
def _GetConfig():
112
  """Simple wrapper to return a SimpleStore.
113

114
  @rtype: L{ssconf.SimpleStore}
115
  @return: a SimpleStore instance
116

117
  """
118
  return ssconf.SimpleStore()
119

    
120

    
121
def _GetSshRunner(cluster_name):
122
  """Simple wrapper to return an SshRunner.
123

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

130
  """
131
  return ssh.SshRunner(cluster_name)
132

    
133

    
134
def _Decompress(data):
135
  """Unpacks data compressed by the RPC client.
136

137
  @type data: list or tuple
138
  @param data: Data sent by RPC client
139
  @rtype: str
140
  @return: Decompressed data
141

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

    
153

    
154
def _CleanDirectory(path, exclude=None):
155
  """Removes all regular files in a directory.
156

157
  @type path: str
158
  @param path: the directory to clean
159
  @type exclude: list
160
  @param exclude: list of files to be excluded, defaults
161
      to the empty list
162

163
  """
164
  if path not in _ALLOWED_CLEAN_DIRS:
165
    _Fail("Path passed to _CleanDirectory not in allowed clean targets: '%s'",
166
          path)
167

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

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

    
183

    
184
def _BuildUploadFileList():
185
  """Build the list of allowed upload files.
186

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

189
  """
190
  allowed_files = set([
191
    constants.CLUSTER_CONF_FILE,
192
    constants.ETC_HOSTS,
193
    constants.SSH_KNOWN_HOSTS_FILE,
194
    constants.VNC_PASSWORD_FILE,
195
    constants.RAPI_CERT_FILE,
196
    constants.RAPI_USERS_FILE,
197
    constants.CONFD_HMAC_KEY,
198
    constants.CLUSTER_DOMAIN_SECRET_FILE,
199
    ])
200

    
201
  for hv_name in constants.HYPER_TYPES:
202
    hv_class = hypervisor.GetHypervisorClass(hv_name)
203
    allowed_files.update(hv_class.GetAncillaryFiles())
204

    
205
  return frozenset(allowed_files)
206

    
207

    
208
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
209

    
210

    
211
def JobQueuePurge():
212
  """Removes job queue files and archived jobs.
213

214
  @rtype: tuple
215
  @return: True, None
216

217
  """
218
  _CleanDirectory(constants.QUEUE_DIR, exclude=[constants.JOB_QUEUE_LOCK_FILE])
219
  _CleanDirectory(constants.JOB_QUEUE_ARCHIVE_DIR)
220

    
221

    
222
def GetMasterInfo():
223
  """Returns master information.
224

225
  This is an utility function to compute master information, either
226
  for consumption here or from the node daemon.
227

228
  @rtype: tuple
229
  @return: master_netdev, master_ip, master_name, primary_ip_family
230
  @raise RPCFail: in case of errors
231

232
  """
233
  try:
234
    cfg = _GetConfig()
235
    master_netdev = cfg.GetMasterNetdev()
236
    master_ip = cfg.GetMasterIP()
237
    master_node = cfg.GetMasterNode()
238
    primary_ip_family = cfg.GetPrimaryIPFamily()
239
  except errors.ConfigurationError, err:
240
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
241
  return (master_netdev, master_ip, master_node, primary_ip_family)
242

    
243

    
244
def StartMaster(start_daemons, no_voting):
245
  """Activate local node as master node.
246

247
  The function will either try activate the IP address of the master
248
  (unless someone else has it) or also start the master daemons, based
249
  on the start_daemons parameter.
250

251
  @type start_daemons: boolean
252
  @param start_daemons: whether to start the master daemons
253
      (ganeti-masterd and ganeti-rapi), or (if false) activate the
254
      master ip
255
  @type no_voting: boolean
256
  @param no_voting: whether to start ganeti-masterd without a node vote
257
      (if start_daemons is True), but still non-interactively
258
  @rtype: None
259

260
  """
261
  # GetMasterInfo will raise an exception if not able to return data
262
  master_netdev, master_ip, _, family = GetMasterInfo()
263

    
264
  err_msgs = []
265
  # either start the master and rapi daemons
266
  if start_daemons:
267
    if no_voting:
268
      masterd_args = "--no-voting --yes-do-it"
269
    else:
270
      masterd_args = ""
271

    
272
    env = {
273
      "EXTRA_MASTERD_ARGS": masterd_args,
274
      }
275

    
276
    result = utils.RunCmd([constants.DAEMON_UTIL, "start-master"], env=env)
277
    if result.failed:
278
      msg = "Can't start Ganeti master: %s" % result.output
279
      logging.error(msg)
280
      err_msgs.append(msg)
281
  # or activate the IP
282
  else:
283
    if netutils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
284
      if netutils.IPAddress.Own(master_ip):
285
        # we already have the ip:
286
        logging.debug("Master IP already configured, doing nothing")
287
      else:
288
        msg = "Someone else has the master ip, not activating"
289
        logging.error(msg)
290
        err_msgs.append(msg)
291
    else:
292
      ipcls = netutils.IP4Address
293
      if family == netutils.IP6Address.family:
294
        ipcls = netutils.IP6Address
295

    
296
      result = utils.RunCmd(["ip", "address", "add",
297
                             "%s/%d" % (master_ip, ipcls.iplen),
298
                             "dev", master_netdev, "label",
299
                             "%s:0" % master_netdev])
300
      if result.failed:
301
        msg = "Can't activate master IP: %s" % result.output
302
        logging.error(msg)
303
        err_msgs.append(msg)
304

    
305
      # we ignore the exit code of the following cmds
306
      if ipcls == netutils.IP4Address:
307
        utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev, "-s",
308
                      master_ip, master_ip])
309
      elif ipcls == netutils.IP6Address:
310
        try:
311
          utils.RunCmd(["ndisc6", "-q", "-r 3", master_ip, master_netdev])
312
        except errors.OpExecError:
313
          # TODO: Better error reporting
314
          logging.warning("Can't execute ndisc6, please install if missing")
315

    
316
  if err_msgs:
317
    _Fail("; ".join(err_msgs))
318

    
319

    
320
def StopMaster(stop_daemons):
321
  """Deactivate this node as master.
322

323
  The function will always try to deactivate the IP address of the
324
  master. It will also stop the master daemons depending on the
325
  stop_daemons parameter.
326

327
  @type stop_daemons: boolean
328
  @param stop_daemons: whether to also stop the master daemons
329
      (ganeti-masterd and ganeti-rapi)
330
  @rtype: None
331

332
  """
333
  # TODO: log and report back to the caller the error failures; we
334
  # need to decide in which case we fail the RPC for this
335

    
336
  # GetMasterInfo will raise an exception if not able to return data
337
  master_netdev, master_ip, _, family = GetMasterInfo()
338

    
339
  ipcls = netutils.IP4Address
340
  if family == netutils.IP6Address.family:
341
    ipcls = netutils.IP6Address
342

    
343
  result = utils.RunCmd(["ip", "address", "del",
344
                         "%s/%d" % (master_ip, ipcls.iplen),
345
                         "dev", master_netdev])
346
  if result.failed:
347
    logging.error("Can't remove the master IP, error: %s", result.output)
348
    # but otherwise ignore the failure
349

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

    
357

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

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

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

    
379

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

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

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

390
  @param modify_ssh_setup: boolean
391

392
  """
393
  _CleanDirectory(constants.DATA_DIR)
394
  _CleanDirectory(constants.CRYPTO_KEYS_DIR)
395
  JobQueuePurge()
396

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

    
401
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
402

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

    
408
  try:
409
    utils.RemoveFile(constants.CONFD_HMAC_KEY)
410
    utils.RemoveFile(constants.RAPI_CERT_FILE)
411
    utils.RemoveFile(constants.NODED_CERT_FILE)
412
  except: # pylint: disable-msg=W0702
413
    logging.exception("Error while removing cluster secrets")
414

    
415
  result = utils.RunCmd([constants.DAEMON_UTIL, "stop", constants.CONFD])
416
  if result.failed:
417
    logging.error("Command %s failed with exitcode %s and error %s",
418
                  result.cmd, result.exit_code, result.output)
419

    
420
  # Raise a custom exception (handled in ganeti-noded)
421
  raise errors.QuitGanetiException(True, 'Shutdown scheduled')
422

    
423

    
424
def GetNodeInfo(vgname, hypervisor_type):
425
  """Gives back a hash with different information about the node.
426

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

440
  """
441
  outputarray = {}
442

    
443
  if vgname is not None:
444
    vginfo = bdev.LogicalVolume.GetVGInfo([vgname])
445
    vg_free = vg_size = None
446
    if vginfo:
447
      vg_free = int(round(vginfo[0][0], 0))
448
      vg_size = int(round(vginfo[0][1], 0))
449
    outputarray['vg_size'] = vg_size
450
    outputarray['vg_free'] = vg_free
451

    
452
  if hypervisor_type is not None:
453
    hyper = hypervisor.GetHypervisor(hypervisor_type)
454
    hyp_info = hyper.GetNodeInfo()
455
    if hyp_info is not None:
456
      outputarray.update(hyp_info)
457

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

    
460
  return outputarray
461

    
462

    
463
def VerifyNode(what, cluster_name):
464
  """Verify the status of the local node.
465

466
  Based on the input L{what} parameter, various checks are done on the
467
  local node.
468

469
  If the I{filelist} key is present, this list of
470
  files is checksummed and the file/checksum pairs are returned.
471

472
  If the I{nodelist} key is present, we check that we have
473
  connectivity via ssh with the target nodes (and check the hostname
474
  report).
475

476
  If the I{node-net-test} key is present, we check that we have
477
  connectivity to the given nodes via both primary IP and, if
478
  applicable, secondary IPs.
479

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

491
  """
492
  result = {}
493
  my_name = netutils.Hostname.GetSysName()
494
  port = netutils.GetDaemonPort(constants.NODED)
495
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
496

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

    
506
  if constants.NV_FILELIST in what:
507
    result[constants.NV_FILELIST] = utils.FingerprintFiles(
508
      what[constants.NV_FILELIST])
509

    
510
  if constants.NV_NODELIST in what:
511
    result[constants.NV_NODELIST] = tmp = {}
512
    random.shuffle(what[constants.NV_NODELIST])
513
    for node in what[constants.NV_NODELIST]:
514
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
515
      if not success:
516
        tmp[node] = message
517

    
518
  if constants.NV_NODENETTEST in what:
519
    result[constants.NV_NODENETTEST] = tmp = {}
520
    my_pip = my_sip = None
521
    for name, pip, sip in what[constants.NV_NODENETTEST]:
522
      if name == my_name:
523
        my_pip = pip
524
        my_sip = sip
525
        break
526
    if not my_pip:
527
      tmp[my_name] = ("Can't find my own primary/secondary IP"
528
                      " in the node list")
529
    else:
530
      for name, pip, sip in what[constants.NV_NODENETTEST]:
531
        fail = []
532
        if not netutils.TcpPing(pip, port, source=my_pip):
533
          fail.append("primary")
534
        if sip != pip:
535
          if not netutils.TcpPing(sip, port, source=my_sip):
536
            fail.append("secondary")
537
        if fail:
538
          tmp[name] = ("failure using the %s interface(s)" %
539
                       " and ".join(fail))
540

    
541
  if constants.NV_MASTERIP in what:
542
    # FIXME: add checks on incoming data structures (here and in the
543
    # rest of the function)
544
    master_name, master_ip = what[constants.NV_MASTERIP]
545
    if master_name == my_name:
546
      source = constants.IP4_ADDRESS_LOCALHOST
547
    else:
548
      source = None
549
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
550
                                                  source=source)
551

    
552
  if constants.NV_LVLIST in what and vm_capable:
553
    try:
554
      val = GetVolumeList(what[constants.NV_LVLIST])
555
    except RPCFail, err:
556
      val = str(err)
557
    result[constants.NV_LVLIST] = val
558

    
559
  if constants.NV_INSTANCELIST in what and vm_capable:
560
    # GetInstanceList can fail
561
    try:
562
      val = GetInstanceList(what[constants.NV_INSTANCELIST])
563
    except RPCFail, err:
564
      val = str(err)
565
    result[constants.NV_INSTANCELIST] = val
566

    
567
  if constants.NV_VGLIST in what and vm_capable:
568
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
569

    
570
  if constants.NV_PVLIST in what and vm_capable:
571
    result[constants.NV_PVLIST] = \
572
      bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
573
                                   filter_allocatable=False)
574

    
575
  if constants.NV_VERSION in what:
576
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
577
                                    constants.RELEASE_VERSION)
578

    
579
  if constants.NV_HVINFO in what and vm_capable:
580
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
581
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
582

    
583
  if constants.NV_DRBDLIST in what and vm_capable:
584
    try:
585
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
586
    except errors.BlockDeviceError, err:
587
      logging.warning("Can't get used minors list", exc_info=True)
588
      used_minors = str(err)
589
    result[constants.NV_DRBDLIST] = used_minors
590

    
591
  if constants.NV_DRBDHELPER in what and vm_capable:
592
    status = True
593
    try:
594
      payload = bdev.BaseDRBD.GetUsermodeHelper()
595
    except errors.BlockDeviceError, err:
596
      logging.error("Can't get DRBD usermode helper: %s", str(err))
597
      status = False
598
      payload = str(err)
599
    result[constants.NV_DRBDHELPER] = (status, payload)
600

    
601
  if constants.NV_NODESETUP in what:
602
    result[constants.NV_NODESETUP] = tmpr = []
603
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
604
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
605
                  " under /sys, missing required directories /sys/block"
606
                  " and /sys/class/net")
607
    if (not os.path.isdir("/proc/sys") or
608
        not os.path.isfile("/proc/sysrq-trigger")):
609
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
610
                  " under /proc, missing required directory /proc/sys and"
611
                  " the file /proc/sysrq-trigger")
612

    
613
  if constants.NV_TIME in what:
614
    result[constants.NV_TIME] = utils.SplitTime(time.time())
615

    
616
  if constants.NV_OSLIST in what and vm_capable:
617
    result[constants.NV_OSLIST] = DiagnoseOS()
618

    
619
  return result
620

    
621

    
622
def GetVolumeList(vg_name):
623
  """Compute list of logical volumes and their size.
624

625
  @type vg_name: str
626
  @param vg_name: the volume group whose LVs we should list
627
  @rtype: dict
628
  @return:
629
      dictionary of all partions (key) with value being a tuple of
630
      their size (in MiB), inactive and online status::
631

632
        {'test1': ('20.06', True, True)}
633

634
      in case of errors, a string is returned with the error
635
      details.
636

637
  """
638
  lvs = {}
639
  sep = '|'
640
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
641
                         "--separator=%s" % sep,
642
                         "-olv_name,lv_size,lv_attr", vg_name])
643
  if result.failed:
644
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
645

    
646
  valid_line_re = re.compile("^ *([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
647
  for line in result.stdout.splitlines():
648
    line = line.strip()
649
    match = valid_line_re.match(line)
650
    if not match:
651
      logging.error("Invalid line returned from lvs output: '%s'", line)
652
      continue
653
    name, size, attr = match.groups()
654
    inactive = attr[4] == '-'
655
    online = attr[5] == 'o'
656
    virtual = attr[0] == 'v'
657
    if virtual:
658
      # we don't want to report such volumes as existing, since they
659
      # don't really hold data
660
      continue
661
    lvs[name] = (size, inactive, online)
662

    
663
  return lvs
664

    
665

    
666
def ListVolumeGroups():
667
  """List the volume groups and their size.
668

669
  @rtype: dict
670
  @return: dictionary with keys volume name and values the
671
      size of the volume
672

673
  """
674
  return utils.ListVolumeGroups()
675

    
676

    
677
def NodeVolumes():
678
  """List all volumes on this node.
679

680
  @rtype: list
681
  @return:
682
    A list of dictionaries, each having four keys:
683
      - name: the logical volume name,
684
      - size: the size of the logical volume
685
      - dev: the physical device on which the LV lives
686
      - vg: the volume group to which it belongs
687

688
    In case of errors, we return an empty list and log the
689
    error.
690

691
    Note that since a logical volume can live on multiple physical
692
    volumes, the resulting list might include a logical volume
693
    multiple times.
694

695
  """
696
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
697
                         "--separator=|",
698
                         "--options=lv_name,lv_size,devices,vg_name"])
699
  if result.failed:
700
    _Fail("Failed to list logical volumes, lvs output: %s",
701
          result.output)
702

    
703
  def parse_dev(dev):
704
    return dev.split('(')[0]
705

    
706
  def handle_dev(dev):
707
    return [parse_dev(x) for x in dev.split(",")]
708

    
709
  def map_line(line):
710
    line = [v.strip() for v in line]
711
    return [{'name': line[0], 'size': line[1],
712
             'dev': dev, 'vg': line[3]} for dev in handle_dev(line[2])]
713

    
714
  all_devs = []
715
  for line in result.stdout.splitlines():
716
    if line.count('|') >= 3:
717
      all_devs.extend(map_line(line.split('|')))
718
    else:
719
      logging.warning("Strange line in the output from lvs: '%s'", line)
720
  return all_devs
721

    
722

    
723
def BridgesExist(bridges_list):
724
  """Check if a list of bridges exist on the current node.
725

726
  @rtype: boolean
727
  @return: C{True} if all of them exist, C{False} otherwise
728

729
  """
730
  missing = []
731
  for bridge in bridges_list:
732
    if not utils.BridgeExists(bridge):
733
      missing.append(bridge)
734

    
735
  if missing:
736
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
737

    
738

    
739
def GetInstanceList(hypervisor_list):
740
  """Provides a list of instances.
741

742
  @type hypervisor_list: list
743
  @param hypervisor_list: the list of hypervisors to query information
744

745
  @rtype: list
746
  @return: a list of all running instances on the current node
747
    - instance1.example.com
748
    - instance2.example.com
749

750
  """
751
  results = []
752
  for hname in hypervisor_list:
753
    try:
754
      names = hypervisor.GetHypervisor(hname).ListInstances()
755
      results.extend(names)
756
    except errors.HypervisorError, err:
757
      _Fail("Error enumerating instances (hypervisor %s): %s",
758
            hname, err, exc=True)
759

    
760
  return results
761

    
762

    
763
def GetInstanceInfo(instance, hname):
764
  """Gives back the information about an instance as a dictionary.
765

766
  @type instance: string
767
  @param instance: the instance name
768
  @type hname: string
769
  @param hname: the hypervisor type of the instance
770

771
  @rtype: dict
772
  @return: dictionary with the following keys:
773
      - memory: memory size of instance (int)
774
      - state: xen state of instance (string)
775
      - time: cpu time of instance (float)
776

777
  """
778
  output = {}
779

    
780
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
781
  if iinfo is not None:
782
    output['memory'] = iinfo[2]
783
    output['state'] = iinfo[4]
784
    output['time'] = iinfo[5]
785

    
786
  return output
787

    
788

    
789
def GetInstanceMigratable(instance):
790
  """Gives whether an instance can be migrated.
791

792
  @type instance: L{objects.Instance}
793
  @param instance: object representing the instance to be checked.
794

795
  @rtype: tuple
796
  @return: tuple of (result, description) where:
797
      - result: whether the instance can be migrated or not
798
      - description: a description of the issue, if relevant
799

800
  """
801
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
802
  iname = instance.name
803
  if iname not in hyper.ListInstances():
804
    _Fail("Instance %s is not running", iname)
805

    
806
  for idx in range(len(instance.disks)):
807
    link_name = _GetBlockDevSymlinkPath(iname, idx)
808
    if not os.path.islink(link_name):
809
      logging.warning("Instance %s is missing symlink %s for disk %d",
810
                      iname, link_name, idx)
811

    
812

    
813
def GetAllInstancesInfo(hypervisor_list):
814
  """Gather data about all instances.
815

816
  This is the equivalent of L{GetInstanceInfo}, except that it
817
  computes data for all instances at once, thus being faster if one
818
  needs data about more than one instance.
819

820
  @type hypervisor_list: list
821
  @param hypervisor_list: list of hypervisors to query for instance data
822

823
  @rtype: dict
824
  @return: dictionary of instance: data, with data having the following keys:
825
      - memory: memory size of instance (int)
826
      - state: xen state of instance (string)
827
      - time: cpu time of instance (float)
828
      - vcpus: the number of vcpus
829

830
  """
831
  output = {}
832

    
833
  for hname in hypervisor_list:
834
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
835
    if iinfo:
836
      for name, _, memory, vcpus, state, times in iinfo:
837
        value = {
838
          'memory': memory,
839
          'vcpus': vcpus,
840
          'state': state,
841
          'time': times,
842
          }
843
        if name in output:
844
          # we only check static parameters, like memory and vcpus,
845
          # and not state and time which can change between the
846
          # invocations of the different hypervisors
847
          for key in 'memory', 'vcpus':
848
            if value[key] != output[name][key]:
849
              _Fail("Instance %s is running twice"
850
                    " with different parameters", name)
851
        output[name] = value
852

    
853
  return output
854

    
855

    
856
def _InstanceLogName(kind, os_name, instance):
857
  """Compute the OS log filename for a given instance and operation.
858

859
  The instance name and os name are passed in as strings since not all
860
  operations have these as part of an instance object.
861

862
  @type kind: string
863
  @param kind: the operation type (e.g. add, import, etc.)
864
  @type os_name: string
865
  @param os_name: the os name
866
  @type instance: string
867
  @param instance: the name of the instance being imported/added/etc.
868

869
  """
870
  # TODO: Use tempfile.mkstemp to create unique filename
871
  base = ("%s-%s-%s-%s.log" %
872
          (kind, os_name, instance, utils.TimestampForFilename()))
873
  return utils.PathJoin(constants.LOG_OS_DIR, base)
874

    
875

    
876
def InstanceOsAdd(instance, reinstall, debug):
877
  """Add an OS to an instance.
878

879
  @type instance: L{objects.Instance}
880
  @param instance: Instance whose OS is to be installed
881
  @type reinstall: boolean
882
  @param reinstall: whether this is an instance reinstall
883
  @type debug: integer
884
  @param debug: debug level, passed to the OS scripts
885
  @rtype: None
886

887
  """
888
  inst_os = OSFromDisk(instance.os)
889

    
890
  create_env = OSEnvironment(instance, inst_os, debug)
891
  if reinstall:
892
    create_env['INSTANCE_REINSTALL'] = "1"
893

    
894
  logfile = _InstanceLogName("add", instance.os, instance.name)
895

    
896
  result = utils.RunCmd([inst_os.create_script], env=create_env,
897
                        cwd=inst_os.path, output=logfile,)
898
  if result.failed:
899
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
900
                  " output: %s", result.cmd, result.fail_reason, logfile,
901
                  result.output)
902
    lines = [utils.SafeEncode(val)
903
             for val in utils.TailFile(logfile, lines=20)]
904
    _Fail("OS create script failed (%s), last lines in the"
905
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
906

    
907

    
908
def RunRenameInstance(instance, old_name, debug):
909
  """Run the OS rename script for an instance.
910

911
  @type instance: L{objects.Instance}
912
  @param instance: Instance whose OS is to be installed
913
  @type old_name: string
914
  @param old_name: previous instance name
915
  @type debug: integer
916
  @param debug: debug level, passed to the OS scripts
917
  @rtype: boolean
918
  @return: the success of the operation
919

920
  """
921
  inst_os = OSFromDisk(instance.os)
922

    
923
  rename_env = OSEnvironment(instance, inst_os, debug)
924
  rename_env['OLD_INSTANCE_NAME'] = old_name
925

    
926
  logfile = _InstanceLogName("rename", instance.os,
927
                             "%s-%s" % (old_name, instance.name))
928

    
929
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
930
                        cwd=inst_os.path, output=logfile)
931

    
932
  if result.failed:
933
    logging.error("os create command '%s' returned error: %s output: %s",
934
                  result.cmd, result.fail_reason, result.output)
935
    lines = [utils.SafeEncode(val)
936
             for val in utils.TailFile(logfile, lines=20)]
937
    _Fail("OS rename script failed (%s), last lines in the"
938
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
939

    
940

    
941
def _GetBlockDevSymlinkPath(instance_name, idx):
942
  return utils.PathJoin(constants.DISK_LINKS_DIR,
943
                        "%s:%d" % (instance_name, idx))
944

    
945

    
946
def _SymlinkBlockDev(instance_name, device_path, idx):
947
  """Set up symlinks to a instance's block device.
948

949
  This is an auxiliary function run when an instance is start (on the primary
950
  node) or when an instance is migrated (on the target node).
951

952

953
  @param instance_name: the name of the target instance
954
  @param device_path: path of the physical block device, on the node
955
  @param idx: the disk index
956
  @return: absolute path to the disk's symlink
957

958
  """
959
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
960
  try:
961
    os.symlink(device_path, link_name)
962
  except OSError, err:
963
    if err.errno == errno.EEXIST:
964
      if (not os.path.islink(link_name) or
965
          os.readlink(link_name) != device_path):
966
        os.remove(link_name)
967
        os.symlink(device_path, link_name)
968
    else:
969
      raise
970

    
971
  return link_name
972

    
973

    
974
def _RemoveBlockDevLinks(instance_name, disks):
975
  """Remove the block device symlinks belonging to the given instance.
976

977
  """
978
  for idx, _ in enumerate(disks):
979
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
980
    if os.path.islink(link_name):
981
      try:
982
        os.remove(link_name)
983
      except OSError:
984
        logging.exception("Can't remove symlink '%s'", link_name)
985

    
986

    
987
def _GatherAndLinkBlockDevs(instance):
988
  """Set up an instance's block device(s).
989

990
  This is run on the primary node at instance startup. The block
991
  devices must be already assembled.
992

993
  @type instance: L{objects.Instance}
994
  @param instance: the instance whose disks we shoul assemble
995
  @rtype: list
996
  @return: list of (disk_object, device_path)
997

998
  """
999
  block_devices = []
1000
  for idx, disk in enumerate(instance.disks):
1001
    device = _RecursiveFindBD(disk)
1002
    if device is None:
1003
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1004
                                    str(disk))
1005
    device.Open()
1006
    try:
1007
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1008
    except OSError, e:
1009
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1010
                                    e.strerror)
1011

    
1012
    block_devices.append((disk, link_name))
1013

    
1014
  return block_devices
1015

    
1016

    
1017
def StartInstance(instance):
1018
  """Start an instance.
1019

1020
  @type instance: L{objects.Instance}
1021
  @param instance: the instance object
1022
  @rtype: None
1023

1024
  """
1025
  running_instances = GetInstanceList([instance.hypervisor])
1026

    
1027
  if instance.name in running_instances:
1028
    logging.info("Instance %s already running, not starting", instance.name)
1029
    return
1030

    
1031
  try:
1032
    block_devices = _GatherAndLinkBlockDevs(instance)
1033
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1034
    hyper.StartInstance(instance, block_devices)
1035
  except errors.BlockDeviceError, err:
1036
    _Fail("Block device error: %s", err, exc=True)
1037
  except errors.HypervisorError, err:
1038
    _RemoveBlockDevLinks(instance.name, instance.disks)
1039
    _Fail("Hypervisor error: %s", err, exc=True)
1040

    
1041

    
1042
def InstanceShutdown(instance, timeout):
1043
  """Shut an instance down.
1044

1045
  @note: this functions uses polling with a hardcoded timeout.
1046

1047
  @type instance: L{objects.Instance}
1048
  @param instance: the instance object
1049
  @type timeout: integer
1050
  @param timeout: maximum timeout for soft shutdown
1051
  @rtype: None
1052

1053
  """
1054
  hv_name = instance.hypervisor
1055
  hyper = hypervisor.GetHypervisor(hv_name)
1056
  iname = instance.name
1057

    
1058
  if instance.name not in hyper.ListInstances():
1059
    logging.info("Instance %s not running, doing nothing", iname)
1060
    return
1061

    
1062
  class _TryShutdown:
1063
    def __init__(self):
1064
      self.tried_once = False
1065

    
1066
    def __call__(self):
1067
      if iname not in hyper.ListInstances():
1068
        return
1069

    
1070
      try:
1071
        hyper.StopInstance(instance, retry=self.tried_once)
1072
      except errors.HypervisorError, err:
1073
        if iname not in hyper.ListInstances():
1074
          # if the instance is no longer existing, consider this a
1075
          # success and go to cleanup
1076
          return
1077

    
1078
        _Fail("Failed to stop instance %s: %s", iname, err)
1079

    
1080
      self.tried_once = True
1081

    
1082
      raise utils.RetryAgain()
1083

    
1084
  try:
1085
    utils.Retry(_TryShutdown(), 5, timeout)
1086
  except utils.RetryTimeout:
1087
    # the shutdown did not succeed
1088
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1089

    
1090
    try:
1091
      hyper.StopInstance(instance, force=True)
1092
    except errors.HypervisorError, err:
1093
      if iname in hyper.ListInstances():
1094
        # only raise an error if the instance still exists, otherwise
1095
        # the error could simply be "instance ... unknown"!
1096
        _Fail("Failed to force stop instance %s: %s", iname, err)
1097

    
1098
    time.sleep(1)
1099

    
1100
    if iname in hyper.ListInstances():
1101
      _Fail("Could not shutdown instance %s even by destroy", iname)
1102

    
1103
  try:
1104
    hyper.CleanupInstance(instance.name)
1105
  except errors.HypervisorError, err:
1106
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1107

    
1108
  _RemoveBlockDevLinks(iname, instance.disks)
1109

    
1110

    
1111
def InstanceReboot(instance, reboot_type, shutdown_timeout):
1112
  """Reboot an instance.
1113

1114
  @type instance: L{objects.Instance}
1115
  @param instance: the instance object to reboot
1116
  @type reboot_type: str
1117
  @param reboot_type: the type of reboot, one the following
1118
    constants:
1119
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1120
        instance OS, do not recreate the VM
1121
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1122
        restart the VM (at the hypervisor level)
1123
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1124
        not accepted here, since that mode is handled differently, in
1125
        cmdlib, and translates into full stop and start of the
1126
        instance (instead of a call_instance_reboot RPC)
1127
  @type shutdown_timeout: integer
1128
  @param shutdown_timeout: maximum timeout for soft shutdown
1129
  @rtype: None
1130

1131
  """
1132
  running_instances = GetInstanceList([instance.hypervisor])
1133

    
1134
  if instance.name not in running_instances:
1135
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1136

    
1137
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1138
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1139
    try:
1140
      hyper.RebootInstance(instance)
1141
    except errors.HypervisorError, err:
1142
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1143
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1144
    try:
1145
      InstanceShutdown(instance, shutdown_timeout)
1146
      return StartInstance(instance)
1147
    except errors.HypervisorError, err:
1148
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1149
  else:
1150
    _Fail("Invalid reboot_type received: %s", reboot_type)
1151

    
1152

    
1153
def MigrationInfo(instance):
1154
  """Gather information about an instance to be migrated.
1155

1156
  @type instance: L{objects.Instance}
1157
  @param instance: the instance definition
1158

1159
  """
1160
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1161
  try:
1162
    info = hyper.MigrationInfo(instance)
1163
  except errors.HypervisorError, err:
1164
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1165
  return info
1166

    
1167

    
1168
def AcceptInstance(instance, info, target):
1169
  """Prepare the node to accept an instance.
1170

1171
  @type instance: L{objects.Instance}
1172
  @param instance: the instance definition
1173
  @type info: string/data (opaque)
1174
  @param info: migration information, from the source node
1175
  @type target: string
1176
  @param target: target host (usually ip), on this node
1177

1178
  """
1179
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1180
  try:
1181
    hyper.AcceptInstance(instance, info, target)
1182
  except errors.HypervisorError, err:
1183
    _Fail("Failed to accept instance: %s", err, exc=True)
1184

    
1185

    
1186
def FinalizeMigration(instance, info, success):
1187
  """Finalize any preparation to accept an instance.
1188

1189
  @type instance: L{objects.Instance}
1190
  @param instance: the instance definition
1191
  @type info: string/data (opaque)
1192
  @param info: migration information, from the source node
1193
  @type success: boolean
1194
  @param success: whether the migration was a success or a failure
1195

1196
  """
1197
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1198
  try:
1199
    hyper.FinalizeMigration(instance, info, success)
1200
  except errors.HypervisorError, err:
1201
    _Fail("Failed to finalize migration: %s", err, exc=True)
1202

    
1203

    
1204
def MigrateInstance(instance, target, live):
1205
  """Migrates an instance to another node.
1206

1207
  @type instance: L{objects.Instance}
1208
  @param instance: the instance definition
1209
  @type target: string
1210
  @param target: the target node name
1211
  @type live: boolean
1212
  @param live: whether the migration should be done live or not (the
1213
      interpretation of this parameter is left to the hypervisor)
1214
  @rtype: tuple
1215
  @return: a tuple of (success, msg) where:
1216
      - succes is a boolean denoting the success/failure of the operation
1217
      - msg is a string with details in case of failure
1218

1219
  """
1220
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1221

    
1222
  try:
1223
    hyper.MigrateInstance(instance, target, live)
1224
  except errors.HypervisorError, err:
1225
    _Fail("Failed to migrate instance: %s", err, exc=True)
1226

    
1227

    
1228
def BlockdevCreate(disk, size, owner, on_primary, info):
1229
  """Creates a block device for an instance.
1230

1231
  @type disk: L{objects.Disk}
1232
  @param disk: the object describing the disk we should create
1233
  @type size: int
1234
  @param size: the size of the physical underlying device, in MiB
1235
  @type owner: str
1236
  @param owner: the name of the instance for which disk is created,
1237
      used for device cache data
1238
  @type on_primary: boolean
1239
  @param on_primary:  indicates if it is the primary node or not
1240
  @type info: string
1241
  @param info: string that will be sent to the physical device
1242
      creation, used for example to set (LVM) tags on LVs
1243

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

1248
  """
1249
  # TODO: remove the obsolete 'size' argument
1250
  # pylint: disable-msg=W0613
1251
  clist = []
1252
  if disk.children:
1253
    for child in disk.children:
1254
      try:
1255
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1256
      except errors.BlockDeviceError, err:
1257
        _Fail("Can't assemble device %s: %s", child, err)
1258
      if on_primary or disk.AssembleOnSecondary():
1259
        # we need the children open in case the device itself has to
1260
        # be assembled
1261
        try:
1262
          # pylint: disable-msg=E1103
1263
          crdev.Open()
1264
        except errors.BlockDeviceError, err:
1265
          _Fail("Can't make child '%s' read-write: %s", child, err)
1266
      clist.append(crdev)
1267

    
1268
  try:
1269
    device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
1270
  except errors.BlockDeviceError, err:
1271
    _Fail("Can't create block device: %s", err)
1272

    
1273
  if on_primary or disk.AssembleOnSecondary():
1274
    try:
1275
      device.Assemble()
1276
    except errors.BlockDeviceError, err:
1277
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1278
    device.SetSyncSpeed(constants.SYNC_SPEED)
1279
    if on_primary or disk.OpenOnSecondary():
1280
      try:
1281
        device.Open(force=True)
1282
      except errors.BlockDeviceError, err:
1283
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1284
    DevCacheManager.UpdateCache(device.dev_path, owner,
1285
                                on_primary, disk.iv_name)
1286

    
1287
  device.SetInfo(info)
1288

    
1289
  return device.unique_id
1290

    
1291

    
1292
def _WipeDevice(path, offset, size):
1293
  """This function actually wipes the device.
1294

1295
  @param path: The path to the device to wipe
1296
  @param offset: The offset in MiB in the file
1297
  @param size: The size in MiB to write
1298

1299
  """
1300
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1301
         "bs=%d" % constants.WIPE_BLOCK_SIZE, "oflag=direct", "of=%s" % path,
1302
         "count=%d" % size]
1303
  result = utils.RunCmd(cmd)
1304

    
1305
  if result.failed:
1306
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1307
          result.fail_reason, result.output)
1308

    
1309

    
1310
def BlockdevWipe(disk, offset, size):
1311
  """Wipes a block device.
1312

1313
  @type disk: L{objects.Disk}
1314
  @param disk: the disk object we want to wipe
1315
  @type offset: int
1316
  @param offset: The offset in MiB in the file
1317
  @type size: int
1318
  @param size: The size in MiB to write
1319

1320
  """
1321
  try:
1322
    rdev = _RecursiveFindBD(disk)
1323
  except errors.BlockDeviceError:
1324
    rdev = None
1325

    
1326
  if not rdev:
1327
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1328

    
1329
  # Do cross verify some of the parameters
1330
  if offset > rdev.size:
1331
    _Fail("Offset is bigger than device size")
1332
  if (offset + size) > rdev.size:
1333
    _Fail("The provided offset and size to wipe is bigger than device size")
1334

    
1335
  _WipeDevice(rdev.dev_path, offset, size)
1336

    
1337

    
1338
def BlockdevRemove(disk):
1339
  """Remove a block device.
1340

1341
  @note: This is intended to be called recursively.
1342

1343
  @type disk: L{objects.Disk}
1344
  @param disk: the disk object we should remove
1345
  @rtype: boolean
1346
  @return: the success of the operation
1347

1348
  """
1349
  msgs = []
1350
  try:
1351
    rdev = _RecursiveFindBD(disk)
1352
  except errors.BlockDeviceError, err:
1353
    # probably can't attach
1354
    logging.info("Can't attach to device %s in remove", disk)
1355
    rdev = None
1356
  if rdev is not None:
1357
    r_path = rdev.dev_path
1358
    try:
1359
      rdev.Remove()
1360
    except errors.BlockDeviceError, err:
1361
      msgs.append(str(err))
1362
    if not msgs:
1363
      DevCacheManager.RemoveCache(r_path)
1364

    
1365
  if disk.children:
1366
    for child in disk.children:
1367
      try:
1368
        BlockdevRemove(child)
1369
      except RPCFail, err:
1370
        msgs.append(str(err))
1371

    
1372
  if msgs:
1373
    _Fail("; ".join(msgs))
1374

    
1375

    
1376
def _RecursiveAssembleBD(disk, owner, as_primary):
1377
  """Activate a block device for an instance.
1378

1379
  This is run on the primary and secondary nodes for an instance.
1380

1381
  @note: this function is called recursively.
1382

1383
  @type disk: L{objects.Disk}
1384
  @param disk: the disk we try to assemble
1385
  @type owner: str
1386
  @param owner: the name of the instance which owns the disk
1387
  @type as_primary: boolean
1388
  @param as_primary: if we should make the block device
1389
      read/write
1390

1391
  @return: the assembled device or None (in case no device
1392
      was assembled)
1393
  @raise errors.BlockDeviceError: in case there is an error
1394
      during the activation of the children or the device
1395
      itself
1396

1397
  """
1398
  children = []
1399
  if disk.children:
1400
    mcn = disk.ChildrenNeeded()
1401
    if mcn == -1:
1402
      mcn = 0 # max number of Nones allowed
1403
    else:
1404
      mcn = len(disk.children) - mcn # max number of Nones
1405
    for chld_disk in disk.children:
1406
      try:
1407
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1408
      except errors.BlockDeviceError, err:
1409
        if children.count(None) >= mcn:
1410
          raise
1411
        cdev = None
1412
        logging.error("Error in child activation (but continuing): %s",
1413
                      str(err))
1414
      children.append(cdev)
1415

    
1416
  if as_primary or disk.AssembleOnSecondary():
1417
    r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
1418
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1419
    result = r_dev
1420
    if as_primary or disk.OpenOnSecondary():
1421
      r_dev.Open()
1422
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1423
                                as_primary, disk.iv_name)
1424

    
1425
  else:
1426
    result = True
1427
  return result
1428

    
1429

    
1430
def BlockdevAssemble(disk, owner, as_primary):
1431
  """Activate a block device for an instance.
1432

1433
  This is a wrapper over _RecursiveAssembleBD.
1434

1435
  @rtype: str or boolean
1436
  @return: a C{/dev/...} path for primary nodes, and
1437
      C{True} for secondary nodes
1438

1439
  """
1440
  try:
1441
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1442
    if isinstance(result, bdev.BlockDev):
1443
      # pylint: disable-msg=E1103
1444
      result = result.dev_path
1445
  except errors.BlockDeviceError, err:
1446
    _Fail("Error while assembling disk: %s", err, exc=True)
1447

    
1448
  return result
1449

    
1450

    
1451
def BlockdevShutdown(disk):
1452
  """Shut down a block device.
1453

1454
  First, if the device is assembled (Attach() is successful), then
1455
  the device is shutdown. Then the children of the device are
1456
  shutdown.
1457

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

1462
  @type disk: L{objects.Disk}
1463
  @param disk: the description of the disk we should
1464
      shutdown
1465
  @rtype: None
1466

1467
  """
1468
  msgs = []
1469
  r_dev = _RecursiveFindBD(disk)
1470
  if r_dev is not None:
1471
    r_path = r_dev.dev_path
1472
    try:
1473
      r_dev.Shutdown()
1474
      DevCacheManager.RemoveCache(r_path)
1475
    except errors.BlockDeviceError, err:
1476
      msgs.append(str(err))
1477

    
1478
  if disk.children:
1479
    for child in disk.children:
1480
      try:
1481
        BlockdevShutdown(child)
1482
      except RPCFail, err:
1483
        msgs.append(str(err))
1484

    
1485
  if msgs:
1486
    _Fail("; ".join(msgs))
1487

    
1488

    
1489
def BlockdevAddchildren(parent_cdev, new_cdevs):
1490
  """Extend a mirrored block device.
1491

1492
  @type parent_cdev: L{objects.Disk}
1493
  @param parent_cdev: the disk to which we should add children
1494
  @type new_cdevs: list of L{objects.Disk}
1495
  @param new_cdevs: the list of children which we should add
1496
  @rtype: None
1497

1498
  """
1499
  parent_bdev = _RecursiveFindBD(parent_cdev)
1500
  if parent_bdev is None:
1501
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1502
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1503
  if new_bdevs.count(None) > 0:
1504
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1505
  parent_bdev.AddChildren(new_bdevs)
1506

    
1507

    
1508
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1509
  """Shrink a mirrored block device.
1510

1511
  @type parent_cdev: L{objects.Disk}
1512
  @param parent_cdev: the disk from which we should remove children
1513
  @type new_cdevs: list of L{objects.Disk}
1514
  @param new_cdevs: the list of children which we should remove
1515
  @rtype: None
1516

1517
  """
1518
  parent_bdev = _RecursiveFindBD(parent_cdev)
1519
  if parent_bdev is None:
1520
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1521
  devs = []
1522
  for disk in new_cdevs:
1523
    rpath = disk.StaticDevPath()
1524
    if rpath is None:
1525
      bd = _RecursiveFindBD(disk)
1526
      if bd is None:
1527
        _Fail("Can't find device %s while removing children", disk)
1528
      else:
1529
        devs.append(bd.dev_path)
1530
    else:
1531
      if not utils.IsNormAbsPath(rpath):
1532
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
1533
      devs.append(rpath)
1534
  parent_bdev.RemoveChildren(devs)
1535

    
1536

    
1537
def BlockdevGetmirrorstatus(disks):
1538
  """Get the mirroring status of a list of devices.
1539

1540
  @type disks: list of L{objects.Disk}
1541
  @param disks: the list of disks which we should query
1542
  @rtype: disk
1543
  @return: List of L{objects.BlockDevStatus}, one for each disk
1544
  @raise errors.BlockDeviceError: if any of the disks cannot be
1545
      found
1546

1547
  """
1548
  stats = []
1549
  for dsk in disks:
1550
    rbd = _RecursiveFindBD(dsk)
1551
    if rbd is None:
1552
      _Fail("Can't find device %s", dsk)
1553

    
1554
    stats.append(rbd.CombinedSyncStatus())
1555

    
1556
  return stats
1557

    
1558

    
1559
def BlockdevGetmirrorstatusMulti(disks):
1560
  """Get the mirroring status of a list of devices.
1561

1562
  @type disks: list of L{objects.Disk}
1563
  @param disks: the list of disks which we should query
1564
  @rtype: disk
1565
  @return: List of tuples, (bool, status), one for each disk; bool denotes
1566
    success/failure, status is L{objects.BlockDevStatus} on success, string
1567
    otherwise
1568

1569
  """
1570
  result = []
1571
  for disk in disks:
1572
    try:
1573
      rbd = _RecursiveFindBD(disk)
1574
      if rbd is None:
1575
        result.append((False, "Can't find device %s" % disk))
1576
        continue
1577

    
1578
      status = rbd.CombinedSyncStatus()
1579
    except errors.BlockDeviceError, err:
1580
      logging.exception("Error while getting disk status")
1581
      result.append((False, str(err)))
1582
    else:
1583
      result.append((True, status))
1584

    
1585
  assert len(disks) == len(result)
1586

    
1587
  return result
1588

    
1589

    
1590
def _RecursiveFindBD(disk):
1591
  """Check if a device is activated.
1592

1593
  If so, return information about the real device.
1594

1595
  @type disk: L{objects.Disk}
1596
  @param disk: the disk object we need to find
1597

1598
  @return: None if the device can't be found,
1599
      otherwise the device instance
1600

1601
  """
1602
  children = []
1603
  if disk.children:
1604
    for chdisk in disk.children:
1605
      children.append(_RecursiveFindBD(chdisk))
1606

    
1607
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1608

    
1609

    
1610
def _OpenRealBD(disk):
1611
  """Opens the underlying block device of a disk.
1612

1613
  @type disk: L{objects.Disk}
1614
  @param disk: the disk object we want to open
1615

1616
  """
1617
  real_disk = _RecursiveFindBD(disk)
1618
  if real_disk is None:
1619
    _Fail("Block device '%s' is not set up", disk)
1620

    
1621
  real_disk.Open()
1622

    
1623
  return real_disk
1624

    
1625

    
1626
def BlockdevFind(disk):
1627
  """Check if a device is activated.
1628

1629
  If it is, return information about the real device.
1630

1631
  @type disk: L{objects.Disk}
1632
  @param disk: the disk to find
1633
  @rtype: None or objects.BlockDevStatus
1634
  @return: None if the disk cannot be found, otherwise a the current
1635
           information
1636

1637
  """
1638
  try:
1639
    rbd = _RecursiveFindBD(disk)
1640
  except errors.BlockDeviceError, err:
1641
    _Fail("Failed to find device: %s", err, exc=True)
1642

    
1643
  if rbd is None:
1644
    return None
1645

    
1646
  return rbd.GetSyncStatus()
1647

    
1648

    
1649
def BlockdevGetsize(disks):
1650
  """Computes the size of the given disks.
1651

1652
  If a disk is not found, returns None instead.
1653

1654
  @type disks: list of L{objects.Disk}
1655
  @param disks: the list of disk to compute the size for
1656
  @rtype: list
1657
  @return: list with elements None if the disk cannot be found,
1658
      otherwise the size
1659

1660
  """
1661
  result = []
1662
  for cf in disks:
1663
    try:
1664
      rbd = _RecursiveFindBD(cf)
1665
    except errors.BlockDeviceError:
1666
      result.append(None)
1667
      continue
1668
    if rbd is None:
1669
      result.append(None)
1670
    else:
1671
      result.append(rbd.GetActualSize())
1672
  return result
1673

    
1674

    
1675
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
1676
  """Export a block device to a remote node.
1677

1678
  @type disk: L{objects.Disk}
1679
  @param disk: the description of the disk to export
1680
  @type dest_node: str
1681
  @param dest_node: the destination node to export to
1682
  @type dest_path: str
1683
  @param dest_path: the destination path on the target node
1684
  @type cluster_name: str
1685
  @param cluster_name: the cluster name, needed for SSH hostalias
1686
  @rtype: None
1687

1688
  """
1689
  real_disk = _OpenRealBD(disk)
1690

    
1691
  # the block size on the read dd is 1MiB to match our units
1692
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
1693
                               "dd if=%s bs=1048576 count=%s",
1694
                               real_disk.dev_path, str(disk.size))
1695

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

    
1705
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1706
                                                   constants.GANETI_RUNAS,
1707
                                                   destcmd)
1708

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

    
1712
  result = utils.RunCmd(["bash", "-c", command])
1713

    
1714
  if result.failed:
1715
    _Fail("Disk copy command '%s' returned error: %s"
1716
          " output: %s", command, result.fail_reason, result.output)
1717

    
1718

    
1719
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1720
  """Write a file to the filesystem.
1721

1722
  This allows the master to overwrite(!) a file. It will only perform
1723
  the operation if the file belongs to a list of configuration files.
1724

1725
  @type file_name: str
1726
  @param file_name: the target file name
1727
  @type data: str
1728
  @param data: the new contents of the file
1729
  @type mode: int
1730
  @param mode: the mode to give the file (can be None)
1731
  @type uid: int
1732
  @param uid: the owner of the file (can be -1 for default)
1733
  @type gid: int
1734
  @param gid: the group of the file (can be -1 for default)
1735
  @type atime: float
1736
  @param atime: the atime to set on the file (can be None)
1737
  @type mtime: float
1738
  @param mtime: the mtime to set on the file (can be None)
1739
  @rtype: None
1740

1741
  """
1742
  if not os.path.isabs(file_name):
1743
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
1744

    
1745
  if file_name not in _ALLOWED_UPLOAD_FILES:
1746
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
1747
          file_name)
1748

    
1749
  raw_data = _Decompress(data)
1750

    
1751
  utils.SafeWriteFile(file_name, None,
1752
                      data=raw_data, mode=mode, uid=uid, gid=gid,
1753
                      atime=atime, mtime=mtime)
1754

    
1755

    
1756
def WriteSsconfFiles(values):
1757
  """Update all ssconf files.
1758

1759
  Wrapper around the SimpleStore.WriteFiles.
1760

1761
  """
1762
  ssconf.SimpleStore().WriteFiles(values)
1763

    
1764

    
1765
def _ErrnoOrStr(err):
1766
  """Format an EnvironmentError exception.
1767

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

1772
  @type err: L{EnvironmentError}
1773
  @param err: the exception to format
1774

1775
  """
1776
  if hasattr(err, 'errno'):
1777
    detail = errno.errorcode[err.errno]
1778
  else:
1779
    detail = str(err)
1780
  return detail
1781

    
1782

    
1783
def _OSOndiskAPIVersion(os_dir):
1784
  """Compute and return the API version of a given OS.
1785

1786
  This function will try to read the API version of the OS residing in
1787
  the 'os_dir' directory.
1788

1789
  @type os_dir: str
1790
  @param os_dir: the directory in which we should look for the OS
1791
  @rtype: tuple
1792
  @return: tuple (status, data) with status denoting the validity and
1793
      data holding either the vaid versions or an error message
1794

1795
  """
1796
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
1797

    
1798
  try:
1799
    st = os.stat(api_file)
1800
  except EnvironmentError, err:
1801
    return False, ("Required file '%s' not found under path %s: %s" %
1802
                   (constants.OS_API_FILE, os_dir, _ErrnoOrStr(err)))
1803

    
1804
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1805
    return False, ("File '%s' in %s is not a regular file" %
1806
                   (constants.OS_API_FILE, os_dir))
1807

    
1808
  try:
1809
    api_versions = utils.ReadFile(api_file).splitlines()
1810
  except EnvironmentError, err:
1811
    return False, ("Error while reading the API version file at %s: %s" %
1812
                   (api_file, _ErrnoOrStr(err)))
1813

    
1814
  try:
1815
    api_versions = [int(version.strip()) for version in api_versions]
1816
  except (TypeError, ValueError), err:
1817
    return False, ("API version(s) can't be converted to integer: %s" %
1818
                   str(err))
1819

    
1820
  return True, api_versions
1821

    
1822

    
1823
def DiagnoseOS(top_dirs=None):
1824
  """Compute the validity for all OSes.
1825

1826
  @type top_dirs: list
1827
  @param top_dirs: the list of directories in which to
1828
      search (if not given defaults to
1829
      L{constants.OS_SEARCH_PATH})
1830
  @rtype: list of L{objects.OS}
1831
  @return: a list of tuples (name, path, status, diagnose, variants,
1832
      parameters, api_version) for all (potential) OSes under all
1833
      search paths, where:
1834
          - name is the (potential) OS name
1835
          - path is the full path to the OS
1836
          - status True/False is the validity of the OS
1837
          - diagnose is the error message for an invalid OS, otherwise empty
1838
          - variants is a list of supported OS variants, if any
1839
          - parameters is a list of (name, help) parameters, if any
1840
          - api_version is a list of support OS API versions
1841

1842
  """
1843
  if top_dirs is None:
1844
    top_dirs = constants.OS_SEARCH_PATH
1845

    
1846
  result = []
1847
  for dir_name in top_dirs:
1848
    if os.path.isdir(dir_name):
1849
      try:
1850
        f_names = utils.ListVisibleFiles(dir_name)
1851
      except EnvironmentError, err:
1852
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
1853
        break
1854
      for name in f_names:
1855
        os_path = utils.PathJoin(dir_name, name)
1856
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
1857
        if status:
1858
          diagnose = ""
1859
          variants = os_inst.supported_variants
1860
          parameters = os_inst.supported_parameters
1861
          api_versions = os_inst.api_versions
1862
        else:
1863
          diagnose = os_inst
1864
          variants = parameters = api_versions = []
1865
        result.append((name, os_path, status, diagnose, variants,
1866
                       parameters, api_versions))
1867

    
1868
  return result
1869

    
1870

    
1871
def _TryOSFromDisk(name, base_dir=None):
1872
  """Create an OS instance from disk.
1873

1874
  This function will return an OS instance if the given name is a
1875
  valid OS name.
1876

1877
  @type base_dir: string
1878
  @keyword base_dir: Base directory containing OS installations.
1879
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1880
  @rtype: tuple
1881
  @return: success and either the OS instance if we find a valid one,
1882
      or error message
1883

1884
  """
1885
  if base_dir is None:
1886
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1887
  else:
1888
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
1889

    
1890
  if os_dir is None:
1891
    return False, "Directory for OS %s not found in search path" % name
1892

    
1893
  status, api_versions = _OSOndiskAPIVersion(os_dir)
1894
  if not status:
1895
    # push the error up
1896
    return status, api_versions
1897

    
1898
  if not constants.OS_API_VERSIONS.intersection(api_versions):
1899
    return False, ("API version mismatch for path '%s': found %s, want %s." %
1900
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
1901

    
1902
  # OS Files dictionary, we will populate it with the absolute path names
1903
  os_files = dict.fromkeys(constants.OS_SCRIPTS)
1904

    
1905
  if max(api_versions) >= constants.OS_API_V15:
1906
    os_files[constants.OS_VARIANTS_FILE] = ''
1907

    
1908
  if max(api_versions) >= constants.OS_API_V20:
1909
    os_files[constants.OS_PARAMETERS_FILE] = ''
1910
  else:
1911
    del os_files[constants.OS_SCRIPT_VERIFY]
1912

    
1913
  for filename in os_files:
1914
    os_files[filename] = utils.PathJoin(os_dir, filename)
1915

    
1916
    try:
1917
      st = os.stat(os_files[filename])
1918
    except EnvironmentError, err:
1919
      return False, ("File '%s' under path '%s' is missing (%s)" %
1920
                     (filename, os_dir, _ErrnoOrStr(err)))
1921

    
1922
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1923
      return False, ("File '%s' under path '%s' is not a regular file" %
1924
                     (filename, os_dir))
1925

    
1926
    if filename in constants.OS_SCRIPTS:
1927
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1928
        return False, ("File '%s' under path '%s' is not executable" %
1929
                       (filename, os_dir))
1930

    
1931
  variants = []
1932
  if constants.OS_VARIANTS_FILE in os_files:
1933
    variants_file = os_files[constants.OS_VARIANTS_FILE]
1934
    try:
1935
      variants = utils.ReadFile(variants_file).splitlines()
1936
    except EnvironmentError, err:
1937
      return False, ("Error while reading the OS variants file at %s: %s" %
1938
                     (variants_file, _ErrnoOrStr(err)))
1939
    if not variants:
1940
      return False, ("No supported os variant found")
1941

    
1942
  parameters = []
1943
  if constants.OS_PARAMETERS_FILE in os_files:
1944
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
1945
    try:
1946
      parameters = utils.ReadFile(parameters_file).splitlines()
1947
    except EnvironmentError, err:
1948
      return False, ("Error while reading the OS parameters file at %s: %s" %
1949
                     (parameters_file, _ErrnoOrStr(err)))
1950
    parameters = [v.split(None, 1) for v in parameters]
1951

    
1952
  os_obj = objects.OS(name=name, path=os_dir,
1953
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
1954
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
1955
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
1956
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
1957
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
1958
                                                 None),
1959
                      supported_variants=variants,
1960
                      supported_parameters=parameters,
1961
                      api_versions=api_versions)
1962
  return True, os_obj
1963

    
1964

    
1965
def OSFromDisk(name, base_dir=None):
1966
  """Create an OS instance from disk.
1967

1968
  This function will return an OS instance if the given name is a
1969
  valid OS name. Otherwise, it will raise an appropriate
1970
  L{RPCFail} exception, detailing why this is not a valid OS.
1971

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

1975
  @type base_dir: string
1976
  @keyword base_dir: Base directory containing OS installations.
1977
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1978
  @rtype: L{objects.OS}
1979
  @return: the OS instance if we find a valid one
1980
  @raise RPCFail: if we don't find a valid OS
1981

1982
  """
1983
  name_only = objects.OS.GetName(name)
1984
  status, payload = _TryOSFromDisk(name_only, base_dir)
1985

    
1986
  if not status:
1987
    _Fail(payload)
1988

    
1989
  return payload
1990

    
1991

    
1992
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
1993
  """Calculate the basic environment for an os script.
1994

1995
  @type os_name: str
1996
  @param os_name: full operating system name (including variant)
1997
  @type inst_os: L{objects.OS}
1998
  @param inst_os: operating system for which the environment is being built
1999
  @type os_params: dict
2000
  @param os_params: the OS parameters
2001
  @type debug: integer
2002
  @param debug: debug level (0 or 1, for OS Api 10)
2003
  @rtype: dict
2004
  @return: dict of environment variables
2005
  @raise errors.BlockDeviceError: if the block device
2006
      cannot be found
2007

2008
  """
2009
  result = {}
2010
  api_version = \
2011
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2012
  result['OS_API_VERSION'] = '%d' % api_version
2013
  result['OS_NAME'] = inst_os.name
2014
  result['DEBUG_LEVEL'] = '%d' % debug
2015

    
2016
  # OS variants
2017
  if api_version >= constants.OS_API_V15:
2018
    variant = objects.OS.GetVariant(os_name)
2019
    if not variant:
2020
      variant = inst_os.supported_variants[0]
2021
    result['OS_VARIANT'] = variant
2022

    
2023
  # OS params
2024
  for pname, pvalue in os_params.items():
2025
    result['OSP_%s' % pname.upper()] = pvalue
2026

    
2027
  return result
2028

    
2029

    
2030
def OSEnvironment(instance, inst_os, debug=0):
2031
  """Calculate the environment for an os script.
2032

2033
  @type instance: L{objects.Instance}
2034
  @param instance: target instance for the os script run
2035
  @type inst_os: L{objects.OS}
2036
  @param inst_os: operating system for which the environment is being built
2037
  @type debug: integer
2038
  @param debug: debug level (0 or 1, for OS Api 10)
2039
  @rtype: dict
2040
  @return: dict of environment variables
2041
  @raise errors.BlockDeviceError: if the block device
2042
      cannot be found
2043

2044
  """
2045
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2046

    
2047
  for attr in ["name", "os", "uuid", "ctime", "mtime"]:
2048
    result["INSTANCE_%s" % attr.upper()] = str(getattr(instance, attr))
2049

    
2050
  result['HYPERVISOR'] = instance.hypervisor
2051
  result['DISK_COUNT'] = '%d' % len(instance.disks)
2052
  result['NIC_COUNT'] = '%d' % len(instance.nics)
2053

    
2054
  # Disks
2055
  for idx, disk in enumerate(instance.disks):
2056
    real_disk = _OpenRealBD(disk)
2057
    result['DISK_%d_PATH' % idx] = real_disk.dev_path
2058
    result['DISK_%d_ACCESS' % idx] = disk.mode
2059
    if constants.HV_DISK_TYPE in instance.hvparams:
2060
      result['DISK_%d_FRONTEND_TYPE' % idx] = \
2061
        instance.hvparams[constants.HV_DISK_TYPE]
2062
    if disk.dev_type in constants.LDS_BLOCK:
2063
      result['DISK_%d_BACKEND_TYPE' % idx] = 'block'
2064
    elif disk.dev_type == constants.LD_FILE:
2065
      result['DISK_%d_BACKEND_TYPE' % idx] = \
2066
        'file:%s' % disk.physical_id[0]
2067

    
2068
  # NICs
2069
  for idx, nic in enumerate(instance.nics):
2070
    result['NIC_%d_MAC' % idx] = nic.mac
2071
    if nic.ip:
2072
      result['NIC_%d_IP' % idx] = nic.ip
2073
    result['NIC_%d_MODE' % idx] = nic.nicparams[constants.NIC_MODE]
2074
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2075
      result['NIC_%d_BRIDGE' % idx] = nic.nicparams[constants.NIC_LINK]
2076
    if nic.nicparams[constants.NIC_LINK]:
2077
      result['NIC_%d_LINK' % idx] = nic.nicparams[constants.NIC_LINK]
2078
    if constants.HV_NIC_TYPE in instance.hvparams:
2079
      result['NIC_%d_FRONTEND_TYPE' % idx] = \
2080
        instance.hvparams[constants.HV_NIC_TYPE]
2081

    
2082
  # HV/BE params
2083
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2084
    for key, value in source.items():
2085
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2086

    
2087
  return result
2088

    
2089

    
2090
def BlockdevGrow(disk, amount):
2091
  """Grow a stack of block devices.
2092

2093
  This function is called recursively, with the childrens being the
2094
  first ones to resize.
2095

2096
  @type disk: L{objects.Disk}
2097
  @param disk: the disk to be grown
2098
  @rtype: (status, result)
2099
  @return: a tuple with the status of the operation
2100
      (True/False), and the errors message if status
2101
      is False
2102

2103
  """
2104
  r_dev = _RecursiveFindBD(disk)
2105
  if r_dev is None:
2106
    _Fail("Cannot find block device %s", disk)
2107

    
2108
  try:
2109
    r_dev.Grow(amount)
2110
  except errors.BlockDeviceError, err:
2111
    _Fail("Failed to grow block device: %s", err, exc=True)
2112

    
2113

    
2114
def BlockdevSnapshot(disk):
2115
  """Create a snapshot copy of a block device.
2116

2117
  This function is called recursively, and the snapshot is actually created
2118
  just for the leaf lvm backend device.
2119

2120
  @type disk: L{objects.Disk}
2121
  @param disk: the disk to be snapshotted
2122
  @rtype: string
2123
  @return: snapshot disk path
2124

2125
  """
2126
  if disk.dev_type == constants.LD_DRBD8:
2127
    if not disk.children:
2128
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2129
            disk.unique_id)
2130
    return BlockdevSnapshot(disk.children[0])
2131
  elif disk.dev_type == constants.LD_LV:
2132
    r_dev = _RecursiveFindBD(disk)
2133
    if r_dev is not None:
2134
      # FIXME: choose a saner value for the snapshot size
2135
      # let's stay on the safe side and ask for the full size, for now
2136
      return r_dev.Snapshot(disk.size)
2137
    else:
2138
      _Fail("Cannot find block device %s", disk)
2139
  else:
2140
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2141
          disk.unique_id, disk.dev_type)
2142

    
2143

    
2144
def FinalizeExport(instance, snap_disks):
2145
  """Write out the export configuration information.
2146

2147
  @type instance: L{objects.Instance}
2148
  @param instance: the instance which we export, used for
2149
      saving configuration
2150
  @type snap_disks: list of L{objects.Disk}
2151
  @param snap_disks: list of snapshot block devices, which
2152
      will be used to get the actual name of the dump file
2153

2154
  @rtype: None
2155

2156
  """
2157
  destdir = utils.PathJoin(constants.EXPORT_DIR, instance.name + ".new")
2158
  finaldestdir = utils.PathJoin(constants.EXPORT_DIR, instance.name)
2159

    
2160
  config = objects.SerializableConfigParser()
2161

    
2162
  config.add_section(constants.INISECT_EXP)
2163
  config.set(constants.INISECT_EXP, 'version', '0')
2164
  config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
2165
  config.set(constants.INISECT_EXP, 'source', instance.primary_node)
2166
  config.set(constants.INISECT_EXP, 'os', instance.os)
2167
  config.set(constants.INISECT_EXP, 'compression', 'gzip')
2168

    
2169
  config.add_section(constants.INISECT_INS)
2170
  config.set(constants.INISECT_INS, 'name', instance.name)
2171
  config.set(constants.INISECT_INS, 'memory', '%d' %
2172
             instance.beparams[constants.BE_MEMORY])
2173
  config.set(constants.INISECT_INS, 'vcpus', '%d' %
2174
             instance.beparams[constants.BE_VCPUS])
2175
  config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
2176
  config.set(constants.INISECT_INS, 'hypervisor', instance.hypervisor)
2177

    
2178
  nic_total = 0
2179
  for nic_count, nic in enumerate(instance.nics):
2180
    nic_total += 1
2181
    config.set(constants.INISECT_INS, 'nic%d_mac' %
2182
               nic_count, '%s' % nic.mac)
2183
    config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
2184
    for param in constants.NICS_PARAMETER_TYPES:
2185
      config.set(constants.INISECT_INS, 'nic%d_%s' % (nic_count, param),
2186
                 '%s' % nic.nicparams.get(param, None))
2187
  # TODO: redundant: on load can read nics until it doesn't exist
2188
  config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_total)
2189

    
2190
  disk_total = 0
2191
  for disk_count, disk in enumerate(snap_disks):
2192
    if disk:
2193
      disk_total += 1
2194
      config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
2195
                 ('%s' % disk.iv_name))
2196
      config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
2197
                 ('%s' % disk.physical_id[1]))
2198
      config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
2199
                 ('%d' % disk.size))
2200

    
2201
  config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_total)
2202

    
2203
  # New-style hypervisor/backend parameters
2204

    
2205
  config.add_section(constants.INISECT_HYP)
2206
  for name, value in instance.hvparams.items():
2207
    if name not in constants.HVC_GLOBALS:
2208
      config.set(constants.INISECT_HYP, name, str(value))
2209

    
2210
  config.add_section(constants.INISECT_BEP)
2211
  for name, value in instance.beparams.items():
2212
    config.set(constants.INISECT_BEP, name, str(value))
2213

    
2214
  config.add_section(constants.INISECT_OSP)
2215
  for name, value in instance.osparams.items():
2216
    config.set(constants.INISECT_OSP, name, str(value))
2217

    
2218
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2219
                  data=config.Dumps())
2220
  shutil.rmtree(finaldestdir, ignore_errors=True)
2221
  shutil.move(destdir, finaldestdir)
2222

    
2223

    
2224
def ExportInfo(dest):
2225
  """Get export configuration information.
2226

2227
  @type dest: str
2228
  @param dest: directory containing the export
2229

2230
  @rtype: L{objects.SerializableConfigParser}
2231
  @return: a serializable config file containing the
2232
      export info
2233

2234
  """
2235
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2236

    
2237
  config = objects.SerializableConfigParser()
2238
  config.read(cff)
2239

    
2240
  if (not config.has_section(constants.INISECT_EXP) or
2241
      not config.has_section(constants.INISECT_INS)):
2242
    _Fail("Export info file doesn't have the required fields")
2243

    
2244
  return config.Dumps()
2245

    
2246

    
2247
def ListExports():
2248
  """Return a list of exports currently available on this machine.
2249

2250
  @rtype: list
2251
  @return: list of the exports
2252

2253
  """
2254
  if os.path.isdir(constants.EXPORT_DIR):
2255
    return sorted(utils.ListVisibleFiles(constants.EXPORT_DIR))
2256
  else:
2257
    _Fail("No exports directory")
2258

    
2259

    
2260
def RemoveExport(export):
2261
  """Remove an existing export from the node.
2262

2263
  @type export: str
2264
  @param export: the name of the export to remove
2265
  @rtype: None
2266

2267
  """
2268
  target = utils.PathJoin(constants.EXPORT_DIR, export)
2269

    
2270
  try:
2271
    shutil.rmtree(target)
2272
  except EnvironmentError, err:
2273
    _Fail("Error while removing the export: %s", err, exc=True)
2274

    
2275

    
2276
def BlockdevRename(devlist):
2277
  """Rename a list of block devices.
2278

2279
  @type devlist: list of tuples
2280
  @param devlist: list of tuples of the form  (disk,
2281
      new_logical_id, new_physical_id); disk is an
2282
      L{objects.Disk} object describing the current disk,
2283
      and new logical_id/physical_id is the name we
2284
      rename it to
2285
  @rtype: boolean
2286
  @return: True if all renames succeeded, False otherwise
2287

2288
  """
2289
  msgs = []
2290
  result = True
2291
  for disk, unique_id in devlist:
2292
    dev = _RecursiveFindBD(disk)
2293
    if dev is None:
2294
      msgs.append("Can't find device %s in rename" % str(disk))
2295
      result = False
2296
      continue
2297
    try:
2298
      old_rpath = dev.dev_path
2299
      dev.Rename(unique_id)
2300
      new_rpath = dev.dev_path
2301
      if old_rpath != new_rpath:
2302
        DevCacheManager.RemoveCache(old_rpath)
2303
        # FIXME: we should add the new cache information here, like:
2304
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2305
        # but we don't have the owner here - maybe parse from existing
2306
        # cache? for now, we only lose lvm data when we rename, which
2307
        # is less critical than DRBD or MD
2308
    except errors.BlockDeviceError, err:
2309
      msgs.append("Can't rename device '%s' to '%s': %s" %
2310
                  (dev, unique_id, err))
2311
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2312
      result = False
2313
  if not result:
2314
    _Fail("; ".join(msgs))
2315

    
2316

    
2317
def _TransformFileStorageDir(file_storage_dir):
2318
  """Checks whether given file_storage_dir is valid.
2319

2320
  Checks wheter the given file_storage_dir is within the cluster-wide
2321
  default file_storage_dir stored in SimpleStore. Only paths under that
2322
  directory are allowed.
2323

2324
  @type file_storage_dir: str
2325
  @param file_storage_dir: the path to check
2326

2327
  @return: the normalized path if valid, None otherwise
2328

2329
  """
2330
  if not constants.ENABLE_FILE_STORAGE:
2331
    _Fail("File storage disabled at configure time")
2332
  cfg = _GetConfig()
2333
  file_storage_dir = os.path.normpath(file_storage_dir)
2334
  base_file_storage_dir = cfg.GetFileStorageDir()
2335
  if (os.path.commonprefix([file_storage_dir, base_file_storage_dir]) !=
2336
      base_file_storage_dir):
2337
    _Fail("File storage directory '%s' is not under base file"
2338
          " storage directory '%s'", file_storage_dir, base_file_storage_dir)
2339
  return file_storage_dir
2340

    
2341

    
2342
def CreateFileStorageDir(file_storage_dir):
2343
  """Create file storage directory.
2344

2345
  @type file_storage_dir: str
2346
  @param file_storage_dir: directory to create
2347

2348
  @rtype: tuple
2349
  @return: tuple with first element a boolean indicating wheter dir
2350
      creation was successful or not
2351

2352
  """
2353
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2354
  if os.path.exists(file_storage_dir):
2355
    if not os.path.isdir(file_storage_dir):
2356
      _Fail("Specified storage dir '%s' is not a directory",
2357
            file_storage_dir)
2358
  else:
2359
    try:
2360
      os.makedirs(file_storage_dir, 0750)
2361
    except OSError, err:
2362
      _Fail("Cannot create file storage directory '%s': %s",
2363
            file_storage_dir, err, exc=True)
2364

    
2365

    
2366
def RemoveFileStorageDir(file_storage_dir):
2367
  """Remove file storage directory.
2368

2369
  Remove it only if it's empty. If not log an error and return.
2370

2371
  @type file_storage_dir: str
2372
  @param file_storage_dir: the directory we should cleanup
2373
  @rtype: tuple (success,)
2374
  @return: tuple of one element, C{success}, denoting
2375
      whether the operation was successful
2376

2377
  """
2378
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2379
  if os.path.exists(file_storage_dir):
2380
    if not os.path.isdir(file_storage_dir):
2381
      _Fail("Specified Storage directory '%s' is not a directory",
2382
            file_storage_dir)
2383
    # deletes dir only if empty, otherwise we want to fail the rpc call
2384
    try:
2385
      os.rmdir(file_storage_dir)
2386
    except OSError, err:
2387
      _Fail("Cannot remove file storage directory '%s': %s",
2388
            file_storage_dir, err)
2389

    
2390

    
2391
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2392
  """Rename the file storage directory.
2393

2394
  @type old_file_storage_dir: str
2395
  @param old_file_storage_dir: the current path
2396
  @type new_file_storage_dir: str
2397
  @param new_file_storage_dir: the name we should rename to
2398
  @rtype: tuple (success,)
2399
  @return: tuple of one element, C{success}, denoting
2400
      whether the operation was successful
2401

2402
  """
2403
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2404
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2405
  if not os.path.exists(new_file_storage_dir):
2406
    if os.path.isdir(old_file_storage_dir):
2407
      try:
2408
        os.rename(old_file_storage_dir, new_file_storage_dir)
2409
      except OSError, err:
2410
        _Fail("Cannot rename '%s' to '%s': %s",
2411
              old_file_storage_dir, new_file_storage_dir, err)
2412
    else:
2413
      _Fail("Specified storage dir '%s' is not a directory",
2414
            old_file_storage_dir)
2415
  else:
2416
    if os.path.exists(old_file_storage_dir):
2417
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2418
            old_file_storage_dir, new_file_storage_dir)
2419

    
2420

    
2421
def _EnsureJobQueueFile(file_name):
2422
  """Checks whether the given filename is in the queue directory.
2423

2424
  @type file_name: str
2425
  @param file_name: the file name we should check
2426
  @rtype: None
2427
  @raises RPCFail: if the file is not valid
2428

2429
  """
2430
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2431
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2432

    
2433
  if not result:
2434
    _Fail("Passed job queue file '%s' does not belong to"
2435
          " the queue directory '%s'", file_name, queue_dir)
2436

    
2437

    
2438
def JobQueueUpdate(file_name, content):
2439
  """Updates a file in the queue directory.
2440

2441
  This is just a wrapper over L{utils.WriteFile}, with proper
2442
  checking.
2443

2444
  @type file_name: str
2445
  @param file_name: the job file name
2446
  @type content: str
2447
  @param content: the new job contents
2448
  @rtype: boolean
2449
  @return: the success of the operation
2450

2451
  """
2452
  _EnsureJobQueueFile(file_name)
2453
  getents = runtime.GetEnts()
2454

    
2455
  # Write and replace the file atomically
2456
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
2457
                  gid=getents.masterd_gid)
2458

    
2459

    
2460
def JobQueueRename(old, new):
2461
  """Renames a job queue file.
2462

2463
  This is just a wrapper over os.rename with proper checking.
2464

2465
  @type old: str
2466
  @param old: the old (actual) file name
2467
  @type new: str
2468
  @param new: the desired file name
2469
  @rtype: tuple
2470
  @return: the success of the operation and payload
2471

2472
  """
2473
  _EnsureJobQueueFile(old)
2474
  _EnsureJobQueueFile(new)
2475

    
2476
  utils.RenameFile(old, new, mkdir=True)
2477

    
2478

    
2479
def BlockdevClose(instance_name, disks):
2480
  """Closes the given block devices.
2481

2482
  This means they will be switched to secondary mode (in case of
2483
  DRBD).
2484

2485
  @param instance_name: if the argument is not empty, the symlinks
2486
      of this instance will be removed
2487
  @type disks: list of L{objects.Disk}
2488
  @param disks: the list of disks to be closed
2489
  @rtype: tuple (success, message)
2490
  @return: a tuple of success and message, where success
2491
      indicates the succes of the operation, and message
2492
      which will contain the error details in case we
2493
      failed
2494

2495
  """
2496
  bdevs = []
2497
  for cf in disks:
2498
    rd = _RecursiveFindBD(cf)
2499
    if rd is None:
2500
      _Fail("Can't find device %s", cf)
2501
    bdevs.append(rd)
2502

    
2503
  msg = []
2504
  for rd in bdevs:
2505
    try:
2506
      rd.Close()
2507
    except errors.BlockDeviceError, err:
2508
      msg.append(str(err))
2509
  if msg:
2510
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2511
  else:
2512
    if instance_name:
2513
      _RemoveBlockDevLinks(instance_name, disks)
2514

    
2515

    
2516
def ValidateHVParams(hvname, hvparams):
2517
  """Validates the given hypervisor parameters.
2518

2519
  @type hvname: string
2520
  @param hvname: the hypervisor name
2521
  @type hvparams: dict
2522
  @param hvparams: the hypervisor parameters to be validated
2523
  @rtype: None
2524

2525
  """
2526
  try:
2527
    hv_type = hypervisor.GetHypervisor(hvname)
2528
    hv_type.ValidateParameters(hvparams)
2529
  except errors.HypervisorError, err:
2530
    _Fail(str(err), log=False)
2531

    
2532

    
2533
def _CheckOSPList(os_obj, parameters):
2534
  """Check whether a list of parameters is supported by the OS.
2535

2536
  @type os_obj: L{objects.OS}
2537
  @param os_obj: OS object to check
2538
  @type parameters: list
2539
  @param parameters: the list of parameters to check
2540

2541
  """
2542
  supported = [v[0] for v in os_obj.supported_parameters]
2543
  delta = frozenset(parameters).difference(supported)
2544
  if delta:
2545
    _Fail("The following parameters are not supported"
2546
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
2547

    
2548

    
2549
def ValidateOS(required, osname, checks, osparams):
2550
  """Validate the given OS' parameters.
2551

2552
  @type required: boolean
2553
  @param required: whether absence of the OS should translate into
2554
      failure or not
2555
  @type osname: string
2556
  @param osname: the OS to be validated
2557
  @type checks: list
2558
  @param checks: list of the checks to run (currently only 'parameters')
2559
  @type osparams: dict
2560
  @param osparams: dictionary with OS parameters
2561
  @rtype: boolean
2562
  @return: True if the validation passed, or False if the OS was not
2563
      found and L{required} was false
2564

2565
  """
2566
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
2567
    _Fail("Unknown checks required for OS %s: %s", osname,
2568
          set(checks).difference(constants.OS_VALIDATE_CALLS))
2569

    
2570
  name_only = objects.OS.GetName(osname)
2571
  status, tbv = _TryOSFromDisk(name_only, None)
2572

    
2573
  if not status:
2574
    if required:
2575
      _Fail(tbv)
2576
    else:
2577
      return False
2578

    
2579
  if max(tbv.api_versions) < constants.OS_API_V20:
2580
    return True
2581

    
2582
  if constants.OS_VALIDATE_PARAMETERS in checks:
2583
    _CheckOSPList(tbv, osparams.keys())
2584

    
2585
  validate_env = OSCoreEnv(osname, tbv, osparams)
2586
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
2587
                        cwd=tbv.path)
2588
  if result.failed:
2589
    logging.error("os validate command '%s' returned error: %s output: %s",
2590
                  result.cmd, result.fail_reason, result.output)
2591
    _Fail("OS validation script failed (%s), output: %s",
2592
          result.fail_reason, result.output, log=False)
2593

    
2594
  return True
2595

    
2596

    
2597
def DemoteFromMC():
2598
  """Demotes the current node from master candidate role.
2599

2600
  """
2601
  # try to ensure we're not the master by mistake
2602
  master, myself = ssconf.GetMasterAndMyself()
2603
  if master == myself:
2604
    _Fail("ssconf status shows I'm the master node, will not demote")
2605

    
2606
  result = utils.RunCmd([constants.DAEMON_UTIL, "check", constants.MASTERD])
2607
  if not result.failed:
2608
    _Fail("The master daemon is running, will not demote")
2609

    
2610
  try:
2611
    if os.path.isfile(constants.CLUSTER_CONF_FILE):
2612
      utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2613
  except EnvironmentError, err:
2614
    if err.errno != errno.ENOENT:
2615
      _Fail("Error while backing up cluster file: %s", err, exc=True)
2616

    
2617
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2618

    
2619

    
2620
def _GetX509Filenames(cryptodir, name):
2621
  """Returns the full paths for the private key and certificate.
2622

2623
  """
2624
  return (utils.PathJoin(cryptodir, name),
2625
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
2626
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
2627

    
2628

    
2629
def CreateX509Certificate(validity, cryptodir=constants.CRYPTO_KEYS_DIR):
2630
  """Creates a new X509 certificate for SSL/TLS.
2631

2632
  @type validity: int
2633
  @param validity: Validity in seconds
2634
  @rtype: tuple; (string, string)
2635
  @return: Certificate name and public part
2636

2637
  """
2638
  (key_pem, cert_pem) = \
2639
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
2640
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
2641

    
2642
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
2643
                              prefix="x509-%s-" % utils.TimestampForFilename())
2644
  try:
2645
    name = os.path.basename(cert_dir)
2646
    assert len(name) > 5
2647

    
2648
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2649

    
2650
    utils.WriteFile(key_file, mode=0400, data=key_pem)
2651
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
2652

    
2653
    # Never return private key as it shouldn't leave the node
2654
    return (name, cert_pem)
2655
  except Exception:
2656
    shutil.rmtree(cert_dir, ignore_errors=True)
2657
    raise
2658

    
2659

    
2660
def RemoveX509Certificate(name, cryptodir=constants.CRYPTO_KEYS_DIR):
2661
  """Removes a X509 certificate.
2662

2663
  @type name: string
2664
  @param name: Certificate name
2665

2666
  """
2667
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2668

    
2669
  utils.RemoveFile(key_file)
2670
  utils.RemoveFile(cert_file)
2671

    
2672
  try:
2673
    os.rmdir(cert_dir)
2674
  except EnvironmentError, err:
2675
    _Fail("Cannot remove certificate directory '%s': %s",
2676
          cert_dir, err)
2677

    
2678

    
2679
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
2680
  """Returns the command for the requested input/output.
2681

2682
  @type instance: L{objects.Instance}
2683
  @param instance: The instance object
2684
  @param mode: Import/export mode
2685
  @param ieio: Input/output type
2686
  @param ieargs: Input/output arguments
2687

2688
  """
2689
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
2690

    
2691
  env = None
2692
  prefix = None
2693
  suffix = None
2694
  exp_size = None
2695

    
2696
  if ieio == constants.IEIO_FILE:
2697
    (filename, ) = ieargs
2698

    
2699
    if not utils.IsNormAbsPath(filename):
2700
      _Fail("Path '%s' is not normalized or absolute", filename)
2701

    
2702
    directory = os.path.normpath(os.path.dirname(filename))
2703

    
2704
    if (os.path.commonprefix([constants.EXPORT_DIR, directory]) !=
2705
        constants.EXPORT_DIR):
2706
      _Fail("File '%s' is not under exports directory '%s'",
2707
            filename, constants.EXPORT_DIR)
2708

    
2709
    # Create directory
2710
    utils.Makedirs(directory, mode=0750)
2711

    
2712
    quoted_filename = utils.ShellQuote(filename)
2713

    
2714
    if mode == constants.IEM_IMPORT:
2715
      suffix = "> %s" % quoted_filename
2716
    elif mode == constants.IEM_EXPORT:
2717
      suffix = "< %s" % quoted_filename
2718

    
2719
      # Retrieve file size
2720
      try:
2721
        st = os.stat(filename)
2722
      except EnvironmentError, err:
2723
        logging.error("Can't stat(2) %s: %s", filename, err)
2724
      else:
2725
        exp_size = utils.BytesToMebibyte(st.st_size)
2726

    
2727
  elif ieio == constants.IEIO_RAW_DISK:
2728
    (disk, ) = ieargs
2729

    
2730
    real_disk = _OpenRealBD(disk)
2731

    
2732
    if mode == constants.IEM_IMPORT:
2733
      # we set here a smaller block size as, due to transport buffering, more
2734
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
2735
      # is not already there or we pass a wrong path; we use notrunc to no
2736
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
2737
      # much memory; this means that at best, we flush every 64k, which will
2738
      # not be very fast
2739
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
2740
                                    " bs=%s oflag=dsync"),
2741
                                    real_disk.dev_path,
2742
                                    str(64 * 1024))
2743

    
2744
    elif mode == constants.IEM_EXPORT:
2745
      # the block size on the read dd is 1MiB to match our units
2746
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
2747
                                   real_disk.dev_path,
2748
                                   str(1024 * 1024), # 1 MB
2749
                                   str(disk.size))
2750
      exp_size = disk.size
2751

    
2752
  elif ieio == constants.IEIO_SCRIPT:
2753
    (disk, disk_index, ) = ieargs
2754

    
2755
    assert isinstance(disk_index, (int, long))
2756

    
2757
    real_disk = _OpenRealBD(disk)
2758

    
2759
    inst_os = OSFromDisk(instance.os)
2760
    env = OSEnvironment(instance, inst_os)
2761

    
2762
    if mode == constants.IEM_IMPORT:
2763
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
2764
      env["IMPORT_INDEX"] = str(disk_index)
2765
      script = inst_os.import_script
2766

    
2767
    elif mode == constants.IEM_EXPORT:
2768
      env["EXPORT_DEVICE"] = real_disk.dev_path
2769
      env["EXPORT_INDEX"] = str(disk_index)
2770
      script = inst_os.export_script
2771

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

    
2775
    if mode == constants.IEM_IMPORT:
2776
      suffix = "| %s" % script_cmd
2777

    
2778
    elif mode == constants.IEM_EXPORT:
2779
      prefix = "%s |" % script_cmd
2780

    
2781
    # Let script predict size
2782
    exp_size = constants.IE_CUSTOM_SIZE
2783

    
2784
  else:
2785
    _Fail("Invalid %s I/O mode %r", mode, ieio)
2786

    
2787
  return (env, prefix, suffix, exp_size)
2788

    
2789

    
2790
def _CreateImportExportStatusDir(prefix):
2791
  """Creates status directory for import/export.
2792

2793
  """
2794
  return tempfile.mkdtemp(dir=constants.IMPORT_EXPORT_DIR,
2795
                          prefix=("%s-%s-" %
2796
                                  (prefix, utils.TimestampForFilename())))
2797

    
2798

    
2799
def StartImportExportDaemon(mode, opts, host, port, instance, ieio, ieioargs):
2800
  """Starts an import or export daemon.
2801

2802
  @param mode: Import/output mode
2803
  @type opts: L{objects.ImportExportOptions}
2804
  @param opts: Daemon options
2805
  @type host: string
2806
  @param host: Remote host for export (None for import)
2807
  @type port: int
2808
  @param port: Remote port for export (None for import)
2809
  @type instance: L{objects.Instance}
2810
  @param instance: Instance object
2811
  @param ieio: Input/output type
2812
  @param ieioargs: Input/output arguments
2813

2814
  """
2815
  if mode == constants.IEM_IMPORT:
2816
    prefix = "import"
2817

    
2818
    if not (host is None and port is None):
2819
      _Fail("Can not specify host or port on import")
2820

    
2821
  elif mode == constants.IEM_EXPORT:
2822
    prefix = "export"
2823

    
2824
    if host is None or port is None:
2825
      _Fail("Host and port must be specified for an export")
2826

    
2827
  else:
2828
    _Fail("Invalid mode %r", mode)
2829

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

    
2833
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
2834
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
2835

    
2836
  if opts.key_name is None:
2837
    # Use server.pem
2838
    key_path = constants.NODED_CERT_FILE
2839
    cert_path = constants.NODED_CERT_FILE
2840
    assert opts.ca_pem is None
2841
  else:
2842
    (_, key_path, cert_path) = _GetX509Filenames(constants.CRYPTO_KEYS_DIR,
2843
                                                 opts.key_name)
2844
    assert opts.ca_pem is not None
2845

    
2846
  for i in [key_path, cert_path]:
2847
    if not os.path.exists(i):
2848
      _Fail("File '%s' does not exist" % i)
2849

    
2850
  status_dir = _CreateImportExportStatusDir(prefix)
2851
  try:
2852
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
2853
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
2854
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
2855

    
2856
    if opts.ca_pem is None:
2857
      # Use server.pem
2858
      ca = utils.ReadFile(constants.NODED_CERT_FILE)
2859
    else:
2860
      ca = opts.ca_pem
2861

    
2862
    # Write CA file
2863
    utils.WriteFile(ca_file, data=ca, mode=0400)
2864

    
2865
    cmd = [
2866
      constants.IMPORT_EXPORT_DAEMON,
2867
      status_file, mode,
2868
      "--key=%s" % key_path,
2869
      "--cert=%s" % cert_path,
2870
      "--ca=%s" % ca_file,
2871
      ]
2872

    
2873
    if host:
2874
      cmd.append("--host=%s" % host)
2875

    
2876
    if port:
2877
      cmd.append("--port=%s" % port)
2878

    
2879
    if opts.compress:
2880
      cmd.append("--compress=%s" % opts.compress)
2881

    
2882
    if opts.magic:
2883
      cmd.append("--magic=%s" % opts.magic)
2884

    
2885
    if exp_size is not None:
2886
      cmd.append("--expected-size=%s" % exp_size)
2887

    
2888
    if cmd_prefix:
2889
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
2890

    
2891
    if cmd_suffix:
2892
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
2893

    
2894
    logfile = _InstanceLogName(prefix, instance.os, instance.name)
2895

    
2896
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
2897
    # support for receiving a file descriptor for output
2898
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
2899
                      output=logfile)
2900

    
2901
    # The import/export name is simply the status directory name
2902
    return os.path.basename(status_dir)
2903

    
2904
  except Exception:
2905
    shutil.rmtree(status_dir, ignore_errors=True)
2906
    raise
2907

    
2908

    
2909
def GetImportExportStatus(names):
2910
  """Returns import/export daemon status.
2911

2912
  @type names: sequence
2913
  @param names: List of names
2914
  @rtype: List of dicts
2915
  @return: Returns a list of the state of each named import/export or None if a
2916
           status couldn't be read
2917

2918
  """
2919
  result = []
2920

    
2921
  for name in names:
2922
    status_file = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name,
2923
                                 _IES_STATUS_FILE)
2924

    
2925
    try:
2926
      data = utils.ReadFile(status_file)
2927
    except EnvironmentError, err:
2928
      if err.errno != errno.ENOENT:
2929
        raise
2930
      data = None
2931

    
2932
    if not data:
2933
      result.append(None)
2934
      continue
2935

    
2936
    result.append(serializer.LoadJson(data))
2937

    
2938
  return result
2939

    
2940

    
2941
def AbortImportExport(name):
2942
  """Sends SIGTERM to a running import/export daemon.
2943

2944
  """
2945
  logging.info("Abort import/export %s", name)
2946

    
2947
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
2948
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
2949

    
2950
  if pid:
2951
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
2952
                 name, pid)
2953
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
2954

    
2955

    
2956
def CleanupImportExport(name):
2957
  """Cleanup after an import or export.
2958

2959
  If the import/export daemon is still running it's killed. Afterwards the
2960
  whole status directory is removed.
2961

2962
  """
2963
  logging.info("Finalizing import/export %s", name)
2964

    
2965
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
2966

    
2967
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
2968

    
2969
  if pid:
2970
    logging.info("Import/export %s is still running with PID %s",
2971
                 name, pid)
2972
    utils.KillProcess(pid, waitpid=False)
2973

    
2974
  shutil.rmtree(status_dir, ignore_errors=True)
2975

    
2976

    
2977
def _FindDisks(nodes_ip, disks):
2978
  """Sets the physical ID on disks and returns the block devices.
2979

2980
  """
2981
  # set the correct physical ID
2982
  my_name = netutils.Hostname.GetSysName()
2983
  for cf in disks:
2984
    cf.SetPhysicalID(my_name, nodes_ip)
2985

    
2986
  bdevs = []
2987

    
2988
  for cf in disks:
2989
    rd = _RecursiveFindBD(cf)
2990
    if rd is None:
2991
      _Fail("Can't find device %s", cf)
2992
    bdevs.append(rd)
2993
  return bdevs
2994

    
2995

    
2996
def DrbdDisconnectNet(nodes_ip, disks):
2997
  """Disconnects the network on a list of drbd devices.
2998

2999
  """
3000
  bdevs = _FindDisks(nodes_ip, disks)
3001

    
3002
  # disconnect disks
3003
  for rd in bdevs:
3004
    try:
3005
      rd.DisconnectNet()
3006
    except errors.BlockDeviceError, err:
3007
      _Fail("Can't change network configuration to standalone mode: %s",
3008
            err, exc=True)
3009

    
3010

    
3011
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3012
  """Attaches the network on a list of drbd devices.
3013

3014
  """
3015
  bdevs = _FindDisks(nodes_ip, disks)
3016

    
3017
  if multimaster:
3018
    for idx, rd in enumerate(bdevs):
3019
      try:
3020
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3021
      except EnvironmentError, err:
3022
        _Fail("Can't create symlink: %s", err)
3023
  # reconnect disks, switch to new master configuration and if
3024
  # needed primary mode
3025
  for rd in bdevs:
3026
    try:
3027
      rd.AttachNet(multimaster)
3028
    except errors.BlockDeviceError, err:
3029
      _Fail("Can't change network configuration: %s", err)
3030

    
3031
  # wait until the disks are connected; we need to retry the re-attach
3032
  # if the device becomes standalone, as this might happen if the one
3033
  # node disconnects and reconnects in a different mode before the
3034
  # other node reconnects; in this case, one or both of the nodes will
3035
  # decide it has wrong configuration and switch to standalone
3036

    
3037
  def _Attach():
3038
    all_connected = True
3039

    
3040
    for rd in bdevs:
3041
      stats = rd.GetProcStatus()
3042

    
3043
      all_connected = (all_connected and
3044
                       (stats.is_connected or stats.is_in_resync))
3045

    
3046
      if stats.is_standalone:
3047
        # peer had different config info and this node became
3048
        # standalone, even though this should not happen with the
3049
        # new staged way of changing disk configs
3050
        try:
3051
          rd.AttachNet(multimaster)
3052
        except errors.BlockDeviceError, err:
3053
          _Fail("Can't change network configuration: %s", err)
3054

    
3055
    if not all_connected:
3056
      raise utils.RetryAgain()
3057

    
3058
  try:
3059
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3060
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3061
  except utils.RetryTimeout:
3062
    _Fail("Timeout in disk reconnecting")
3063

    
3064
  if multimaster:
3065
    # change to primary mode
3066
    for rd in bdevs:
3067
      try:
3068
        rd.Open()
3069
      except errors.BlockDeviceError, err:
3070
        _Fail("Can't change to primary mode: %s", err)
3071

    
3072

    
3073
def DrbdWaitSync(nodes_ip, disks):
3074
  """Wait until DRBDs have synchronized.
3075

3076
  """
3077
  def _helper(rd):
3078
    stats = rd.GetProcStatus()
3079
    if not (stats.is_connected or stats.is_in_resync):
3080
      raise utils.RetryAgain()
3081
    return stats
3082

    
3083
  bdevs = _FindDisks(nodes_ip, disks)
3084

    
3085
  min_resync = 100
3086
  alldone = True
3087
  for rd in bdevs:
3088
    try:
3089
      # poll each second for 15 seconds
3090
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3091
    except utils.RetryTimeout:
3092
      stats = rd.GetProcStatus()
3093
      # last check
3094
      if not (stats.is_connected or stats.is_in_resync):
3095
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3096
    alldone = alldone and (not stats.is_in_resync)
3097
    if stats.sync_percent is not None:
3098
      min_resync = min(min_resync, stats.sync_percent)
3099

    
3100
  return (alldone, min_resync)
3101

    
3102

    
3103
def GetDrbdUsermodeHelper():
3104
  """Returns DRBD usermode helper currently configured.
3105

3106
  """
3107
  try:
3108
    return bdev.BaseDRBD.GetUsermodeHelper()
3109
  except errors.BlockDeviceError, err:
3110
    _Fail(str(err))
3111

    
3112

    
3113
def PowercycleNode(hypervisor_type):
3114
  """Hard-powercycle the node.
3115

3116
  Because we need to return first, and schedule the powercycle in the
3117
  background, we won't be able to report failures nicely.
3118

3119
  """
3120
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3121
  try:
3122
    pid = os.fork()
3123
  except OSError:
3124
    # if we can't fork, we'll pretend that we're in the child process
3125
    pid = 0
3126
  if pid > 0:
3127
    return "Reboot scheduled in 5 seconds"
3128
  # ensure the child is running on ram
3129
  try:
3130
    utils.Mlockall()
3131
  except Exception: # pylint: disable-msg=W0703
3132
    pass
3133
  time.sleep(5)
3134
  hyper.PowercycleNode()
3135

    
3136

    
3137
class HooksRunner(object):
3138
  """Hook runner.
3139

3140
  This class is instantiated on the node side (ganeti-noded) and not
3141
  on the master side.
3142

3143
  """
3144
  def __init__(self, hooks_base_dir=None):
3145
    """Constructor for hooks runner.
3146

3147
    @type hooks_base_dir: str or None
3148
    @param hooks_base_dir: if not None, this overrides the
3149
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
3150

3151
    """
3152
    if hooks_base_dir is None:
3153
      hooks_base_dir = constants.HOOKS_BASE_DIR
3154
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3155
    # constant
3156
    self._BASE_DIR = hooks_base_dir # pylint: disable-msg=C0103
3157

    
3158
  def RunHooks(self, hpath, phase, env):
3159
    """Run the scripts in the hooks directory.
3160

3161
    @type hpath: str
3162
    @param hpath: the path to the hooks directory which
3163
        holds the scripts
3164
    @type phase: str
3165
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
3166
        L{constants.HOOKS_PHASE_POST}
3167
    @type env: dict
3168
    @param env: dictionary with the environment for the hook
3169
    @rtype: list
3170
    @return: list of 3-element tuples:
3171
      - script path
3172
      - script result, either L{constants.HKR_SUCCESS} or
3173
        L{constants.HKR_FAIL}
3174
      - output of the script
3175

3176
    @raise errors.ProgrammerError: for invalid input
3177
        parameters
3178

3179
    """
3180
    if phase == constants.HOOKS_PHASE_PRE:
3181
      suffix = "pre"
3182
    elif phase == constants.HOOKS_PHASE_POST:
3183
      suffix = "post"
3184
    else:
3185
      _Fail("Unknown hooks phase '%s'", phase)
3186

    
3187

    
3188
    subdir = "%s-%s.d" % (hpath, suffix)
3189
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3190

    
3191
    results = []
3192

    
3193
    if not os.path.isdir(dir_name):
3194
      # for non-existing/non-dirs, we simply exit instead of logging a
3195
      # warning at every operation
3196
      return results
3197

    
3198
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3199

    
3200
    for (relname, relstatus, runresult)  in runparts_results:
3201
      if relstatus == constants.RUNPARTS_SKIP:
3202
        rrval = constants.HKR_SKIP
3203
        output = ""
3204
      elif relstatus == constants.RUNPARTS_ERR:
3205
        rrval = constants.HKR_FAIL
3206
        output = "Hook script execution error: %s" % runresult
3207
      elif relstatus == constants.RUNPARTS_RUN:
3208
        if runresult.failed:
3209
          rrval = constants.HKR_FAIL
3210
        else:
3211
          rrval = constants.HKR_SUCCESS
3212
        output = utils.SafeEncode(runresult.output.strip())
3213
      results.append(("%s/%s" % (subdir, relname), rrval, output))
3214

    
3215
    return results
3216

    
3217

    
3218
class IAllocatorRunner(object):
3219
  """IAllocator runner.
3220

3221
  This class is instantiated on the node side (ganeti-noded) and not on
3222
  the master side.
3223

3224
  """
3225
  @staticmethod
3226
  def Run(name, idata):
3227
    """Run an iallocator script.
3228

3229
    @type name: str
3230
    @param name: the iallocator script name
3231
    @type idata: str
3232
    @param idata: the allocator input data
3233

3234
    @rtype: tuple
3235
    @return: two element tuple of:
3236
       - status
3237
       - either error message or stdout of allocator (for success)
3238

3239
    """
3240
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
3241
                                  os.path.isfile)
3242
    if alloc_script is None:
3243
      _Fail("iallocator module '%s' not found in the search path", name)
3244

    
3245
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
3246
    try:
3247
      os.write(fd, idata)
3248
      os.close(fd)
3249
      result = utils.RunCmd([alloc_script, fin_name])
3250
      if result.failed:
3251
        _Fail("iallocator module '%s' failed: %s, output '%s'",
3252
              name, result.fail_reason, result.output)
3253
    finally:
3254
      os.unlink(fin_name)
3255

    
3256
    return result.stdout
3257

    
3258

    
3259
class DevCacheManager(object):
3260
  """Simple class for managing a cache of block device information.
3261

3262
  """
3263
  _DEV_PREFIX = "/dev/"
3264
  _ROOT_DIR = constants.BDEV_CACHE_DIR
3265

    
3266
  @classmethod
3267
  def _ConvertPath(cls, dev_path):
3268
    """Converts a /dev/name path to the cache file name.
3269

3270
    This replaces slashes with underscores and strips the /dev
3271
    prefix. It then returns the full path to the cache file.
3272

3273
    @type dev_path: str
3274
    @param dev_path: the C{/dev/} path name
3275
    @rtype: str
3276
    @return: the converted path name
3277

3278
    """
3279
    if dev_path.startswith(cls._DEV_PREFIX):
3280
      dev_path = dev_path[len(cls._DEV_PREFIX):]
3281
    dev_path = dev_path.replace("/", "_")
3282
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
3283
    return fpath
3284

    
3285
  @classmethod
3286
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
3287
    """Updates the cache information for a given device.
3288

3289
    @type dev_path: str
3290
    @param dev_path: the pathname of the device
3291
    @type owner: str
3292
    @param owner: the owner (instance name) of the device
3293
    @type on_primary: bool
3294
    @param on_primary: whether this is the primary
3295
        node nor not
3296
    @type iv_name: str
3297
    @param iv_name: the instance-visible name of the
3298
        device, as in objects.Disk.iv_name
3299

3300
    @rtype: None
3301

3302
    """
3303
    if dev_path is None:
3304
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
3305
      return
3306
    fpath = cls._ConvertPath(dev_path)
3307
    if on_primary:
3308
      state = "primary"
3309
    else:
3310
      state = "secondary"
3311
    if iv_name is None:
3312
      iv_name = "not_visible"
3313
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
3314
    try:
3315
      utils.WriteFile(fpath, data=fdata)
3316
    except EnvironmentError, err:
3317
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
3318

    
3319
  @classmethod
3320
  def RemoveCache(cls, dev_path):
3321
    """Remove data for a dev_path.
3322

3323
    This is just a wrapper over L{utils.RemoveFile} with a converted
3324
    path name and logging.
3325

3326
    @type dev_path: str
3327
    @param dev_path: the pathname of the device
3328

3329
    @rtype: None
3330

3331
    """
3332
    if dev_path is None:
3333
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
3334
      return
3335
    fpath = cls._ConvertPath(dev_path)
3336
    try:
3337
      utils.RemoveFile(fpath)
3338
    except EnvironmentError, err:
3339
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)