Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ d8e0caa6

History | View | Annotate | Download (97.9 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 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

    
63

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

    
78

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

82
  Its argument is the error message.
83

84
  """
85

    
86

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

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

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

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

    
109

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

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

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

    
119

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

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

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

    
132

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

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

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

    
152

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

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

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

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

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

    
182

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

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

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

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

    
204
  return frozenset(allowed_files)
205

    
206

    
207
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
208

    
209

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

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

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

    
220

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

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

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

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

    
242

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

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

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

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

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

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

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

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

    
304
      # we ignore the exit code of the following cmds
305
      if ipcls == netutils.IP4Address:
306
        utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev, "-s",
307
                      master_ip, master_ip])
308
      elif ipcls == netutils.IP6Address:
309
        utils.RunCmd(["ndisc6", "-q", "-r 3", master_ip, master_netdev])
310

    
311
  if err_msgs:
312
    _Fail("; ".join(err_msgs))
313

    
314

    
315
def StopMaster(stop_daemons):
316
  """Deactivate this node as master.
317

318
  The function will always try to deactivate the IP address of the
319
  master. It will also stop the master daemons depending on the
320
  stop_daemons parameter.
321

322
  @type stop_daemons: boolean
323
  @param stop_daemons: whether to also stop the master daemons
324
      (ganeti-masterd and ganeti-rapi)
325
  @rtype: None
326

327
  """
328
  # TODO: log and report back to the caller the error failures; we
329
  # need to decide in which case we fail the RPC for this
330

    
331
  # GetMasterInfo will raise an exception if not able to return data
332
  master_netdev, master_ip, _, family = GetMasterInfo()
333

    
334
  ipcls = netutils.IP4Address
335
  if family == netutils.IP6Address.family:
336
    ipcls = netutils.IP6Address
337

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

    
345
  if stop_daemons:
346
    result = utils.RunCmd([constants.DAEMON_UTIL, "stop-master"])
347
    if result.failed:
348
      logging.error("Could not stop Ganeti master, command %s had exitcode %s"
349
                    " and error %s",
350
                    result.cmd, result.exit_code, result.output)
351

    
352

    
353
def LeaveCluster(modify_ssh_setup):
354
  """Cleans up and remove the current node.
355

356
  This function cleans up and prepares the current node to be removed
357
  from the cluster.
358

359
  If processing is successful, then it raises an
360
  L{errors.QuitGanetiException} which is used as a special case to
361
  shutdown the node daemon.
362

363
  @param modify_ssh_setup: boolean
364

365
  """
366
  _CleanDirectory(constants.DATA_DIR)
367
  _CleanDirectory(constants.CRYPTO_KEYS_DIR)
368
  JobQueuePurge()
369

    
370
  if modify_ssh_setup:
371
    try:
372
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
373

    
374
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
375

    
376
      utils.RemoveFile(priv_key)
377
      utils.RemoveFile(pub_key)
378
    except errors.OpExecError:
379
      logging.exception("Error while processing ssh files")
380

    
381
  try:
382
    utils.RemoveFile(constants.CONFD_HMAC_KEY)
383
    utils.RemoveFile(constants.RAPI_CERT_FILE)
384
    utils.RemoveFile(constants.NODED_CERT_FILE)
385
  except: # pylint: disable-msg=W0702
386
    logging.exception("Error while removing cluster secrets")
387

    
388
  result = utils.RunCmd([constants.DAEMON_UTIL, "stop", constants.CONFD])
389
  if result.failed:
390
    logging.error("Command %s failed with exitcode %s and error %s",
391
                  result.cmd, result.exit_code, result.output)
392

    
393
  # Raise a custom exception (handled in ganeti-noded)
394
  raise errors.QuitGanetiException(True, 'Shutdown scheduled')
395

    
396

    
397
def GetNodeInfo(vgname, hypervisor_type):
398
  """Gives back a hash with different information about the node.
399

400
  @type vgname: C{string}
401
  @param vgname: the name of the volume group to ask for disk space information
402
  @type hypervisor_type: C{str}
403
  @param hypervisor_type: the name of the hypervisor to ask for
404
      memory information
405
  @rtype: C{dict}
406
  @return: dictionary with the following keys:
407
      - vg_size is the size of the configured volume group in MiB
408
      - vg_free is the free size of the volume group in MiB
409
      - memory_dom0 is the memory allocated for domain0 in MiB
410
      - memory_free is the currently available (free) ram in MiB
411
      - memory_total is the total number of ram in MiB
412

413
  """
414
  outputarray = {}
415
  vginfo = _GetVGInfo(vgname)
416
  outputarray['vg_size'] = vginfo['vg_size']
417
  outputarray['vg_free'] = vginfo['vg_free']
418

    
419
  hyper = hypervisor.GetHypervisor(hypervisor_type)
420
  hyp_info = hyper.GetNodeInfo()
421
  if hyp_info is not None:
422
    outputarray.update(hyp_info)
423

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

    
426
  return outputarray
427

    
428

    
429
def VerifyNode(what, cluster_name):
430
  """Verify the status of the local node.
431

432
  Based on the input L{what} parameter, various checks are done on the
433
  local node.
434

435
  If the I{filelist} key is present, this list of
436
  files is checksummed and the file/checksum pairs are returned.
437

438
  If the I{nodelist} key is present, we check that we have
439
  connectivity via ssh with the target nodes (and check the hostname
440
  report).
441

442
  If the I{node-net-test} key is present, we check that we have
443
  connectivity to the given nodes via both primary IP and, if
444
  applicable, secondary IPs.
445

446
  @type what: C{dict}
447
  @param what: a dictionary of things to check:
448
      - filelist: list of files for which to compute checksums
449
      - nodelist: list of nodes we should check ssh communication with
450
      - node-net-test: list of nodes we should check node daemon port
451
        connectivity with
452
      - hypervisor: list with hypervisors to run the verify for
453
  @rtype: dict
454
  @return: a dictionary with the same keys as the input dict, and
455
      values representing the result of the checks
456

457
  """
458
  result = {}
459
  my_name = netutils.Hostname.GetSysName()
460
  port = netutils.GetDaemonPort(constants.NODED)
461

    
462
  if constants.NV_HYPERVISOR in what:
463
    result[constants.NV_HYPERVISOR] = tmp = {}
464
    for hv_name in what[constants.NV_HYPERVISOR]:
465
      try:
466
        val = hypervisor.GetHypervisor(hv_name).Verify()
467
      except errors.HypervisorError, err:
468
        val = "Error while checking hypervisor: %s" % str(err)
469
      tmp[hv_name] = val
470

    
471
  if constants.NV_FILELIST in what:
472
    result[constants.NV_FILELIST] = utils.FingerprintFiles(
473
      what[constants.NV_FILELIST])
474

    
475
  if constants.NV_NODELIST in what:
476
    result[constants.NV_NODELIST] = tmp = {}
477
    random.shuffle(what[constants.NV_NODELIST])
478
    for node in what[constants.NV_NODELIST]:
479
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
480
      if not success:
481
        tmp[node] = message
482

    
483
  if constants.NV_NODENETTEST in what:
484
    result[constants.NV_NODENETTEST] = tmp = {}
485
    my_pip = my_sip = None
486
    for name, pip, sip in what[constants.NV_NODENETTEST]:
487
      if name == my_name:
488
        my_pip = pip
489
        my_sip = sip
490
        break
491
    if not my_pip:
492
      tmp[my_name] = ("Can't find my own primary/secondary IP"
493
                      " in the node list")
494
    else:
495
      for name, pip, sip in what[constants.NV_NODENETTEST]:
496
        fail = []
497
        if not netutils.TcpPing(pip, port, source=my_pip):
498
          fail.append("primary")
499
        if sip != pip:
500
          if not netutils.TcpPing(sip, port, source=my_sip):
501
            fail.append("secondary")
502
        if fail:
503
          tmp[name] = ("failure using the %s interface(s)" %
504
                       " and ".join(fail))
505

    
506
  if constants.NV_MASTERIP in what:
507
    # FIXME: add checks on incoming data structures (here and in the
508
    # rest of the function)
509
    master_name, master_ip = what[constants.NV_MASTERIP]
510
    if master_name == my_name:
511
      source = constants.IP4_ADDRESS_LOCALHOST
512
    else:
513
      source = None
514
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
515
                                                  source=source)
516

    
517
  if constants.NV_LVLIST in what:
518
    try:
519
      val = GetVolumeList(what[constants.NV_LVLIST])
520
    except RPCFail, err:
521
      val = str(err)
522
    result[constants.NV_LVLIST] = val
523

    
524
  if constants.NV_INSTANCELIST in what:
525
    # GetInstanceList can fail
526
    try:
527
      val = GetInstanceList(what[constants.NV_INSTANCELIST])
528
    except RPCFail, err:
529
      val = str(err)
530
    result[constants.NV_INSTANCELIST] = val
531

    
532
  if constants.NV_VGLIST in what:
533
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
534

    
535
  if constants.NV_PVLIST in what:
536
    result[constants.NV_PVLIST] = \
537
      bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
538
                                   filter_allocatable=False)
539

    
540
  if constants.NV_VERSION in what:
541
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
542
                                    constants.RELEASE_VERSION)
543

    
544
  if constants.NV_HVINFO in what:
545
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
546
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
547

    
548
  if constants.NV_DRBDLIST in what:
549
    try:
550
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
551
    except errors.BlockDeviceError, err:
552
      logging.warning("Can't get used minors list", exc_info=True)
553
      used_minors = str(err)
554
    result[constants.NV_DRBDLIST] = used_minors
555

    
556
  if constants.NV_DRBDHELPER in what:
557
    status = True
558
    try:
559
      payload = bdev.BaseDRBD.GetUsermodeHelper()
560
    except errors.BlockDeviceError, err:
561
      logging.error("Can't get DRBD usermode helper: %s", str(err))
562
      status = False
563
      payload = str(err)
564
    result[constants.NV_DRBDHELPER] = (status, payload)
565

    
566
  if constants.NV_NODESETUP in what:
567
    result[constants.NV_NODESETUP] = tmpr = []
568
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
569
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
570
                  " under /sys, missing required directories /sys/block"
571
                  " and /sys/class/net")
572
    if (not os.path.isdir("/proc/sys") or
573
        not os.path.isfile("/proc/sysrq-trigger")):
574
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
575
                  " under /proc, missing required directory /proc/sys and"
576
                  " the file /proc/sysrq-trigger")
577

    
578
  if constants.NV_TIME in what:
579
    result[constants.NV_TIME] = utils.SplitTime(time.time())
580

    
581
  if constants.NV_OSLIST in what:
582
    result[constants.NV_OSLIST] = DiagnoseOS()
583

    
584
  return result
585

    
586

    
587
def GetVolumeList(vg_name):
588
  """Compute list of logical volumes and their size.
589

590
  @type vg_name: str
591
  @param vg_name: the volume group whose LVs we should list
592
  @rtype: dict
593
  @return:
594
      dictionary of all partions (key) with value being a tuple of
595
      their size (in MiB), inactive and online status::
596

597
        {'test1': ('20.06', True, True)}
598

599
      in case of errors, a string is returned with the error
600
      details.
601

602
  """
603
  lvs = {}
604
  sep = '|'
605
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
606
                         "--separator=%s" % sep,
607
                         "-olv_name,lv_size,lv_attr", vg_name])
608
  if result.failed:
609
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
610

    
611
  valid_line_re = re.compile("^ *([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
612
  for line in result.stdout.splitlines():
613
    line = line.strip()
614
    match = valid_line_re.match(line)
615
    if not match:
616
      logging.error("Invalid line returned from lvs output: '%s'", line)
617
      continue
618
    name, size, attr = match.groups()
619
    inactive = attr[4] == '-'
620
    online = attr[5] == 'o'
621
    virtual = attr[0] == 'v'
622
    if virtual:
623
      # we don't want to report such volumes as existing, since they
624
      # don't really hold data
625
      continue
626
    lvs[name] = (size, inactive, online)
627

    
628
  return lvs
629

    
630

    
631
def ListVolumeGroups():
632
  """List the volume groups and their size.
633

634
  @rtype: dict
635
  @return: dictionary with keys volume name and values the
636
      size of the volume
637

638
  """
639
  return utils.ListVolumeGroups()
640

    
641

    
642
def NodeVolumes():
643
  """List all volumes on this node.
644

645
  @rtype: list
646
  @return:
647
    A list of dictionaries, each having four keys:
648
      - name: the logical volume name,
649
      - size: the size of the logical volume
650
      - dev: the physical device on which the LV lives
651
      - vg: the volume group to which it belongs
652

653
    In case of errors, we return an empty list and log the
654
    error.
655

656
    Note that since a logical volume can live on multiple physical
657
    volumes, the resulting list might include a logical volume
658
    multiple times.
659

660
  """
661
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
662
                         "--separator=|",
663
                         "--options=lv_name,lv_size,devices,vg_name"])
664
  if result.failed:
665
    _Fail("Failed to list logical volumes, lvs output: %s",
666
          result.output)
667

    
668
  def parse_dev(dev):
669
    return dev.split('(')[0]
670

    
671
  def handle_dev(dev):
672
    return [parse_dev(x) for x in dev.split(",")]
673

    
674
  def map_line(line):
675
    line = [v.strip() for v in line]
676
    return [{'name': line[0], 'size': line[1],
677
             'dev': dev, 'vg': line[3]} for dev in handle_dev(line[2])]
678

    
679
  all_devs = []
680
  for line in result.stdout.splitlines():
681
    if line.count('|') >= 3:
682
      all_devs.extend(map_line(line.split('|')))
683
    else:
684
      logging.warning("Strange line in the output from lvs: '%s'", line)
685
  return all_devs
686

    
687

    
688
def BridgesExist(bridges_list):
689
  """Check if a list of bridges exist on the current node.
690

691
  @rtype: boolean
692
  @return: C{True} if all of them exist, C{False} otherwise
693

694
  """
695
  missing = []
696
  for bridge in bridges_list:
697
    if not utils.BridgeExists(bridge):
698
      missing.append(bridge)
699

    
700
  if missing:
701
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
702

    
703

    
704
def GetInstanceList(hypervisor_list):
705
  """Provides a list of instances.
706

707
  @type hypervisor_list: list
708
  @param hypervisor_list: the list of hypervisors to query information
709

710
  @rtype: list
711
  @return: a list of all running instances on the current node
712
    - instance1.example.com
713
    - instance2.example.com
714

715
  """
716
  results = []
717
  for hname in hypervisor_list:
718
    try:
719
      names = hypervisor.GetHypervisor(hname).ListInstances()
720
      results.extend(names)
721
    except errors.HypervisorError, err:
722
      _Fail("Error enumerating instances (hypervisor %s): %s",
723
            hname, err, exc=True)
724

    
725
  return results
726

    
727

    
728
def GetInstanceInfo(instance, hname):
729
  """Gives back the information about an instance as a dictionary.
730

731
  @type instance: string
732
  @param instance: the instance name
733
  @type hname: string
734
  @param hname: the hypervisor type of the instance
735

736
  @rtype: dict
737
  @return: dictionary with the following keys:
738
      - memory: memory size of instance (int)
739
      - state: xen state of instance (string)
740
      - time: cpu time of instance (float)
741

742
  """
743
  output = {}
744

    
745
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
746
  if iinfo is not None:
747
    output['memory'] = iinfo[2]
748
    output['state'] = iinfo[4]
749
    output['time'] = iinfo[5]
750

    
751
  return output
752

    
753

    
754
def GetInstanceMigratable(instance):
755
  """Gives whether an instance can be migrated.
756

757
  @type instance: L{objects.Instance}
758
  @param instance: object representing the instance to be checked.
759

760
  @rtype: tuple
761
  @return: tuple of (result, description) where:
762
      - result: whether the instance can be migrated or not
763
      - description: a description of the issue, if relevant
764

765
  """
766
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
767
  iname = instance.name
768
  if iname not in hyper.ListInstances():
769
    _Fail("Instance %s is not running", iname)
770

    
771
  for idx in range(len(instance.disks)):
772
    link_name = _GetBlockDevSymlinkPath(iname, idx)
773
    if not os.path.islink(link_name):
774
      logging.warning("Instance %s is missing symlink %s for disk %d",
775
                      iname, link_name, idx)
776

    
777

    
778
def GetAllInstancesInfo(hypervisor_list):
779
  """Gather data about all instances.
780

781
  This is the equivalent of L{GetInstanceInfo}, except that it
782
  computes data for all instances at once, thus being faster if one
783
  needs data about more than one instance.
784

785
  @type hypervisor_list: list
786
  @param hypervisor_list: list of hypervisors to query for instance data
787

788
  @rtype: dict
789
  @return: dictionary of instance: data, with data having the following keys:
790
      - memory: memory size of instance (int)
791
      - state: xen state of instance (string)
792
      - time: cpu time of instance (float)
793
      - vcpus: the number of vcpus
794

795
  """
796
  output = {}
797

    
798
  for hname in hypervisor_list:
799
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
800
    if iinfo:
801
      for name, _, memory, vcpus, state, times in iinfo:
802
        value = {
803
          'memory': memory,
804
          'vcpus': vcpus,
805
          'state': state,
806
          'time': times,
807
          }
808
        if name in output:
809
          # we only check static parameters, like memory and vcpus,
810
          # and not state and time which can change between the
811
          # invocations of the different hypervisors
812
          for key in 'memory', 'vcpus':
813
            if value[key] != output[name][key]:
814
              _Fail("Instance %s is running twice"
815
                    " with different parameters", name)
816
        output[name] = value
817

    
818
  return output
819

    
820

    
821
def _InstanceLogName(kind, os_name, instance):
822
  """Compute the OS log filename for a given instance and operation.
823

824
  The instance name and os name are passed in as strings since not all
825
  operations have these as part of an instance object.
826

827
  @type kind: string
828
  @param kind: the operation type (e.g. add, import, etc.)
829
  @type os_name: string
830
  @param os_name: the os name
831
  @type instance: string
832
  @param instance: the name of the instance being imported/added/etc.
833

834
  """
835
  # TODO: Use tempfile.mkstemp to create unique filename
836
  base = ("%s-%s-%s-%s.log" %
837
          (kind, os_name, instance, utils.TimestampForFilename()))
838
  return utils.PathJoin(constants.LOG_OS_DIR, base)
839

    
840

    
841
def InstanceOsAdd(instance, reinstall, debug):
842
  """Add an OS to an instance.
843

844
  @type instance: L{objects.Instance}
845
  @param instance: Instance whose OS is to be installed
846
  @type reinstall: boolean
847
  @param reinstall: whether this is an instance reinstall
848
  @type debug: integer
849
  @param debug: debug level, passed to the OS scripts
850
  @rtype: None
851

852
  """
853
  inst_os = OSFromDisk(instance.os)
854

    
855
  create_env = OSEnvironment(instance, inst_os, debug)
856
  if reinstall:
857
    create_env['INSTANCE_REINSTALL'] = "1"
858

    
859
  logfile = _InstanceLogName("add", instance.os, instance.name)
860

    
861
  result = utils.RunCmd([inst_os.create_script], env=create_env,
862
                        cwd=inst_os.path, output=logfile,)
863
  if result.failed:
864
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
865
                  " output: %s", result.cmd, result.fail_reason, logfile,
866
                  result.output)
867
    lines = [utils.SafeEncode(val)
868
             for val in utils.TailFile(logfile, lines=20)]
869
    _Fail("OS create script failed (%s), last lines in the"
870
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
871

    
872

    
873
def RunRenameInstance(instance, old_name, debug):
874
  """Run the OS rename script for an instance.
875

876
  @type instance: L{objects.Instance}
877
  @param instance: Instance whose OS is to be installed
878
  @type old_name: string
879
  @param old_name: previous instance name
880
  @type debug: integer
881
  @param debug: debug level, passed to the OS scripts
882
  @rtype: boolean
883
  @return: the success of the operation
884

885
  """
886
  inst_os = OSFromDisk(instance.os)
887

    
888
  rename_env = OSEnvironment(instance, inst_os, debug)
889
  rename_env['OLD_INSTANCE_NAME'] = old_name
890

    
891
  logfile = _InstanceLogName("rename", instance.os,
892
                             "%s-%s" % (old_name, instance.name))
893

    
894
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
895
                        cwd=inst_os.path, output=logfile)
896

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

    
905

    
906
def _GetVGInfo(vg_name):
907
  """Get information about the volume group.
908

909
  @type vg_name: str
910
  @param vg_name: the volume group which we query
911
  @rtype: dict
912
  @return:
913
    A dictionary with the following keys:
914
      - C{vg_size} is the total size of the volume group in MiB
915
      - C{vg_free} is the free size of the volume group in MiB
916
      - C{pv_count} are the number of physical disks in that VG
917

918
    If an error occurs during gathering of data, we return the same dict
919
    with keys all set to None.
920

921
  """
922
  retdic = dict.fromkeys(["vg_size", "vg_free", "pv_count"])
923

    
924
  retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings",
925
                         "--nosuffix", "--units=m", "--separator=:", vg_name])
926

    
927
  if retval.failed:
928
    logging.error("volume group %s not present", vg_name)
929
    return retdic
930
  valarr = retval.stdout.strip().rstrip(':').split(':')
931
  if len(valarr) == 3:
932
    try:
933
      retdic = {
934
        "vg_size": int(round(float(valarr[0]), 0)),
935
        "vg_free": int(round(float(valarr[1]), 0)),
936
        "pv_count": int(valarr[2]),
937
        }
938
    except (TypeError, ValueError), err:
939
      logging.exception("Fail to parse vgs output: %s", err)
940
  else:
941
    logging.error("vgs output has the wrong number of fields (expected"
942
                  " three): %s", str(valarr))
943
  return retdic
944

    
945

    
946
def _GetBlockDevSymlinkPath(instance_name, idx):
947
  return utils.PathJoin(constants.DISK_LINKS_DIR,
948
                        "%s:%d" % (instance_name, idx))
949

    
950

    
951
def _SymlinkBlockDev(instance_name, device_path, idx):
952
  """Set up symlinks to a instance's block device.
953

954
  This is an auxiliary function run when an instance is start (on the primary
955
  node) or when an instance is migrated (on the target node).
956

957

958
  @param instance_name: the name of the target instance
959
  @param device_path: path of the physical block device, on the node
960
  @param idx: the disk index
961
  @return: absolute path to the disk's symlink
962

963
  """
964
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
965
  try:
966
    os.symlink(device_path, link_name)
967
  except OSError, err:
968
    if err.errno == errno.EEXIST:
969
      if (not os.path.islink(link_name) or
970
          os.readlink(link_name) != device_path):
971
        os.remove(link_name)
972
        os.symlink(device_path, link_name)
973
    else:
974
      raise
975

    
976
  return link_name
977

    
978

    
979
def _RemoveBlockDevLinks(instance_name, disks):
980
  """Remove the block device symlinks belonging to the given instance.
981

982
  """
983
  for idx, _ in enumerate(disks):
984
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
985
    if os.path.islink(link_name):
986
      try:
987
        os.remove(link_name)
988
      except OSError:
989
        logging.exception("Can't remove symlink '%s'", link_name)
990

    
991

    
992
def _GatherAndLinkBlockDevs(instance):
993
  """Set up an instance's block device(s).
994

995
  This is run on the primary node at instance startup. The block
996
  devices must be already assembled.
997

998
  @type instance: L{objects.Instance}
999
  @param instance: the instance whose disks we shoul assemble
1000
  @rtype: list
1001
  @return: list of (disk_object, device_path)
1002

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

    
1017
    block_devices.append((disk, link_name))
1018

    
1019
  return block_devices
1020

    
1021

    
1022
def StartInstance(instance):
1023
  """Start an instance.
1024

1025
  @type instance: L{objects.Instance}
1026
  @param instance: the instance object
1027
  @rtype: None
1028

1029
  """
1030
  running_instances = GetInstanceList([instance.hypervisor])
1031

    
1032
  if instance.name in running_instances:
1033
    logging.info("Instance %s already running, not starting", instance.name)
1034
    return
1035

    
1036
  try:
1037
    block_devices = _GatherAndLinkBlockDevs(instance)
1038
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1039
    hyper.StartInstance(instance, block_devices)
1040
  except errors.BlockDeviceError, err:
1041
    _Fail("Block device error: %s", err, exc=True)
1042
  except errors.HypervisorError, err:
1043
    _RemoveBlockDevLinks(instance.name, instance.disks)
1044
    _Fail("Hypervisor error: %s", err, exc=True)
1045

    
1046

    
1047
def InstanceShutdown(instance, timeout):
1048
  """Shut an instance down.
1049

1050
  @note: this functions uses polling with a hardcoded timeout.
1051

1052
  @type instance: L{objects.Instance}
1053
  @param instance: the instance object
1054
  @type timeout: integer
1055
  @param timeout: maximum timeout for soft shutdown
1056
  @rtype: None
1057

1058
  """
1059
  hv_name = instance.hypervisor
1060
  hyper = hypervisor.GetHypervisor(hv_name)
1061
  iname = instance.name
1062

    
1063
  if instance.name not in hyper.ListInstances():
1064
    logging.info("Instance %s not running, doing nothing", iname)
1065
    return
1066

    
1067
  class _TryShutdown:
1068
    def __init__(self):
1069
      self.tried_once = False
1070

    
1071
    def __call__(self):
1072
      if iname not in hyper.ListInstances():
1073
        return
1074

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

    
1083
        _Fail("Failed to stop instance %s: %s", iname, err)
1084

    
1085
      self.tried_once = True
1086

    
1087
      raise utils.RetryAgain()
1088

    
1089
  try:
1090
    utils.Retry(_TryShutdown(), 5, timeout)
1091
  except utils.RetryTimeout:
1092
    # the shutdown did not succeed
1093
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1094

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

    
1103
    time.sleep(1)
1104

    
1105
    if iname in hyper.ListInstances():
1106
      _Fail("Could not shutdown instance %s even by destroy", iname)
1107

    
1108
  try:
1109
    hyper.CleanupInstance(instance.name)
1110
  except errors.HypervisorError, err:
1111
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1112

    
1113
  _RemoveBlockDevLinks(iname, instance.disks)
1114

    
1115

    
1116
def InstanceReboot(instance, reboot_type, shutdown_timeout):
1117
  """Reboot an instance.
1118

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

1136
  """
1137
  running_instances = GetInstanceList([instance.hypervisor])
1138

    
1139
  if instance.name not in running_instances:
1140
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1141

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

    
1157

    
1158
def MigrationInfo(instance):
1159
  """Gather information about an instance to be migrated.
1160

1161
  @type instance: L{objects.Instance}
1162
  @param instance: the instance definition
1163

1164
  """
1165
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1166
  try:
1167
    info = hyper.MigrationInfo(instance)
1168
  except errors.HypervisorError, err:
1169
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1170
  return info
1171

    
1172

    
1173
def AcceptInstance(instance, info, target):
1174
  """Prepare the node to accept an instance.
1175

1176
  @type instance: L{objects.Instance}
1177
  @param instance: the instance definition
1178
  @type info: string/data (opaque)
1179
  @param info: migration information, from the source node
1180
  @type target: string
1181
  @param target: target host (usually ip), on this node
1182

1183
  """
1184
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1185
  try:
1186
    hyper.AcceptInstance(instance, info, target)
1187
  except errors.HypervisorError, err:
1188
    _Fail("Failed to accept instance: %s", err, exc=True)
1189

    
1190

    
1191
def FinalizeMigration(instance, info, success):
1192
  """Finalize any preparation to accept an instance.
1193

1194
  @type instance: L{objects.Instance}
1195
  @param instance: the instance definition
1196
  @type info: string/data (opaque)
1197
  @param info: migration information, from the source node
1198
  @type success: boolean
1199
  @param success: whether the migration was a success or a failure
1200

1201
  """
1202
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1203
  try:
1204
    hyper.FinalizeMigration(instance, info, success)
1205
  except errors.HypervisorError, err:
1206
    _Fail("Failed to finalize migration: %s", err, exc=True)
1207

    
1208

    
1209
def MigrateInstance(instance, target, live):
1210
  """Migrates an instance to another node.
1211

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

1224
  """
1225
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1226

    
1227
  try:
1228
    hyper.MigrateInstance(instance, target, live)
1229
  except errors.HypervisorError, err:
1230
    _Fail("Failed to migrate instance: %s", err, exc=True)
1231

    
1232

    
1233
def BlockdevCreate(disk, size, owner, on_primary, info):
1234
  """Creates a block device for an instance.
1235

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

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

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

    
1273
  try:
1274
    device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
1275
  except errors.BlockDeviceError, err:
1276
    _Fail("Can't create block device: %s", err)
1277

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

    
1292
  device.SetInfo(info)
1293

    
1294
  return device.unique_id
1295

    
1296

    
1297
def BlockdevRemove(disk):
1298
  """Remove a block device.
1299

1300
  @note: This is intended to be called recursively.
1301

1302
  @type disk: L{objects.Disk}
1303
  @param disk: the disk object we should remove
1304
  @rtype: boolean
1305
  @return: the success of the operation
1306

1307
  """
1308
  msgs = []
1309
  try:
1310
    rdev = _RecursiveFindBD(disk)
1311
  except errors.BlockDeviceError, err:
1312
    # probably can't attach
1313
    logging.info("Can't attach to device %s in remove", disk)
1314
    rdev = None
1315
  if rdev is not None:
1316
    r_path = rdev.dev_path
1317
    try:
1318
      rdev.Remove()
1319
    except errors.BlockDeviceError, err:
1320
      msgs.append(str(err))
1321
    if not msgs:
1322
      DevCacheManager.RemoveCache(r_path)
1323

    
1324
  if disk.children:
1325
    for child in disk.children:
1326
      try:
1327
        BlockdevRemove(child)
1328
      except RPCFail, err:
1329
        msgs.append(str(err))
1330

    
1331
  if msgs:
1332
    _Fail("; ".join(msgs))
1333

    
1334

    
1335
def _RecursiveAssembleBD(disk, owner, as_primary):
1336
  """Activate a block device for an instance.
1337

1338
  This is run on the primary and secondary nodes for an instance.
1339

1340
  @note: this function is called recursively.
1341

1342
  @type disk: L{objects.Disk}
1343
  @param disk: the disk we try to assemble
1344
  @type owner: str
1345
  @param owner: the name of the instance which owns the disk
1346
  @type as_primary: boolean
1347
  @param as_primary: if we should make the block device
1348
      read/write
1349

1350
  @return: the assembled device or None (in case no device
1351
      was assembled)
1352
  @raise errors.BlockDeviceError: in case there is an error
1353
      during the activation of the children or the device
1354
      itself
1355

1356
  """
1357
  children = []
1358
  if disk.children:
1359
    mcn = disk.ChildrenNeeded()
1360
    if mcn == -1:
1361
      mcn = 0 # max number of Nones allowed
1362
    else:
1363
      mcn = len(disk.children) - mcn # max number of Nones
1364
    for chld_disk in disk.children:
1365
      try:
1366
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1367
      except errors.BlockDeviceError, err:
1368
        if children.count(None) >= mcn:
1369
          raise
1370
        cdev = None
1371
        logging.error("Error in child activation (but continuing): %s",
1372
                      str(err))
1373
      children.append(cdev)
1374

    
1375
  if as_primary or disk.AssembleOnSecondary():
1376
    r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
1377
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1378
    result = r_dev
1379
    if as_primary or disk.OpenOnSecondary():
1380
      r_dev.Open()
1381
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1382
                                as_primary, disk.iv_name)
1383

    
1384
  else:
1385
    result = True
1386
  return result
1387

    
1388

    
1389
def BlockdevAssemble(disk, owner, as_primary):
1390
  """Activate a block device for an instance.
1391

1392
  This is a wrapper over _RecursiveAssembleBD.
1393

1394
  @rtype: str or boolean
1395
  @return: a C{/dev/...} path for primary nodes, and
1396
      C{True} for secondary nodes
1397

1398
  """
1399
  try:
1400
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1401
    if isinstance(result, bdev.BlockDev):
1402
      # pylint: disable-msg=E1103
1403
      result = result.dev_path
1404
  except errors.BlockDeviceError, err:
1405
    _Fail("Error while assembling disk: %s", err, exc=True)
1406

    
1407
  return result
1408

    
1409

    
1410
def BlockdevShutdown(disk):
1411
  """Shut down a block device.
1412

1413
  First, if the device is assembled (Attach() is successful), then
1414
  the device is shutdown. Then the children of the device are
1415
  shutdown.
1416

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

1421
  @type disk: L{objects.Disk}
1422
  @param disk: the description of the disk we should
1423
      shutdown
1424
  @rtype: None
1425

1426
  """
1427
  msgs = []
1428
  r_dev = _RecursiveFindBD(disk)
1429
  if r_dev is not None:
1430
    r_path = r_dev.dev_path
1431
    try:
1432
      r_dev.Shutdown()
1433
      DevCacheManager.RemoveCache(r_path)
1434
    except errors.BlockDeviceError, err:
1435
      msgs.append(str(err))
1436

    
1437
  if disk.children:
1438
    for child in disk.children:
1439
      try:
1440
        BlockdevShutdown(child)
1441
      except RPCFail, err:
1442
        msgs.append(str(err))
1443

    
1444
  if msgs:
1445
    _Fail("; ".join(msgs))
1446

    
1447

    
1448
def BlockdevAddchildren(parent_cdev, new_cdevs):
1449
  """Extend a mirrored block device.
1450

1451
  @type parent_cdev: L{objects.Disk}
1452
  @param parent_cdev: the disk to which we should add children
1453
  @type new_cdevs: list of L{objects.Disk}
1454
  @param new_cdevs: the list of children which we should add
1455
  @rtype: None
1456

1457
  """
1458
  parent_bdev = _RecursiveFindBD(parent_cdev)
1459
  if parent_bdev is None:
1460
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1461
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1462
  if new_bdevs.count(None) > 0:
1463
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1464
  parent_bdev.AddChildren(new_bdevs)
1465

    
1466

    
1467
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1468
  """Shrink a mirrored block device.
1469

1470
  @type parent_cdev: L{objects.Disk}
1471
  @param parent_cdev: the disk from which we should remove children
1472
  @type new_cdevs: list of L{objects.Disk}
1473
  @param new_cdevs: the list of children which we should remove
1474
  @rtype: None
1475

1476
  """
1477
  parent_bdev = _RecursiveFindBD(parent_cdev)
1478
  if parent_bdev is None:
1479
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1480
  devs = []
1481
  for disk in new_cdevs:
1482
    rpath = disk.StaticDevPath()
1483
    if rpath is None:
1484
      bd = _RecursiveFindBD(disk)
1485
      if bd is None:
1486
        _Fail("Can't find device %s while removing children", disk)
1487
      else:
1488
        devs.append(bd.dev_path)
1489
    else:
1490
      if not utils.IsNormAbsPath(rpath):
1491
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
1492
      devs.append(rpath)
1493
  parent_bdev.RemoveChildren(devs)
1494

    
1495

    
1496
def BlockdevGetmirrorstatus(disks):
1497
  """Get the mirroring status of a list of devices.
1498

1499
  @type disks: list of L{objects.Disk}
1500
  @param disks: the list of disks which we should query
1501
  @rtype: disk
1502
  @return:
1503
      a list of (mirror_done, estimated_time) tuples, which
1504
      are the result of L{bdev.BlockDev.CombinedSyncStatus}
1505
  @raise errors.BlockDeviceError: if any of the disks cannot be
1506
      found
1507

1508
  """
1509
  stats = []
1510
  for dsk in disks:
1511
    rbd = _RecursiveFindBD(dsk)
1512
    if rbd is None:
1513
      _Fail("Can't find device %s", dsk)
1514

    
1515
    stats.append(rbd.CombinedSyncStatus())
1516

    
1517
  return stats
1518

    
1519

    
1520
def _RecursiveFindBD(disk):
1521
  """Check if a device is activated.
1522

1523
  If so, return information about the real device.
1524

1525
  @type disk: L{objects.Disk}
1526
  @param disk: the disk object we need to find
1527

1528
  @return: None if the device can't be found,
1529
      otherwise the device instance
1530

1531
  """
1532
  children = []
1533
  if disk.children:
1534
    for chdisk in disk.children:
1535
      children.append(_RecursiveFindBD(chdisk))
1536

    
1537
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1538

    
1539

    
1540
def _OpenRealBD(disk):
1541
  """Opens the underlying block device of a disk.
1542

1543
  @type disk: L{objects.Disk}
1544
  @param disk: the disk object we want to open
1545

1546
  """
1547
  real_disk = _RecursiveFindBD(disk)
1548
  if real_disk is None:
1549
    _Fail("Block device '%s' is not set up", disk)
1550

    
1551
  real_disk.Open()
1552

    
1553
  return real_disk
1554

    
1555

    
1556
def BlockdevFind(disk):
1557
  """Check if a device is activated.
1558

1559
  If it is, return information about the real device.
1560

1561
  @type disk: L{objects.Disk}
1562
  @param disk: the disk to find
1563
  @rtype: None or objects.BlockDevStatus
1564
  @return: None if the disk cannot be found, otherwise a the current
1565
           information
1566

1567
  """
1568
  try:
1569
    rbd = _RecursiveFindBD(disk)
1570
  except errors.BlockDeviceError, err:
1571
    _Fail("Failed to find device: %s", err, exc=True)
1572

    
1573
  if rbd is None:
1574
    return None
1575

    
1576
  return rbd.GetSyncStatus()
1577

    
1578

    
1579
def BlockdevGetsize(disks):
1580
  """Computes the size of the given disks.
1581

1582
  If a disk is not found, returns None instead.
1583

1584
  @type disks: list of L{objects.Disk}
1585
  @param disks: the list of disk to compute the size for
1586
  @rtype: list
1587
  @return: list with elements None if the disk cannot be found,
1588
      otherwise the size
1589

1590
  """
1591
  result = []
1592
  for cf in disks:
1593
    try:
1594
      rbd = _RecursiveFindBD(cf)
1595
    except errors.BlockDeviceError:
1596
      result.append(None)
1597
      continue
1598
    if rbd is None:
1599
      result.append(None)
1600
    else:
1601
      result.append(rbd.GetActualSize())
1602
  return result
1603

    
1604

    
1605
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
1606
  """Export a block device to a remote node.
1607

1608
  @type disk: L{objects.Disk}
1609
  @param disk: the description of the disk to export
1610
  @type dest_node: str
1611
  @param dest_node: the destination node to export to
1612
  @type dest_path: str
1613
  @param dest_path: the destination path on the target node
1614
  @type cluster_name: str
1615
  @param cluster_name: the cluster name, needed for SSH hostalias
1616
  @rtype: None
1617

1618
  """
1619
  real_disk = _OpenRealBD(disk)
1620

    
1621
  # the block size on the read dd is 1MiB to match our units
1622
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
1623
                               "dd if=%s bs=1048576 count=%s",
1624
                               real_disk.dev_path, str(disk.size))
1625

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

    
1635
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1636
                                                   constants.GANETI_RUNAS,
1637
                                                   destcmd)
1638

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

    
1642
  result = utils.RunCmd(["bash", "-c", command])
1643

    
1644
  if result.failed:
1645
    _Fail("Disk copy command '%s' returned error: %s"
1646
          " output: %s", command, result.fail_reason, result.output)
1647

    
1648

    
1649
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1650
  """Write a file to the filesystem.
1651

1652
  This allows the master to overwrite(!) a file. It will only perform
1653
  the operation if the file belongs to a list of configuration files.
1654

1655
  @type file_name: str
1656
  @param file_name: the target file name
1657
  @type data: str
1658
  @param data: the new contents of the file
1659
  @type mode: int
1660
  @param mode: the mode to give the file (can be None)
1661
  @type uid: int
1662
  @param uid: the owner of the file (can be -1 for default)
1663
  @type gid: int
1664
  @param gid: the group of the file (can be -1 for default)
1665
  @type atime: float
1666
  @param atime: the atime to set on the file (can be None)
1667
  @type mtime: float
1668
  @param mtime: the mtime to set on the file (can be None)
1669
  @rtype: None
1670

1671
  """
1672
  if not os.path.isabs(file_name):
1673
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
1674

    
1675
  if file_name not in _ALLOWED_UPLOAD_FILES:
1676
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
1677
          file_name)
1678

    
1679
  raw_data = _Decompress(data)
1680

    
1681
  utils.WriteFile(file_name, data=raw_data, mode=mode, uid=uid, gid=gid,
1682
                  atime=atime, mtime=mtime)
1683

    
1684

    
1685
def WriteSsconfFiles(values):
1686
  """Update all ssconf files.
1687

1688
  Wrapper around the SimpleStore.WriteFiles.
1689

1690
  """
1691
  ssconf.SimpleStore().WriteFiles(values)
1692

    
1693

    
1694
def _ErrnoOrStr(err):
1695
  """Format an EnvironmentError exception.
1696

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

1701
  @type err: L{EnvironmentError}
1702
  @param err: the exception to format
1703

1704
  """
1705
  if hasattr(err, 'errno'):
1706
    detail = errno.errorcode[err.errno]
1707
  else:
1708
    detail = str(err)
1709
  return detail
1710

    
1711

    
1712
def _OSOndiskAPIVersion(os_dir):
1713
  """Compute and return the API version of a given OS.
1714

1715
  This function will try to read the API version of the OS residing in
1716
  the 'os_dir' directory.
1717

1718
  @type os_dir: str
1719
  @param os_dir: the directory in which we should look for the OS
1720
  @rtype: tuple
1721
  @return: tuple (status, data) with status denoting the validity and
1722
      data holding either the vaid versions or an error message
1723

1724
  """
1725
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
1726

    
1727
  try:
1728
    st = os.stat(api_file)
1729
  except EnvironmentError, err:
1730
    return False, ("Required file '%s' not found under path %s: %s" %
1731
                   (constants.OS_API_FILE, os_dir, _ErrnoOrStr(err)))
1732

    
1733
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1734
    return False, ("File '%s' in %s is not a regular file" %
1735
                   (constants.OS_API_FILE, os_dir))
1736

    
1737
  try:
1738
    api_versions = utils.ReadFile(api_file).splitlines()
1739
  except EnvironmentError, err:
1740
    return False, ("Error while reading the API version file at %s: %s" %
1741
                   (api_file, _ErrnoOrStr(err)))
1742

    
1743
  try:
1744
    api_versions = [int(version.strip()) for version in api_versions]
1745
  except (TypeError, ValueError), err:
1746
    return False, ("API version(s) can't be converted to integer: %s" %
1747
                   str(err))
1748

    
1749
  return True, api_versions
1750

    
1751

    
1752
def DiagnoseOS(top_dirs=None):
1753
  """Compute the validity for all OSes.
1754

1755
  @type top_dirs: list
1756
  @param top_dirs: the list of directories in which to
1757
      search (if not given defaults to
1758
      L{constants.OS_SEARCH_PATH})
1759
  @rtype: list of L{objects.OS}
1760
  @return: a list of tuples (name, path, status, diagnose, variants,
1761
      parameters, api_version) for all (potential) OSes under all
1762
      search paths, where:
1763
          - name is the (potential) OS name
1764
          - path is the full path to the OS
1765
          - status True/False is the validity of the OS
1766
          - diagnose is the error message for an invalid OS, otherwise empty
1767
          - variants is a list of supported OS variants, if any
1768
          - parameters is a list of (name, help) parameters, if any
1769
          - api_version is a list of support OS API versions
1770

1771
  """
1772
  if top_dirs is None:
1773
    top_dirs = constants.OS_SEARCH_PATH
1774

    
1775
  result = []
1776
  for dir_name in top_dirs:
1777
    if os.path.isdir(dir_name):
1778
      try:
1779
        f_names = utils.ListVisibleFiles(dir_name)
1780
      except EnvironmentError, err:
1781
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
1782
        break
1783
      for name in f_names:
1784
        os_path = utils.PathJoin(dir_name, name)
1785
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
1786
        if status:
1787
          diagnose = ""
1788
          variants = os_inst.supported_variants
1789
          parameters = os_inst.supported_parameters
1790
          api_versions = os_inst.api_versions
1791
        else:
1792
          diagnose = os_inst
1793
          variants = parameters = api_versions = []
1794
        result.append((name, os_path, status, diagnose, variants,
1795
                       parameters, api_versions))
1796

    
1797
  return result
1798

    
1799

    
1800
def _TryOSFromDisk(name, base_dir=None):
1801
  """Create an OS instance from disk.
1802

1803
  This function will return an OS instance if the given name is a
1804
  valid OS name.
1805

1806
  @type base_dir: string
1807
  @keyword base_dir: Base directory containing OS installations.
1808
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1809
  @rtype: tuple
1810
  @return: success and either the OS instance if we find a valid one,
1811
      or error message
1812

1813
  """
1814
  if base_dir is None:
1815
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1816
  else:
1817
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
1818

    
1819
  if os_dir is None:
1820
    return False, "Directory for OS %s not found in search path" % name
1821

    
1822
  status, api_versions = _OSOndiskAPIVersion(os_dir)
1823
  if not status:
1824
    # push the error up
1825
    return status, api_versions
1826

    
1827
  if not constants.OS_API_VERSIONS.intersection(api_versions):
1828
    return False, ("API version mismatch for path '%s': found %s, want %s." %
1829
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
1830

    
1831
  # OS Files dictionary, we will populate it with the absolute path names
1832
  os_files = dict.fromkeys(constants.OS_SCRIPTS)
1833

    
1834
  if max(api_versions) >= constants.OS_API_V15:
1835
    os_files[constants.OS_VARIANTS_FILE] = ''
1836

    
1837
  if max(api_versions) >= constants.OS_API_V20:
1838
    os_files[constants.OS_PARAMETERS_FILE] = ''
1839
  else:
1840
    del os_files[constants.OS_SCRIPT_VERIFY]
1841

    
1842
  for filename in os_files:
1843
    os_files[filename] = utils.PathJoin(os_dir, filename)
1844

    
1845
    try:
1846
      st = os.stat(os_files[filename])
1847
    except EnvironmentError, err:
1848
      return False, ("File '%s' under path '%s' is missing (%s)" %
1849
                     (filename, os_dir, _ErrnoOrStr(err)))
1850

    
1851
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1852
      return False, ("File '%s' under path '%s' is not a regular file" %
1853
                     (filename, os_dir))
1854

    
1855
    if filename in constants.OS_SCRIPTS:
1856
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1857
        return False, ("File '%s' under path '%s' is not executable" %
1858
                       (filename, os_dir))
1859

    
1860
  variants = []
1861
  if constants.OS_VARIANTS_FILE in os_files:
1862
    variants_file = os_files[constants.OS_VARIANTS_FILE]
1863
    try:
1864
      variants = utils.ReadFile(variants_file).splitlines()
1865
    except EnvironmentError, err:
1866
      return False, ("Error while reading the OS variants file at %s: %s" %
1867
                     (variants_file, _ErrnoOrStr(err)))
1868
    if not variants:
1869
      return False, ("No supported os variant found")
1870

    
1871
  parameters = []
1872
  if constants.OS_PARAMETERS_FILE in os_files:
1873
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
1874
    try:
1875
      parameters = utils.ReadFile(parameters_file).splitlines()
1876
    except EnvironmentError, err:
1877
      return False, ("Error while reading the OS parameters file at %s: %s" %
1878
                     (parameters_file, _ErrnoOrStr(err)))
1879
    parameters = [v.split(None, 1) for v in parameters]
1880

    
1881
  os_obj = objects.OS(name=name, path=os_dir,
1882
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
1883
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
1884
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
1885
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
1886
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
1887
                                                 None),
1888
                      supported_variants=variants,
1889
                      supported_parameters=parameters,
1890
                      api_versions=api_versions)
1891
  return True, os_obj
1892

    
1893

    
1894
def OSFromDisk(name, base_dir=None):
1895
  """Create an OS instance from disk.
1896

1897
  This function will return an OS instance if the given name is a
1898
  valid OS name. Otherwise, it will raise an appropriate
1899
  L{RPCFail} exception, detailing why this is not a valid OS.
1900

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

1904
  @type base_dir: string
1905
  @keyword base_dir: Base directory containing OS installations.
1906
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1907
  @rtype: L{objects.OS}
1908
  @return: the OS instance if we find a valid one
1909
  @raise RPCFail: if we don't find a valid OS
1910

1911
  """
1912
  name_only = name.split("+", 1)[0]
1913
  status, payload = _TryOSFromDisk(name_only, base_dir)
1914

    
1915
  if not status:
1916
    _Fail(payload)
1917

    
1918
  return payload
1919

    
1920

    
1921
def OSCoreEnv(inst_os, os_params, debug=0):
1922
  """Calculate the basic environment for an os script.
1923

1924
  @type inst_os: L{objects.OS}
1925
  @param inst_os: operating system for which the environment is being built
1926
  @type os_params: dict
1927
  @param os_params: the OS parameters
1928
  @type debug: integer
1929
  @param debug: debug level (0 or 1, for OS Api 10)
1930
  @rtype: dict
1931
  @return: dict of environment variables
1932
  @raise errors.BlockDeviceError: if the block device
1933
      cannot be found
1934

1935
  """
1936
  result = {}
1937
  api_version = \
1938
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
1939
  result['OS_API_VERSION'] = '%d' % api_version
1940
  result['OS_NAME'] = inst_os.name
1941
  result['DEBUG_LEVEL'] = '%d' % debug
1942

    
1943
  # OS variants
1944
  if api_version >= constants.OS_API_V15:
1945
    try:
1946
      variant = inst_os.name.split('+', 1)[1]
1947
    except IndexError:
1948
      variant = inst_os.supported_variants[0]
1949
    result['OS_VARIANT'] = variant
1950

    
1951
  # OS params
1952
  for pname, pvalue in os_params.items():
1953
    result['OSP_%s' % pname.upper()] = pvalue
1954

    
1955
  return result
1956

    
1957

    
1958
def OSEnvironment(instance, inst_os, debug=0):
1959
  """Calculate the environment for an os script.
1960

1961
  @type instance: L{objects.Instance}
1962
  @param instance: target instance for the os script run
1963
  @type inst_os: L{objects.OS}
1964
  @param inst_os: operating system for which the environment is being built
1965
  @type debug: integer
1966
  @param debug: debug level (0 or 1, for OS Api 10)
1967
  @rtype: dict
1968
  @return: dict of environment variables
1969
  @raise errors.BlockDeviceError: if the block device
1970
      cannot be found
1971

1972
  """
1973
  result = OSCoreEnv(inst_os, instance.osparams, debug=debug)
1974

    
1975
  result['INSTANCE_NAME'] = instance.name
1976
  result['INSTANCE_OS'] = instance.os
1977
  result['HYPERVISOR'] = instance.hypervisor
1978
  result['DISK_COUNT'] = '%d' % len(instance.disks)
1979
  result['NIC_COUNT'] = '%d' % len(instance.nics)
1980

    
1981
  # Disks
1982
  for idx, disk in enumerate(instance.disks):
1983
    real_disk = _OpenRealBD(disk)
1984
    result['DISK_%d_PATH' % idx] = real_disk.dev_path
1985
    result['DISK_%d_ACCESS' % idx] = disk.mode
1986
    if constants.HV_DISK_TYPE in instance.hvparams:
1987
      result['DISK_%d_FRONTEND_TYPE' % idx] = \
1988
        instance.hvparams[constants.HV_DISK_TYPE]
1989
    if disk.dev_type in constants.LDS_BLOCK:
1990
      result['DISK_%d_BACKEND_TYPE' % idx] = 'block'
1991
    elif disk.dev_type == constants.LD_FILE:
1992
      result['DISK_%d_BACKEND_TYPE' % idx] = \
1993
        'file:%s' % disk.physical_id[0]
1994

    
1995
  # NICs
1996
  for idx, nic in enumerate(instance.nics):
1997
    result['NIC_%d_MAC' % idx] = nic.mac
1998
    if nic.ip:
1999
      result['NIC_%d_IP' % idx] = nic.ip
2000
    result['NIC_%d_MODE' % idx] = nic.nicparams[constants.NIC_MODE]
2001
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2002
      result['NIC_%d_BRIDGE' % idx] = nic.nicparams[constants.NIC_LINK]
2003
    if nic.nicparams[constants.NIC_LINK]:
2004
      result['NIC_%d_LINK' % idx] = nic.nicparams[constants.NIC_LINK]
2005
    if constants.HV_NIC_TYPE in instance.hvparams:
2006
      result['NIC_%d_FRONTEND_TYPE' % idx] = \
2007
        instance.hvparams[constants.HV_NIC_TYPE]
2008

    
2009
  # HV/BE params
2010
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2011
    for key, value in source.items():
2012
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2013

    
2014
  return result
2015

    
2016

    
2017
def BlockdevGrow(disk, amount):
2018
  """Grow a stack of block devices.
2019

2020
  This function is called recursively, with the childrens being the
2021
  first ones to resize.
2022

2023
  @type disk: L{objects.Disk}
2024
  @param disk: the disk to be grown
2025
  @rtype: (status, result)
2026
  @return: a tuple with the status of the operation
2027
      (True/False), and the errors message if status
2028
      is False
2029

2030
  """
2031
  r_dev = _RecursiveFindBD(disk)
2032
  if r_dev is None:
2033
    _Fail("Cannot find block device %s", disk)
2034

    
2035
  try:
2036
    r_dev.Grow(amount)
2037
  except errors.BlockDeviceError, err:
2038
    _Fail("Failed to grow block device: %s", err, exc=True)
2039

    
2040

    
2041
def BlockdevSnapshot(disk):
2042
  """Create a snapshot copy of a block device.
2043

2044
  This function is called recursively, and the snapshot is actually created
2045
  just for the leaf lvm backend device.
2046

2047
  @type disk: L{objects.Disk}
2048
  @param disk: the disk to be snapshotted
2049
  @rtype: string
2050
  @return: snapshot disk path
2051

2052
  """
2053
  if disk.dev_type == constants.LD_DRBD8:
2054
    if not disk.children:
2055
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2056
            disk.unique_id)
2057
    return BlockdevSnapshot(disk.children[0])
2058
  elif disk.dev_type == constants.LD_LV:
2059
    r_dev = _RecursiveFindBD(disk)
2060
    if r_dev is not None:
2061
      # FIXME: choose a saner value for the snapshot size
2062
      # let's stay on the safe side and ask for the full size, for now
2063
      return r_dev.Snapshot(disk.size)
2064
    else:
2065
      _Fail("Cannot find block device %s", disk)
2066
  else:
2067
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2068
          disk.unique_id, disk.dev_type)
2069

    
2070

    
2071
def FinalizeExport(instance, snap_disks):
2072
  """Write out the export configuration information.
2073

2074
  @type instance: L{objects.Instance}
2075
  @param instance: the instance which we export, used for
2076
      saving configuration
2077
  @type snap_disks: list of L{objects.Disk}
2078
  @param snap_disks: list of snapshot block devices, which
2079
      will be used to get the actual name of the dump file
2080

2081
  @rtype: None
2082

2083
  """
2084
  destdir = utils.PathJoin(constants.EXPORT_DIR, instance.name + ".new")
2085
  finaldestdir = utils.PathJoin(constants.EXPORT_DIR, instance.name)
2086

    
2087
  config = objects.SerializableConfigParser()
2088

    
2089
  config.add_section(constants.INISECT_EXP)
2090
  config.set(constants.INISECT_EXP, 'version', '0')
2091
  config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
2092
  config.set(constants.INISECT_EXP, 'source', instance.primary_node)
2093
  config.set(constants.INISECT_EXP, 'os', instance.os)
2094
  config.set(constants.INISECT_EXP, 'compression', 'gzip')
2095

    
2096
  config.add_section(constants.INISECT_INS)
2097
  config.set(constants.INISECT_INS, 'name', instance.name)
2098
  config.set(constants.INISECT_INS, 'memory', '%d' %
2099
             instance.beparams[constants.BE_MEMORY])
2100
  config.set(constants.INISECT_INS, 'vcpus', '%d' %
2101
             instance.beparams[constants.BE_VCPUS])
2102
  config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
2103
  config.set(constants.INISECT_INS, 'hypervisor', instance.hypervisor)
2104

    
2105
  nic_total = 0
2106
  for nic_count, nic in enumerate(instance.nics):
2107
    nic_total += 1
2108
    config.set(constants.INISECT_INS, 'nic%d_mac' %
2109
               nic_count, '%s' % nic.mac)
2110
    config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
2111
    for param in constants.NICS_PARAMETER_TYPES:
2112
      config.set(constants.INISECT_INS, 'nic%d_%s' % (nic_count, param),
2113
                 '%s' % nic.nicparams.get(param, None))
2114
  # TODO: redundant: on load can read nics until it doesn't exist
2115
  config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_total)
2116

    
2117
  disk_total = 0
2118
  for disk_count, disk in enumerate(snap_disks):
2119
    if disk:
2120
      disk_total += 1
2121
      config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
2122
                 ('%s' % disk.iv_name))
2123
      config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
2124
                 ('%s' % disk.physical_id[1]))
2125
      config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
2126
                 ('%d' % disk.size))
2127

    
2128
  config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_total)
2129

    
2130
  # New-style hypervisor/backend parameters
2131

    
2132
  config.add_section(constants.INISECT_HYP)
2133
  for name, value in instance.hvparams.items():
2134
    if name not in constants.HVC_GLOBALS:
2135
      config.set(constants.INISECT_HYP, name, str(value))
2136

    
2137
  config.add_section(constants.INISECT_BEP)
2138
  for name, value in instance.beparams.items():
2139
    config.set(constants.INISECT_BEP, name, str(value))
2140

    
2141
  config.add_section(constants.INISECT_OSP)
2142
  for name, value in instance.osparams.items():
2143
    config.set(constants.INISECT_OSP, name, str(value))
2144

    
2145
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2146
                  data=config.Dumps())
2147
  shutil.rmtree(finaldestdir, ignore_errors=True)
2148
  shutil.move(destdir, finaldestdir)
2149

    
2150

    
2151
def ExportInfo(dest):
2152
  """Get export configuration information.
2153

2154
  @type dest: str
2155
  @param dest: directory containing the export
2156

2157
  @rtype: L{objects.SerializableConfigParser}
2158
  @return: a serializable config file containing the
2159
      export info
2160

2161
  """
2162
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2163

    
2164
  config = objects.SerializableConfigParser()
2165
  config.read(cff)
2166

    
2167
  if (not config.has_section(constants.INISECT_EXP) or
2168
      not config.has_section(constants.INISECT_INS)):
2169
    _Fail("Export info file doesn't have the required fields")
2170

    
2171
  return config.Dumps()
2172

    
2173

    
2174
def ListExports():
2175
  """Return a list of exports currently available on this machine.
2176

2177
  @rtype: list
2178
  @return: list of the exports
2179

2180
  """
2181
  if os.path.isdir(constants.EXPORT_DIR):
2182
    return sorted(utils.ListVisibleFiles(constants.EXPORT_DIR))
2183
  else:
2184
    _Fail("No exports directory")
2185

    
2186

    
2187
def RemoveExport(export):
2188
  """Remove an existing export from the node.
2189

2190
  @type export: str
2191
  @param export: the name of the export to remove
2192
  @rtype: None
2193

2194
  """
2195
  target = utils.PathJoin(constants.EXPORT_DIR, export)
2196

    
2197
  try:
2198
    shutil.rmtree(target)
2199
  except EnvironmentError, err:
2200
    _Fail("Error while removing the export: %s", err, exc=True)
2201

    
2202

    
2203
def BlockdevRename(devlist):
2204
  """Rename a list of block devices.
2205

2206
  @type devlist: list of tuples
2207
  @param devlist: list of tuples of the form  (disk,
2208
      new_logical_id, new_physical_id); disk is an
2209
      L{objects.Disk} object describing the current disk,
2210
      and new logical_id/physical_id is the name we
2211
      rename it to
2212
  @rtype: boolean
2213
  @return: True if all renames succeeded, False otherwise
2214

2215
  """
2216
  msgs = []
2217
  result = True
2218
  for disk, unique_id in devlist:
2219
    dev = _RecursiveFindBD(disk)
2220
    if dev is None:
2221
      msgs.append("Can't find device %s in rename" % str(disk))
2222
      result = False
2223
      continue
2224
    try:
2225
      old_rpath = dev.dev_path
2226
      dev.Rename(unique_id)
2227
      new_rpath = dev.dev_path
2228
      if old_rpath != new_rpath:
2229
        DevCacheManager.RemoveCache(old_rpath)
2230
        # FIXME: we should add the new cache information here, like:
2231
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2232
        # but we don't have the owner here - maybe parse from existing
2233
        # cache? for now, we only lose lvm data when we rename, which
2234
        # is less critical than DRBD or MD
2235
    except errors.BlockDeviceError, err:
2236
      msgs.append("Can't rename device '%s' to '%s': %s" %
2237
                  (dev, unique_id, err))
2238
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2239
      result = False
2240
  if not result:
2241
    _Fail("; ".join(msgs))
2242

    
2243

    
2244
def _TransformFileStorageDir(file_storage_dir):
2245
  """Checks whether given file_storage_dir is valid.
2246

2247
  Checks wheter the given file_storage_dir is within the cluster-wide
2248
  default file_storage_dir stored in SimpleStore. Only paths under that
2249
  directory are allowed.
2250

2251
  @type file_storage_dir: str
2252
  @param file_storage_dir: the path to check
2253

2254
  @return: the normalized path if valid, None otherwise
2255

2256
  """
2257
  if not constants.ENABLE_FILE_STORAGE:
2258
    _Fail("File storage disabled at configure time")
2259
  cfg = _GetConfig()
2260
  file_storage_dir = os.path.normpath(file_storage_dir)
2261
  base_file_storage_dir = cfg.GetFileStorageDir()
2262
  if (os.path.commonprefix([file_storage_dir, base_file_storage_dir]) !=
2263
      base_file_storage_dir):
2264
    _Fail("File storage directory '%s' is not under base file"
2265
          " storage directory '%s'", file_storage_dir, base_file_storage_dir)
2266
  return file_storage_dir
2267

    
2268

    
2269
def CreateFileStorageDir(file_storage_dir):
2270
  """Create file storage directory.
2271

2272
  @type file_storage_dir: str
2273
  @param file_storage_dir: directory to create
2274

2275
  @rtype: tuple
2276
  @return: tuple with first element a boolean indicating wheter dir
2277
      creation was successful or not
2278

2279
  """
2280
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2281
  if os.path.exists(file_storage_dir):
2282
    if not os.path.isdir(file_storage_dir):
2283
      _Fail("Specified storage dir '%s' is not a directory",
2284
            file_storage_dir)
2285
  else:
2286
    try:
2287
      os.makedirs(file_storage_dir, 0750)
2288
    except OSError, err:
2289
      _Fail("Cannot create file storage directory '%s': %s",
2290
            file_storage_dir, err, exc=True)
2291

    
2292

    
2293
def RemoveFileStorageDir(file_storage_dir):
2294
  """Remove file storage directory.
2295

2296
  Remove it only if it's empty. If not log an error and return.
2297

2298
  @type file_storage_dir: str
2299
  @param file_storage_dir: the directory we should cleanup
2300
  @rtype: tuple (success,)
2301
  @return: tuple of one element, C{success}, denoting
2302
      whether the operation was successful
2303

2304
  """
2305
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2306
  if os.path.exists(file_storage_dir):
2307
    if not os.path.isdir(file_storage_dir):
2308
      _Fail("Specified Storage directory '%s' is not a directory",
2309
            file_storage_dir)
2310
    # deletes dir only if empty, otherwise we want to fail the rpc call
2311
    try:
2312
      os.rmdir(file_storage_dir)
2313
    except OSError, err:
2314
      _Fail("Cannot remove file storage directory '%s': %s",
2315
            file_storage_dir, err)
2316

    
2317

    
2318
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2319
  """Rename the file storage directory.
2320

2321
  @type old_file_storage_dir: str
2322
  @param old_file_storage_dir: the current path
2323
  @type new_file_storage_dir: str
2324
  @param new_file_storage_dir: the name we should rename to
2325
  @rtype: tuple (success,)
2326
  @return: tuple of one element, C{success}, denoting
2327
      whether the operation was successful
2328

2329
  """
2330
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2331
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2332
  if not os.path.exists(new_file_storage_dir):
2333
    if os.path.isdir(old_file_storage_dir):
2334
      try:
2335
        os.rename(old_file_storage_dir, new_file_storage_dir)
2336
      except OSError, err:
2337
        _Fail("Cannot rename '%s' to '%s': %s",
2338
              old_file_storage_dir, new_file_storage_dir, err)
2339
    else:
2340
      _Fail("Specified storage dir '%s' is not a directory",
2341
            old_file_storage_dir)
2342
  else:
2343
    if os.path.exists(old_file_storage_dir):
2344
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2345
            old_file_storage_dir, new_file_storage_dir)
2346

    
2347

    
2348
def _EnsureJobQueueFile(file_name):
2349
  """Checks whether the given filename is in the queue directory.
2350

2351
  @type file_name: str
2352
  @param file_name: the file name we should check
2353
  @rtype: None
2354
  @raises RPCFail: if the file is not valid
2355

2356
  """
2357
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2358
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2359

    
2360
  if not result:
2361
    _Fail("Passed job queue file '%s' does not belong to"
2362
          " the queue directory '%s'", file_name, queue_dir)
2363

    
2364

    
2365
def JobQueueUpdate(file_name, content):
2366
  """Updates a file in the queue directory.
2367

2368
  This is just a wrapper over L{utils.WriteFile}, with proper
2369
  checking.
2370

2371
  @type file_name: str
2372
  @param file_name: the job file name
2373
  @type content: str
2374
  @param content: the new job contents
2375
  @rtype: boolean
2376
  @return: the success of the operation
2377

2378
  """
2379
  _EnsureJobQueueFile(file_name)
2380

    
2381
  # Write and replace the file atomically
2382
  utils.WriteFile(file_name, data=_Decompress(content))
2383

    
2384

    
2385
def JobQueueRename(old, new):
2386
  """Renames a job queue file.
2387

2388
  This is just a wrapper over os.rename with proper checking.
2389

2390
  @type old: str
2391
  @param old: the old (actual) file name
2392
  @type new: str
2393
  @param new: the desired file name
2394
  @rtype: tuple
2395
  @return: the success of the operation and payload
2396

2397
  """
2398
  _EnsureJobQueueFile(old)
2399
  _EnsureJobQueueFile(new)
2400

    
2401
  utils.RenameFile(old, new, mkdir=True)
2402

    
2403

    
2404
def BlockdevClose(instance_name, disks):
2405
  """Closes the given block devices.
2406

2407
  This means they will be switched to secondary mode (in case of
2408
  DRBD).
2409

2410
  @param instance_name: if the argument is not empty, the symlinks
2411
      of this instance will be removed
2412
  @type disks: list of L{objects.Disk}
2413
  @param disks: the list of disks to be closed
2414
  @rtype: tuple (success, message)
2415
  @return: a tuple of success and message, where success
2416
      indicates the succes of the operation, and message
2417
      which will contain the error details in case we
2418
      failed
2419

2420
  """
2421
  bdevs = []
2422
  for cf in disks:
2423
    rd = _RecursiveFindBD(cf)
2424
    if rd is None:
2425
      _Fail("Can't find device %s", cf)
2426
    bdevs.append(rd)
2427

    
2428
  msg = []
2429
  for rd in bdevs:
2430
    try:
2431
      rd.Close()
2432
    except errors.BlockDeviceError, err:
2433
      msg.append(str(err))
2434
  if msg:
2435
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2436
  else:
2437
    if instance_name:
2438
      _RemoveBlockDevLinks(instance_name, disks)
2439

    
2440

    
2441
def ValidateHVParams(hvname, hvparams):
2442
  """Validates the given hypervisor parameters.
2443

2444
  @type hvname: string
2445
  @param hvname: the hypervisor name
2446
  @type hvparams: dict
2447
  @param hvparams: the hypervisor parameters to be validated
2448
  @rtype: None
2449

2450
  """
2451
  try:
2452
    hv_type = hypervisor.GetHypervisor(hvname)
2453
    hv_type.ValidateParameters(hvparams)
2454
  except errors.HypervisorError, err:
2455
    _Fail(str(err), log=False)
2456

    
2457

    
2458
def _CheckOSPList(os_obj, parameters):
2459
  """Check whether a list of parameters is supported by the OS.
2460

2461
  @type os_obj: L{objects.OS}
2462
  @param os_obj: OS object to check
2463
  @type parameters: list
2464
  @param parameters: the list of parameters to check
2465

2466
  """
2467
  supported = [v[0] for v in os_obj.supported_parameters]
2468
  delta = frozenset(parameters).difference(supported)
2469
  if delta:
2470
    _Fail("The following parameters are not supported"
2471
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
2472

    
2473

    
2474
def ValidateOS(required, osname, checks, osparams):
2475
  """Validate the given OS' parameters.
2476

2477
  @type required: boolean
2478
  @param required: whether absence of the OS should translate into
2479
      failure or not
2480
  @type osname: string
2481
  @param osname: the OS to be validated
2482
  @type checks: list
2483
  @param checks: list of the checks to run (currently only 'parameters')
2484
  @type osparams: dict
2485
  @param osparams: dictionary with OS parameters
2486
  @rtype: boolean
2487
  @return: True if the validation passed, or False if the OS was not
2488
      found and L{required} was false
2489

2490
  """
2491
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
2492
    _Fail("Unknown checks required for OS %s: %s", osname,
2493
          set(checks).difference(constants.OS_VALIDATE_CALLS))
2494

    
2495
  name_only = osname.split("+", 1)[0]
2496
  status, tbv = _TryOSFromDisk(name_only, None)
2497

    
2498
  if not status:
2499
    if required:
2500
      _Fail(tbv)
2501
    else:
2502
      return False
2503

    
2504
  if max(tbv.api_versions) < constants.OS_API_V20:
2505
    return True
2506

    
2507
  if constants.OS_VALIDATE_PARAMETERS in checks:
2508
    _CheckOSPList(tbv, osparams.keys())
2509

    
2510
  validate_env = OSCoreEnv(tbv, osparams)
2511
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
2512
                        cwd=tbv.path)
2513
  if result.failed:
2514
    logging.error("os validate command '%s' returned error: %s output: %s",
2515
                  result.cmd, result.fail_reason, result.output)
2516
    _Fail("OS validation script failed (%s), output: %s",
2517
          result.fail_reason, result.output, log=False)
2518

    
2519
  return True
2520

    
2521

    
2522
def DemoteFromMC():
2523
  """Demotes the current node from master candidate role.
2524

2525
  """
2526
  # try to ensure we're not the master by mistake
2527
  master, myself = ssconf.GetMasterAndMyself()
2528
  if master == myself:
2529
    _Fail("ssconf status shows I'm the master node, will not demote")
2530

    
2531
  result = utils.RunCmd([constants.DAEMON_UTIL, "check", constants.MASTERD])
2532
  if not result.failed:
2533
    _Fail("The master daemon is running, will not demote")
2534

    
2535
  try:
2536
    if os.path.isfile(constants.CLUSTER_CONF_FILE):
2537
      utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2538
  except EnvironmentError, err:
2539
    if err.errno != errno.ENOENT:
2540
      _Fail("Error while backing up cluster file: %s", err, exc=True)
2541

    
2542
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2543

    
2544

    
2545
def _GetX509Filenames(cryptodir, name):
2546
  """Returns the full paths for the private key and certificate.
2547

2548
  """
2549
  return (utils.PathJoin(cryptodir, name),
2550
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
2551
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
2552

    
2553

    
2554
def CreateX509Certificate(validity, cryptodir=constants.CRYPTO_KEYS_DIR):
2555
  """Creates a new X509 certificate for SSL/TLS.
2556

2557
  @type validity: int
2558
  @param validity: Validity in seconds
2559
  @rtype: tuple; (string, string)
2560
  @return: Certificate name and public part
2561

2562
  """
2563
  (key_pem, cert_pem) = \
2564
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
2565
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
2566

    
2567
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
2568
                              prefix="x509-%s-" % utils.TimestampForFilename())
2569
  try:
2570
    name = os.path.basename(cert_dir)
2571
    assert len(name) > 5
2572

    
2573
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2574

    
2575
    utils.WriteFile(key_file, mode=0400, data=key_pem)
2576
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
2577

    
2578
    # Never return private key as it shouldn't leave the node
2579
    return (name, cert_pem)
2580
  except Exception:
2581
    shutil.rmtree(cert_dir, ignore_errors=True)
2582
    raise
2583

    
2584

    
2585
def RemoveX509Certificate(name, cryptodir=constants.CRYPTO_KEYS_DIR):
2586
  """Removes a X509 certificate.
2587

2588
  @type name: string
2589
  @param name: Certificate name
2590

2591
  """
2592
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2593

    
2594
  utils.RemoveFile(key_file)
2595
  utils.RemoveFile(cert_file)
2596

    
2597
  try:
2598
    os.rmdir(cert_dir)
2599
  except EnvironmentError, err:
2600
    _Fail("Cannot remove certificate directory '%s': %s",
2601
          cert_dir, err)
2602

    
2603

    
2604
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
2605
  """Returns the command for the requested input/output.
2606

2607
  @type instance: L{objects.Instance}
2608
  @param instance: The instance object
2609
  @param mode: Import/export mode
2610
  @param ieio: Input/output type
2611
  @param ieargs: Input/output arguments
2612

2613
  """
2614
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
2615

    
2616
  env = None
2617
  prefix = None
2618
  suffix = None
2619
  exp_size = None
2620

    
2621
  if ieio == constants.IEIO_FILE:
2622
    (filename, ) = ieargs
2623

    
2624
    if not utils.IsNormAbsPath(filename):
2625
      _Fail("Path '%s' is not normalized or absolute", filename)
2626

    
2627
    directory = os.path.normpath(os.path.dirname(filename))
2628

    
2629
    if (os.path.commonprefix([constants.EXPORT_DIR, directory]) !=
2630
        constants.EXPORT_DIR):
2631
      _Fail("File '%s' is not under exports directory '%s'",
2632
            filename, constants.EXPORT_DIR)
2633

    
2634
    # Create directory
2635
    utils.Makedirs(directory, mode=0750)
2636

    
2637
    quoted_filename = utils.ShellQuote(filename)
2638

    
2639
    if mode == constants.IEM_IMPORT:
2640
      suffix = "> %s" % quoted_filename
2641
    elif mode == constants.IEM_EXPORT:
2642
      suffix = "< %s" % quoted_filename
2643

    
2644
      # Retrieve file size
2645
      try:
2646
        st = os.stat(filename)
2647
      except EnvironmentError, err:
2648
        logging.error("Can't stat(2) %s: %s", filename, err)
2649
      else:
2650
        exp_size = utils.BytesToMebibyte(st.st_size)
2651

    
2652
  elif ieio == constants.IEIO_RAW_DISK:
2653
    (disk, ) = ieargs
2654

    
2655
    real_disk = _OpenRealBD(disk)
2656

    
2657
    if mode == constants.IEM_IMPORT:
2658
      # we set here a smaller block size as, due to transport buffering, more
2659
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
2660
      # is not already there or we pass a wrong path; we use notrunc to no
2661
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
2662
      # much memory; this means that at best, we flush every 64k, which will
2663
      # not be very fast
2664
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
2665
                                    " bs=%s oflag=dsync"),
2666
                                    real_disk.dev_path,
2667
                                    str(64 * 1024))
2668

    
2669
    elif mode == constants.IEM_EXPORT:
2670
      # the block size on the read dd is 1MiB to match our units
2671
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
2672
                                   real_disk.dev_path,
2673
                                   str(1024 * 1024), # 1 MB
2674
                                   str(disk.size))
2675
      exp_size = disk.size
2676

    
2677
  elif ieio == constants.IEIO_SCRIPT:
2678
    (disk, disk_index, ) = ieargs
2679

    
2680
    assert isinstance(disk_index, (int, long))
2681

    
2682
    real_disk = _OpenRealBD(disk)
2683

    
2684
    inst_os = OSFromDisk(instance.os)
2685
    env = OSEnvironment(instance, inst_os)
2686

    
2687
    if mode == constants.IEM_IMPORT:
2688
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
2689
      env["IMPORT_INDEX"] = str(disk_index)
2690
      script = inst_os.import_script
2691

    
2692
    elif mode == constants.IEM_EXPORT:
2693
      env["EXPORT_DEVICE"] = real_disk.dev_path
2694
      env["EXPORT_INDEX"] = str(disk_index)
2695
      script = inst_os.export_script
2696

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

    
2700
    if mode == constants.IEM_IMPORT:
2701
      suffix = "| %s" % script_cmd
2702

    
2703
    elif mode == constants.IEM_EXPORT:
2704
      prefix = "%s |" % script_cmd
2705

    
2706
    # Let script predict size
2707
    exp_size = constants.IE_CUSTOM_SIZE
2708

    
2709
  else:
2710
    _Fail("Invalid %s I/O mode %r", mode, ieio)
2711

    
2712
  return (env, prefix, suffix, exp_size)
2713

    
2714

    
2715
def _CreateImportExportStatusDir(prefix):
2716
  """Creates status directory for import/export.
2717

2718
  """
2719
  return tempfile.mkdtemp(dir=constants.IMPORT_EXPORT_DIR,
2720
                          prefix=("%s-%s-" %
2721
                                  (prefix, utils.TimestampForFilename())))
2722

    
2723

    
2724
def StartImportExportDaemon(mode, opts, host, port, instance, ieio, ieioargs):
2725
  """Starts an import or export daemon.
2726

2727
  @param mode: Import/output mode
2728
  @type opts: L{objects.ImportExportOptions}
2729
  @param opts: Daemon options
2730
  @type host: string
2731
  @param host: Remote host for export (None for import)
2732
  @type port: int
2733
  @param port: Remote port for export (None for import)
2734
  @type instance: L{objects.Instance}
2735
  @param instance: Instance object
2736
  @param ieio: Input/output type
2737
  @param ieioargs: Input/output arguments
2738

2739
  """
2740
  if mode == constants.IEM_IMPORT:
2741
    prefix = "import"
2742

    
2743
    if not (host is None and port is None):
2744
      _Fail("Can not specify host or port on import")
2745

    
2746
  elif mode == constants.IEM_EXPORT:
2747
    prefix = "export"
2748

    
2749
    if host is None or port is None:
2750
      _Fail("Host and port must be specified for an export")
2751

    
2752
  else:
2753
    _Fail("Invalid mode %r", mode)
2754

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

    
2758
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
2759
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
2760

    
2761
  if opts.key_name is None:
2762
    # Use server.pem
2763
    key_path = constants.NODED_CERT_FILE
2764
    cert_path = constants.NODED_CERT_FILE
2765
    assert opts.ca_pem is None
2766
  else:
2767
    (_, key_path, cert_path) = _GetX509Filenames(constants.CRYPTO_KEYS_DIR,
2768
                                                 opts.key_name)
2769
    assert opts.ca_pem is not None
2770

    
2771
  for i in [key_path, cert_path]:
2772
    if not os.path.exists(i):
2773
      _Fail("File '%s' does not exist" % i)
2774

    
2775
  status_dir = _CreateImportExportStatusDir(prefix)
2776
  try:
2777
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
2778
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
2779
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
2780

    
2781
    if opts.ca_pem is None:
2782
      # Use server.pem
2783
      ca = utils.ReadFile(constants.NODED_CERT_FILE)
2784
    else:
2785
      ca = opts.ca_pem
2786

    
2787
    # Write CA file
2788
    utils.WriteFile(ca_file, data=ca, mode=0400)
2789

    
2790
    cmd = [
2791
      constants.IMPORT_EXPORT_DAEMON,
2792
      status_file, mode,
2793
      "--key=%s" % key_path,
2794
      "--cert=%s" % cert_path,
2795
      "--ca=%s" % ca_file,
2796
      ]
2797

    
2798
    if host:
2799
      cmd.append("--host=%s" % host)
2800

    
2801
    if port:
2802
      cmd.append("--port=%s" % port)
2803

    
2804
    if opts.compress:
2805
      cmd.append("--compress=%s" % opts.compress)
2806

    
2807
    if opts.magic:
2808
      cmd.append("--magic=%s" % opts.magic)
2809

    
2810
    if exp_size is not None:
2811
      cmd.append("--expected-size=%s" % exp_size)
2812

    
2813
    if cmd_prefix:
2814
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
2815

    
2816
    if cmd_suffix:
2817
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
2818

    
2819
    logfile = _InstanceLogName(prefix, instance.os, instance.name)
2820

    
2821
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
2822
    # support for receiving a file descriptor for output
2823
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
2824
                      output=logfile)
2825

    
2826
    # The import/export name is simply the status directory name
2827
    return os.path.basename(status_dir)
2828

    
2829
  except Exception:
2830
    shutil.rmtree(status_dir, ignore_errors=True)
2831
    raise
2832

    
2833

    
2834
def GetImportExportStatus(names):
2835
  """Returns import/export daemon status.
2836

2837
  @type names: sequence
2838
  @param names: List of names
2839
  @rtype: List of dicts
2840
  @return: Returns a list of the state of each named import/export or None if a
2841
           status couldn't be read
2842

2843
  """
2844
  result = []
2845

    
2846
  for name in names:
2847
    status_file = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name,
2848
                                 _IES_STATUS_FILE)
2849

    
2850
    try:
2851
      data = utils.ReadFile(status_file)
2852
    except EnvironmentError, err:
2853
      if err.errno != errno.ENOENT:
2854
        raise
2855
      data = None
2856

    
2857
    if not data:
2858
      result.append(None)
2859
      continue
2860

    
2861
    result.append(serializer.LoadJson(data))
2862

    
2863
  return result
2864

    
2865

    
2866
def AbortImportExport(name):
2867
  """Sends SIGTERM to a running import/export daemon.
2868

2869
  """
2870
  logging.info("Abort import/export %s", name)
2871

    
2872
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
2873
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
2874

    
2875
  if pid:
2876
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
2877
                 name, pid)
2878
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
2879

    
2880

    
2881
def CleanupImportExport(name):
2882
  """Cleanup after an import or export.
2883

2884
  If the import/export daemon is still running it's killed. Afterwards the
2885
  whole status directory is removed.
2886

2887
  """
2888
  logging.info("Finalizing import/export %s", name)
2889

    
2890
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
2891

    
2892
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
2893

    
2894
  if pid:
2895
    logging.info("Import/export %s is still running with PID %s",
2896
                 name, pid)
2897
    utils.KillProcess(pid, waitpid=False)
2898

    
2899
  shutil.rmtree(status_dir, ignore_errors=True)
2900

    
2901

    
2902
def _FindDisks(nodes_ip, disks):
2903
  """Sets the physical ID on disks and returns the block devices.
2904

2905
  """
2906
  # set the correct physical ID
2907
  my_name = netutils.Hostname.GetSysName()
2908
  for cf in disks:
2909
    cf.SetPhysicalID(my_name, nodes_ip)
2910

    
2911
  bdevs = []
2912

    
2913
  for cf in disks:
2914
    rd = _RecursiveFindBD(cf)
2915
    if rd is None:
2916
      _Fail("Can't find device %s", cf)
2917
    bdevs.append(rd)
2918
  return bdevs
2919

    
2920

    
2921
def DrbdDisconnectNet(nodes_ip, disks):
2922
  """Disconnects the network on a list of drbd devices.
2923

2924
  """
2925
  bdevs = _FindDisks(nodes_ip, disks)
2926

    
2927
  # disconnect disks
2928
  for rd in bdevs:
2929
    try:
2930
      rd.DisconnectNet()
2931
    except errors.BlockDeviceError, err:
2932
      _Fail("Can't change network configuration to standalone mode: %s",
2933
            err, exc=True)
2934

    
2935

    
2936
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
2937
  """Attaches the network on a list of drbd devices.
2938

2939
  """
2940
  bdevs = _FindDisks(nodes_ip, disks)
2941

    
2942
  if multimaster:
2943
    for idx, rd in enumerate(bdevs):
2944
      try:
2945
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
2946
      except EnvironmentError, err:
2947
        _Fail("Can't create symlink: %s", err)
2948
  # reconnect disks, switch to new master configuration and if
2949
  # needed primary mode
2950
  for rd in bdevs:
2951
    try:
2952
      rd.AttachNet(multimaster)
2953
    except errors.BlockDeviceError, err:
2954
      _Fail("Can't change network configuration: %s", err)
2955

    
2956
  # wait until the disks are connected; we need to retry the re-attach
2957
  # if the device becomes standalone, as this might happen if the one
2958
  # node disconnects and reconnects in a different mode before the
2959
  # other node reconnects; in this case, one or both of the nodes will
2960
  # decide it has wrong configuration and switch to standalone
2961

    
2962
  def _Attach():
2963
    all_connected = True
2964

    
2965
    for rd in bdevs:
2966
      stats = rd.GetProcStatus()
2967

    
2968
      all_connected = (all_connected and
2969
                       (stats.is_connected or stats.is_in_resync))
2970

    
2971
      if stats.is_standalone:
2972
        # peer had different config info and this node became
2973
        # standalone, even though this should not happen with the
2974
        # new staged way of changing disk configs
2975
        try:
2976
          rd.AttachNet(multimaster)
2977
        except errors.BlockDeviceError, err:
2978
          _Fail("Can't change network configuration: %s", err)
2979

    
2980
    if not all_connected:
2981
      raise utils.RetryAgain()
2982

    
2983
  try:
2984
    # Start with a delay of 100 miliseconds and go up to 5 seconds
2985
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
2986
  except utils.RetryTimeout:
2987
    _Fail("Timeout in disk reconnecting")
2988

    
2989
  if multimaster:
2990
    # change to primary mode
2991
    for rd in bdevs:
2992
      try:
2993
        rd.Open()
2994
      except errors.BlockDeviceError, err:
2995
        _Fail("Can't change to primary mode: %s", err)
2996

    
2997

    
2998
def DrbdWaitSync(nodes_ip, disks):
2999
  """Wait until DRBDs have synchronized.
3000

3001
  """
3002
  def _helper(rd):
3003
    stats = rd.GetProcStatus()
3004
    if not (stats.is_connected or stats.is_in_resync):
3005
      raise utils.RetryAgain()
3006
    return stats
3007

    
3008
  bdevs = _FindDisks(nodes_ip, disks)
3009

    
3010
  min_resync = 100
3011
  alldone = True
3012
  for rd in bdevs:
3013
    try:
3014
      # poll each second for 15 seconds
3015
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3016
    except utils.RetryTimeout:
3017
      stats = rd.GetProcStatus()
3018
      # last check
3019
      if not (stats.is_connected or stats.is_in_resync):
3020
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3021
    alldone = alldone and (not stats.is_in_resync)
3022
    if stats.sync_percent is not None:
3023
      min_resync = min(min_resync, stats.sync_percent)
3024

    
3025
  return (alldone, min_resync)
3026

    
3027

    
3028
def GetDrbdUsermodeHelper():
3029
  """Returns DRBD usermode helper currently configured.
3030

3031
  """
3032
  try:
3033
    return bdev.BaseDRBD.GetUsermodeHelper()
3034
  except errors.BlockDeviceError, err:
3035
    _Fail(str(err))
3036

    
3037

    
3038
def PowercycleNode(hypervisor_type):
3039
  """Hard-powercycle the node.
3040

3041
  Because we need to return first, and schedule the powercycle in the
3042
  background, we won't be able to report failures nicely.
3043

3044
  """
3045
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3046
  try:
3047
    pid = os.fork()
3048
  except OSError:
3049
    # if we can't fork, we'll pretend that we're in the child process
3050
    pid = 0
3051
  if pid > 0:
3052
    return "Reboot scheduled in 5 seconds"
3053
  # ensure the child is running on ram
3054
  try:
3055
    utils.Mlockall()
3056
  except Exception: # pylint: disable-msg=W0703
3057
    pass
3058
  time.sleep(5)
3059
  hyper.PowercycleNode()
3060

    
3061

    
3062
class HooksRunner(object):
3063
  """Hook runner.
3064

3065
  This class is instantiated on the node side (ganeti-noded) and not
3066
  on the master side.
3067

3068
  """
3069
  def __init__(self, hooks_base_dir=None):
3070
    """Constructor for hooks runner.
3071

3072
    @type hooks_base_dir: str or None
3073
    @param hooks_base_dir: if not None, this overrides the
3074
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
3075

3076
    """
3077
    if hooks_base_dir is None:
3078
      hooks_base_dir = constants.HOOKS_BASE_DIR
3079
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3080
    # constant
3081
    self._BASE_DIR = hooks_base_dir # pylint: disable-msg=C0103
3082

    
3083
  def RunHooks(self, hpath, phase, env):
3084
    """Run the scripts in the hooks directory.
3085

3086
    @type hpath: str
3087
    @param hpath: the path to the hooks directory which
3088
        holds the scripts
3089
    @type phase: str
3090
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
3091
        L{constants.HOOKS_PHASE_POST}
3092
    @type env: dict
3093
    @param env: dictionary with the environment for the hook
3094
    @rtype: list
3095
    @return: list of 3-element tuples:
3096
      - script path
3097
      - script result, either L{constants.HKR_SUCCESS} or
3098
        L{constants.HKR_FAIL}
3099
      - output of the script
3100

3101
    @raise errors.ProgrammerError: for invalid input
3102
        parameters
3103

3104
    """
3105
    if phase == constants.HOOKS_PHASE_PRE:
3106
      suffix = "pre"
3107
    elif phase == constants.HOOKS_PHASE_POST:
3108
      suffix = "post"
3109
    else:
3110
      _Fail("Unknown hooks phase '%s'", phase)
3111

    
3112

    
3113
    subdir = "%s-%s.d" % (hpath, suffix)
3114
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3115

    
3116
    results = []
3117

    
3118
    if not os.path.isdir(dir_name):
3119
      # for non-existing/non-dirs, we simply exit instead of logging a
3120
      # warning at every operation
3121
      return results
3122

    
3123
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3124

    
3125
    for (relname, relstatus, runresult)  in runparts_results:
3126
      if relstatus == constants.RUNPARTS_SKIP:
3127
        rrval = constants.HKR_SKIP
3128
        output = ""
3129
      elif relstatus == constants.RUNPARTS_ERR:
3130
        rrval = constants.HKR_FAIL
3131
        output = "Hook script execution error: %s" % runresult
3132
      elif relstatus == constants.RUNPARTS_RUN:
3133
        if runresult.failed:
3134
          rrval = constants.HKR_FAIL
3135
        else:
3136
          rrval = constants.HKR_SUCCESS
3137
        output = utils.SafeEncode(runresult.output.strip())
3138
      results.append(("%s/%s" % (subdir, relname), rrval, output))
3139

    
3140
    return results
3141

    
3142

    
3143
class IAllocatorRunner(object):
3144
  """IAllocator runner.
3145

3146
  This class is instantiated on the node side (ganeti-noded) and not on
3147
  the master side.
3148

3149
  """
3150
  @staticmethod
3151
  def Run(name, idata):
3152
    """Run an iallocator script.
3153

3154
    @type name: str
3155
    @param name: the iallocator script name
3156
    @type idata: str
3157
    @param idata: the allocator input data
3158

3159
    @rtype: tuple
3160
    @return: two element tuple of:
3161
       - status
3162
       - either error message or stdout of allocator (for success)
3163

3164
    """
3165
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
3166
                                  os.path.isfile)
3167
    if alloc_script is None:
3168
      _Fail("iallocator module '%s' not found in the search path", name)
3169

    
3170
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
3171
    try:
3172
      os.write(fd, idata)
3173
      os.close(fd)
3174
      result = utils.RunCmd([alloc_script, fin_name])
3175
      if result.failed:
3176
        _Fail("iallocator module '%s' failed: %s, output '%s'",
3177
              name, result.fail_reason, result.output)
3178
    finally:
3179
      os.unlink(fin_name)
3180

    
3181
    return result.stdout
3182

    
3183

    
3184
class DevCacheManager(object):
3185
  """Simple class for managing a cache of block device information.
3186

3187
  """
3188
  _DEV_PREFIX = "/dev/"
3189
  _ROOT_DIR = constants.BDEV_CACHE_DIR
3190

    
3191
  @classmethod
3192
  def _ConvertPath(cls, dev_path):
3193
    """Converts a /dev/name path to the cache file name.
3194

3195
    This replaces slashes with underscores and strips the /dev
3196
    prefix. It then returns the full path to the cache file.
3197

3198
    @type dev_path: str
3199
    @param dev_path: the C{/dev/} path name
3200
    @rtype: str
3201
    @return: the converted path name
3202

3203
    """
3204
    if dev_path.startswith(cls._DEV_PREFIX):
3205
      dev_path = dev_path[len(cls._DEV_PREFIX):]
3206
    dev_path = dev_path.replace("/", "_")
3207
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
3208
    return fpath
3209

    
3210
  @classmethod
3211
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
3212
    """Updates the cache information for a given device.
3213

3214
    @type dev_path: str
3215
    @param dev_path: the pathname of the device
3216
    @type owner: str
3217
    @param owner: the owner (instance name) of the device
3218
    @type on_primary: bool
3219
    @param on_primary: whether this is the primary
3220
        node nor not
3221
    @type iv_name: str
3222
    @param iv_name: the instance-visible name of the
3223
        device, as in objects.Disk.iv_name
3224

3225
    @rtype: None
3226

3227
    """
3228
    if dev_path is None:
3229
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
3230
      return
3231
    fpath = cls._ConvertPath(dev_path)
3232
    if on_primary:
3233
      state = "primary"
3234
    else:
3235
      state = "secondary"
3236
    if iv_name is None:
3237
      iv_name = "not_visible"
3238
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
3239
    try:
3240
      utils.WriteFile(fpath, data=fdata)
3241
    except EnvironmentError, err:
3242
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
3243

    
3244
  @classmethod
3245
  def RemoveCache(cls, dev_path):
3246
    """Remove data for a dev_path.
3247

3248
    This is just a wrapper over L{utils.RemoveFile} with a converted
3249
    path name and logging.
3250

3251
    @type dev_path: str
3252
    @param dev_path: the pathname of the device
3253

3254
    @rtype: None
3255

3256
    """
3257
    if dev_path is None:
3258
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
3259
      return
3260
    fpath = cls._ConvertPath(dev_path)
3261
    try:
3262
      utils.RemoveFile(fpath)
3263
    except EnvironmentError, err:
3264
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)