Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 20d38e8a

History | View | Annotate | Download (108 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011 Google Inc.
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful, but
12
# WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
# General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19
# 02110-1301, USA.
20

    
21

    
22
"""Functions used by the node daemon
23

24
@var _ALLOWED_UPLOAD_FILES: denotes which files are accepted in
25
     the L{UploadFile} function
26
@var _ALLOWED_CLEAN_DIRS: denotes which directories are accepted
27
     in the L{_CleanDirectory} function
28

29
"""
30

    
31
# pylint: disable=E1103
32

    
33
# E1103: %s %r has no %r member (but some types could not be
34
# inferred), because the _TryOSFromDisk returns either (True, os_obj)
35
# or (False, "string") which confuses pylint
36

    
37

    
38
import os
39
import os.path
40
import shutil
41
import time
42
import stat
43
import errno
44
import re
45
import random
46
import logging
47
import tempfile
48
import zlib
49
import base64
50
import signal
51

    
52
from ganeti import errors
53
from ganeti import utils
54
from ganeti import ssh
55
from ganeti import hypervisor
56
from ganeti import constants
57
from ganeti import bdev
58
from ganeti import objects
59
from ganeti import ssconf
60
from ganeti import serializer
61
from ganeti import netutils
62
from ganeti import runtime
63
from ganeti import mcpu
64

    
65

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

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

    
83

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

87
  Its argument is the error message.
88

89
  """
90

    
91

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

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

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

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

    
114

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

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

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

    
124

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

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

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

    
137

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

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

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

    
157

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

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

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

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

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

    
187

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

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

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

    
205
  for hv_name in constants.HYPER_TYPES:
206
    hv_class = hypervisor.GetHypervisorClass(hv_name)
207
    allowed_files.update(hv_class.GetAncillaryFiles()[0])
208

    
209
  return frozenset(allowed_files)
210

    
211

    
212
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
213

    
214

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

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

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

    
225

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

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

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

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

    
247

    
248
def RunLocalHooks(hook_opcode, hooks_path, env_builder_fn):
249
  """Decorator that runs hooks before and after the decorated function.
250

251
  @type hook_opcode: string
252
  @param hook_opcode: opcode of the hook
253
  @type hooks_path: string
254
  @param hooks_path: path of the hooks
255
  @type env_builder_fn: function
256
  @param env_builder_fn: function that returns a dictionary containing the
257
    environment variables for the hooks.
258
  @raise RPCFail: in case of pre-hook failure
259

260
  """
261
  def decorator(fn):
262
    def wrapper(*args, **kwargs):
263
      _, myself = ssconf.GetMasterAndMyself()
264
      nodes = ([myself], [myself])  # these hooks run locally
265

    
266
      cfg = _GetConfig()
267
      hr = HooksRunner()
268
      hm = mcpu.HooksMaster(hook_opcode, hooks_path, nodes, hr.RunLocalHooks,
269
                            None, env_builder_fn, logging.warning,
270
                            cfg.GetClusterName(), cfg.GetMasterNode())
271

    
272
      hm.RunPhase(constants.HOOKS_PHASE_PRE)
273
      result = fn(*args, **kwargs)
274
      hm.RunPhase(constants.HOOKS_PHASE_POST)
275

    
276
      return result
277
    return wrapper
278
  return decorator
279

    
280

    
281
def ActivateMasterIp():
282
  """Activate the IP address of the master daemon.
283

284
  """
285
  # GetMasterInfo will raise an exception if not able to return data
286
  master_netdev, master_ip, _, family = GetMasterInfo()
287

    
288
  err_msg = None
289
  if netutils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
290
    if netutils.IPAddress.Own(master_ip):
291
      # we already have the ip:
292
      logging.debug("Master IP already configured, doing nothing")
293
    else:
294
      err_msg = "Someone else has the master ip, not activating"
295
      logging.error(err_msg)
296
  else:
297
    ipcls = netutils.IP4Address
298
    if family == netutils.IP6Address.family:
299
      ipcls = netutils.IP6Address
300

    
301
    result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
302
                           "%s/%d" % (master_ip, ipcls.iplen),
303
                           "dev", master_netdev, "label",
304
                           "%s:0" % master_netdev])
305
    if result.failed:
306
      err_msg = "Can't activate master IP: %s" % result.output
307
      logging.error(err_msg)
308

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

    
320
  if err_msg:
321
    _Fail(err_msg)
322

    
323

    
324
def StartMasterDaemons(no_voting):
325
  """Activate local node as master node.
326

327
  The function will start the master daemons (ganeti-masterd and ganeti-rapi).
328

329
  @type no_voting: boolean
330
  @param no_voting: whether to start ganeti-masterd without a node vote
331
      but still non-interactively
332
  @rtype: None
333

334
  """
335

    
336
  if no_voting:
337
    masterd_args = "--no-voting --yes-do-it"
338
  else:
339
    masterd_args = ""
340

    
341
  env = {
342
    "EXTRA_MASTERD_ARGS": masterd_args,
343
    }
344

    
345
  result = utils.RunCmd([constants.DAEMON_UTIL, "start-master"], env=env)
346
  if result.failed:
347
    msg = "Can't start Ganeti master: %s" % result.output
348
    logging.error(msg)
349
    _Fail(msg)
350

    
351

    
352
def DeactivateMasterIp():
353
  """Deactivate the master IP on this node.
354

355
  """
356
  # TODO: log and report back to the caller the error failures; we
357
  # need to decide in which case we fail the RPC for this
358

    
359
  # GetMasterInfo will raise an exception if not able to return data
360
  master_netdev, master_ip, _, family = GetMasterInfo()
361

    
362
  ipcls = netutils.IP4Address
363
  if family == netutils.IP6Address.family:
364
    ipcls = netutils.IP6Address
365

    
366
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
367
                         "%s/%d" % (master_ip, ipcls.iplen),
368
                         "dev", master_netdev])
369
  if result.failed:
370
    logging.error("Can't remove the master IP, error: %s", result.output)
371
    # but otherwise ignore the failure
372

    
373

    
374
def StopMasterDaemons():
375
  """Stop the master daemons on this node.
376

377
  Stop the master daemons (ganeti-masterd and ganeti-rapi) on this node.
378

379
  @rtype: None
380

381
  """
382
  # TODO: log and report back to the caller the error failures; we
383
  # need to decide in which case we fail the RPC for this
384

    
385
  result = utils.RunCmd([constants.DAEMON_UTIL, "stop-master"])
386
  if result.failed:
387
    logging.error("Could not stop Ganeti master, command %s had exitcode %s"
388
                  " and error %s",
389
                  result.cmd, result.exit_code, result.output)
390

    
391

    
392
def EtcHostsModify(mode, host, ip):
393
  """Modify a host entry in /etc/hosts.
394

395
  @param mode: The mode to operate. Either add or remove entry
396
  @param host: The host to operate on
397
  @param ip: The ip associated with the entry
398

399
  """
400
  if mode == constants.ETC_HOSTS_ADD:
401
    if not ip:
402
      RPCFail("Mode 'add' needs 'ip' parameter, but parameter not"
403
              " present")
404
    utils.AddHostToEtcHosts(host, ip)
405
  elif mode == constants.ETC_HOSTS_REMOVE:
406
    if ip:
407
      RPCFail("Mode 'remove' does not allow 'ip' parameter, but"
408
              " parameter is present")
409
    utils.RemoveHostFromEtcHosts(host)
410
  else:
411
    RPCFail("Mode not supported")
412

    
413

    
414
def LeaveCluster(modify_ssh_setup):
415
  """Cleans up and remove the current node.
416

417
  This function cleans up and prepares the current node to be removed
418
  from the cluster.
419

420
  If processing is successful, then it raises an
421
  L{errors.QuitGanetiException} which is used as a special case to
422
  shutdown the node daemon.
423

424
  @param modify_ssh_setup: boolean
425

426
  """
427
  _CleanDirectory(constants.DATA_DIR)
428
  _CleanDirectory(constants.CRYPTO_KEYS_DIR)
429
  JobQueuePurge()
430

    
431
  if modify_ssh_setup:
432
    try:
433
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
434

    
435
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
436

    
437
      utils.RemoveFile(priv_key)
438
      utils.RemoveFile(pub_key)
439
    except errors.OpExecError:
440
      logging.exception("Error while processing ssh files")
441

    
442
  try:
443
    utils.RemoveFile(constants.CONFD_HMAC_KEY)
444
    utils.RemoveFile(constants.RAPI_CERT_FILE)
445
    utils.RemoveFile(constants.NODED_CERT_FILE)
446
  except: # pylint: disable=W0702
447
    logging.exception("Error while removing cluster secrets")
448

    
449
  result = utils.RunCmd([constants.DAEMON_UTIL, "stop", constants.CONFD])
450
  if result.failed:
451
    logging.error("Command %s failed with exitcode %s and error %s",
452
                  result.cmd, result.exit_code, result.output)
453

    
454
  # Raise a custom exception (handled in ganeti-noded)
455
  raise errors.QuitGanetiException(True, "Shutdown scheduled")
456

    
457

    
458
def GetNodeInfo(vgname, hypervisor_type):
459
  """Gives back a hash with different information about the node.
460

461
  @type vgname: C{string}
462
  @param vgname: the name of the volume group to ask for disk space information
463
  @type hypervisor_type: C{str}
464
  @param hypervisor_type: the name of the hypervisor to ask for
465
      memory information
466
  @rtype: C{dict}
467
  @return: dictionary with the following keys:
468
      - vg_size is the size of the configured volume group in MiB
469
      - vg_free is the free size of the volume group in MiB
470
      - memory_dom0 is the memory allocated for domain0 in MiB
471
      - memory_free is the currently available (free) ram in MiB
472
      - memory_total is the total number of ram in MiB
473
      - hv_version: the hypervisor version, if available
474

475
  """
476
  outputarray = {}
477

    
478
  if vgname is not None:
479
    vginfo = bdev.LogicalVolume.GetVGInfo([vgname])
480
    vg_free = vg_size = None
481
    if vginfo:
482
      vg_free = int(round(vginfo[0][0], 0))
483
      vg_size = int(round(vginfo[0][1], 0))
484
    outputarray["vg_size"] = vg_size
485
    outputarray["vg_free"] = vg_free
486

    
487
  if hypervisor_type is not None:
488
    hyper = hypervisor.GetHypervisor(hypervisor_type)
489
    hyp_info = hyper.GetNodeInfo()
490
    if hyp_info is not None:
491
      outputarray.update(hyp_info)
492

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

    
495
  return outputarray
496

    
497

    
498
def VerifyNode(what, cluster_name):
499
  """Verify the status of the local node.
500

501
  Based on the input L{what} parameter, various checks are done on the
502
  local node.
503

504
  If the I{filelist} key is present, this list of
505
  files is checksummed and the file/checksum pairs are returned.
506

507
  If the I{nodelist} key is present, we check that we have
508
  connectivity via ssh with the target nodes (and check the hostname
509
  report).
510

511
  If the I{node-net-test} key is present, we check that we have
512
  connectivity to the given nodes via both primary IP and, if
513
  applicable, secondary IPs.
514

515
  @type what: C{dict}
516
  @param what: a dictionary of things to check:
517
      - filelist: list of files for which to compute checksums
518
      - nodelist: list of nodes we should check ssh communication with
519
      - node-net-test: list of nodes we should check node daemon port
520
        connectivity with
521
      - hypervisor: list with hypervisors to run the verify for
522
  @rtype: dict
523
  @return: a dictionary with the same keys as the input dict, and
524
      values representing the result of the checks
525

526
  """
527
  result = {}
528
  my_name = netutils.Hostname.GetSysName()
529
  port = netutils.GetDaemonPort(constants.NODED)
530
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
531

    
532
  if constants.NV_HYPERVISOR in what and vm_capable:
533
    result[constants.NV_HYPERVISOR] = tmp = {}
534
    for hv_name in what[constants.NV_HYPERVISOR]:
535
      try:
536
        val = hypervisor.GetHypervisor(hv_name).Verify()
537
      except errors.HypervisorError, err:
538
        val = "Error while checking hypervisor: %s" % str(err)
539
      tmp[hv_name] = val
540

    
541
  if constants.NV_HVPARAMS in what and vm_capable:
542
    result[constants.NV_HVPARAMS] = tmp = []
543
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
544
      try:
545
        logging.info("Validating hv %s, %s", hv_name, hvparms)
546
        hypervisor.GetHypervisor(hv_name).ValidateParameters(hvparms)
547
      except errors.HypervisorError, err:
548
        tmp.append((source, hv_name, str(err)))
549

    
550
  if constants.NV_FILELIST in what:
551
    result[constants.NV_FILELIST] = utils.FingerprintFiles(
552
      what[constants.NV_FILELIST])
553

    
554
  if constants.NV_NODELIST in what:
555
    (nodes, bynode) = what[constants.NV_NODELIST]
556

    
557
    # Add nodes from other groups (different for each node)
558
    try:
559
      nodes.extend(bynode[my_name])
560
    except KeyError:
561
      pass
562

    
563
    # Use a random order
564
    random.shuffle(nodes)
565

    
566
    # Try to contact all nodes
567
    val = {}
568
    for node in nodes:
569
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
570
      if not success:
571
        val[node] = message
572

    
573
    result[constants.NV_NODELIST] = val
574

    
575
  if constants.NV_NODENETTEST in what:
576
    result[constants.NV_NODENETTEST] = tmp = {}
577
    my_pip = my_sip = None
578
    for name, pip, sip in what[constants.NV_NODENETTEST]:
579
      if name == my_name:
580
        my_pip = pip
581
        my_sip = sip
582
        break
583
    if not my_pip:
584
      tmp[my_name] = ("Can't find my own primary/secondary IP"
585
                      " in the node list")
586
    else:
587
      for name, pip, sip in what[constants.NV_NODENETTEST]:
588
        fail = []
589
        if not netutils.TcpPing(pip, port, source=my_pip):
590
          fail.append("primary")
591
        if sip != pip:
592
          if not netutils.TcpPing(sip, port, source=my_sip):
593
            fail.append("secondary")
594
        if fail:
595
          tmp[name] = ("failure using the %s interface(s)" %
596
                       " and ".join(fail))
597

    
598
  if constants.NV_MASTERIP in what:
599
    # FIXME: add checks on incoming data structures (here and in the
600
    # rest of the function)
601
    master_name, master_ip = what[constants.NV_MASTERIP]
602
    if master_name == my_name:
603
      source = constants.IP4_ADDRESS_LOCALHOST
604
    else:
605
      source = None
606
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
607
                                                  source=source)
608

    
609
  if constants.NV_OOB_PATHS in what:
610
    result[constants.NV_OOB_PATHS] = tmp = []
611
    for path in what[constants.NV_OOB_PATHS]:
612
      try:
613
        st = os.stat(path)
614
      except OSError, err:
615
        tmp.append("error stating out of band helper: %s" % err)
616
      else:
617
        if stat.S_ISREG(st.st_mode):
618
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
619
            tmp.append(None)
620
          else:
621
            tmp.append("out of band helper %s is not executable" % path)
622
        else:
623
          tmp.append("out of band helper %s is not a file" % path)
624

    
625
  if constants.NV_LVLIST in what and vm_capable:
626
    try:
627
      val = GetVolumeList(utils.ListVolumeGroups().keys())
628
    except RPCFail, err:
629
      val = str(err)
630
    result[constants.NV_LVLIST] = val
631

    
632
  if constants.NV_INSTANCELIST in what and vm_capable:
633
    # GetInstanceList can fail
634
    try:
635
      val = GetInstanceList(what[constants.NV_INSTANCELIST])
636
    except RPCFail, err:
637
      val = str(err)
638
    result[constants.NV_INSTANCELIST] = val
639

    
640
  if constants.NV_VGLIST in what and vm_capable:
641
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
642

    
643
  if constants.NV_PVLIST in what and vm_capable:
644
    result[constants.NV_PVLIST] = \
645
      bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
646
                                   filter_allocatable=False)
647

    
648
  if constants.NV_VERSION in what:
649
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
650
                                    constants.RELEASE_VERSION)
651

    
652
  if constants.NV_HVINFO in what and vm_capable:
653
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
654
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
655

    
656
  if constants.NV_DRBDLIST in what and vm_capable:
657
    try:
658
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
659
    except errors.BlockDeviceError, err:
660
      logging.warning("Can't get used minors list", exc_info=True)
661
      used_minors = str(err)
662
    result[constants.NV_DRBDLIST] = used_minors
663

    
664
  if constants.NV_DRBDHELPER in what and vm_capable:
665
    status = True
666
    try:
667
      payload = bdev.BaseDRBD.GetUsermodeHelper()
668
    except errors.BlockDeviceError, err:
669
      logging.error("Can't get DRBD usermode helper: %s", str(err))
670
      status = False
671
      payload = str(err)
672
    result[constants.NV_DRBDHELPER] = (status, payload)
673

    
674
  if constants.NV_NODESETUP in what:
675
    result[constants.NV_NODESETUP] = tmpr = []
676
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
677
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
678
                  " under /sys, missing required directories /sys/block"
679
                  " and /sys/class/net")
680
    if (not os.path.isdir("/proc/sys") or
681
        not os.path.isfile("/proc/sysrq-trigger")):
682
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
683
                  " under /proc, missing required directory /proc/sys and"
684
                  " the file /proc/sysrq-trigger")
685

    
686
  if constants.NV_TIME in what:
687
    result[constants.NV_TIME] = utils.SplitTime(time.time())
688

    
689
  if constants.NV_OSLIST in what and vm_capable:
690
    result[constants.NV_OSLIST] = DiagnoseOS()
691

    
692
  if constants.NV_BRIDGES in what and vm_capable:
693
    result[constants.NV_BRIDGES] = [bridge
694
                                    for bridge in what[constants.NV_BRIDGES]
695
                                    if not utils.BridgeExists(bridge)]
696
  return result
697

    
698

    
699
def GetBlockDevSizes(devices):
700
  """Return the size of the given block devices
701

702
  @type devices: list
703
  @param devices: list of block device nodes to query
704
  @rtype: dict
705
  @return:
706
    dictionary of all block devices under /dev (key). The value is their
707
    size in MiB.
708

709
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
710

711
  """
712
  DEV_PREFIX = "/dev/"
713
  blockdevs = {}
714

    
715
  for devpath in devices:
716
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
717
      continue
718

    
719
    try:
720
      st = os.stat(devpath)
721
    except EnvironmentError, err:
722
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
723
      continue
724

    
725
    if stat.S_ISBLK(st.st_mode):
726
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
727
      if result.failed:
728
        # We don't want to fail, just do not list this device as available
729
        logging.warning("Cannot get size for block device %s", devpath)
730
        continue
731

    
732
      size = int(result.stdout) / (1024 * 1024)
733
      blockdevs[devpath] = size
734
  return blockdevs
735

    
736

    
737
def GetVolumeList(vg_names):
738
  """Compute list of logical volumes and their size.
739

740
  @type vg_names: list
741
  @param vg_names: the volume groups whose LVs we should list, or
742
      empty for all volume groups
743
  @rtype: dict
744
  @return:
745
      dictionary of all partions (key) with value being a tuple of
746
      their size (in MiB), inactive and online status::
747

748
        {'xenvg/test1': ('20.06', True, True)}
749

750
      in case of errors, a string is returned with the error
751
      details.
752

753
  """
754
  lvs = {}
755
  sep = "|"
756
  if not vg_names:
757
    vg_names = []
758
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
759
                         "--separator=%s" % sep,
760
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
761
  if result.failed:
762
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
763

    
764
  for line in result.stdout.splitlines():
765
    line = line.strip()
766
    match = _LVSLINE_REGEX.match(line)
767
    if not match:
768
      logging.error("Invalid line returned from lvs output: '%s'", line)
769
      continue
770
    vg_name, name, size, attr = match.groups()
771
    inactive = attr[4] == "-"
772
    online = attr[5] == "o"
773
    virtual = attr[0] == "v"
774
    if virtual:
775
      # we don't want to report such volumes as existing, since they
776
      # don't really hold data
777
      continue
778
    lvs[vg_name + "/" + name] = (size, inactive, online)
779

    
780
  return lvs
781

    
782

    
783
def ListVolumeGroups():
784
  """List the volume groups and their size.
785

786
  @rtype: dict
787
  @return: dictionary with keys volume name and values the
788
      size of the volume
789

790
  """
791
  return utils.ListVolumeGroups()
792

    
793

    
794
def NodeVolumes():
795
  """List all volumes on this node.
796

797
  @rtype: list
798
  @return:
799
    A list of dictionaries, each having four keys:
800
      - name: the logical volume name,
801
      - size: the size of the logical volume
802
      - dev: the physical device on which the LV lives
803
      - vg: the volume group to which it belongs
804

805
    In case of errors, we return an empty list and log the
806
    error.
807

808
    Note that since a logical volume can live on multiple physical
809
    volumes, the resulting list might include a logical volume
810
    multiple times.
811

812
  """
813
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
814
                         "--separator=|",
815
                         "--options=lv_name,lv_size,devices,vg_name"])
816
  if result.failed:
817
    _Fail("Failed to list logical volumes, lvs output: %s",
818
          result.output)
819

    
820
  def parse_dev(dev):
821
    return dev.split("(")[0]
822

    
823
  def handle_dev(dev):
824
    return [parse_dev(x) for x in dev.split(",")]
825

    
826
  def map_line(line):
827
    line = [v.strip() for v in line]
828
    return [{"name": line[0], "size": line[1],
829
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
830

    
831
  all_devs = []
832
  for line in result.stdout.splitlines():
833
    if line.count("|") >= 3:
834
      all_devs.extend(map_line(line.split("|")))
835
    else:
836
      logging.warning("Strange line in the output from lvs: '%s'", line)
837
  return all_devs
838

    
839

    
840
def BridgesExist(bridges_list):
841
  """Check if a list of bridges exist on the current node.
842

843
  @rtype: boolean
844
  @return: C{True} if all of them exist, C{False} otherwise
845

846
  """
847
  missing = []
848
  for bridge in bridges_list:
849
    if not utils.BridgeExists(bridge):
850
      missing.append(bridge)
851

    
852
  if missing:
853
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
854

    
855

    
856
def GetInstanceList(hypervisor_list):
857
  """Provides a list of instances.
858

859
  @type hypervisor_list: list
860
  @param hypervisor_list: the list of hypervisors to query information
861

862
  @rtype: list
863
  @return: a list of all running instances on the current node
864
    - instance1.example.com
865
    - instance2.example.com
866

867
  """
868
  results = []
869
  for hname in hypervisor_list:
870
    try:
871
      names = hypervisor.GetHypervisor(hname).ListInstances()
872
      results.extend(names)
873
    except errors.HypervisorError, err:
874
      _Fail("Error enumerating instances (hypervisor %s): %s",
875
            hname, err, exc=True)
876

    
877
  return results
878

    
879

    
880
def GetInstanceInfo(instance, hname):
881
  """Gives back the information about an instance as a dictionary.
882

883
  @type instance: string
884
  @param instance: the instance name
885
  @type hname: string
886
  @param hname: the hypervisor type of the instance
887

888
  @rtype: dict
889
  @return: dictionary with the following keys:
890
      - memory: memory size of instance (int)
891
      - state: xen state of instance (string)
892
      - time: cpu time of instance (float)
893

894
  """
895
  output = {}
896

    
897
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
898
  if iinfo is not None:
899
    output["memory"] = iinfo[2]
900
    output["state"] = iinfo[4]
901
    output["time"] = iinfo[5]
902

    
903
  return output
904

    
905

    
906
def GetInstanceMigratable(instance):
907
  """Gives whether an instance can be migrated.
908

909
  @type instance: L{objects.Instance}
910
  @param instance: object representing the instance to be checked.
911

912
  @rtype: tuple
913
  @return: tuple of (result, description) where:
914
      - result: whether the instance can be migrated or not
915
      - description: a description of the issue, if relevant
916

917
  """
918
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
919
  iname = instance.name
920
  if iname not in hyper.ListInstances():
921
    _Fail("Instance %s is not running", iname)
922

    
923
  for idx in range(len(instance.disks)):
924
    link_name = _GetBlockDevSymlinkPath(iname, idx)
925
    if not os.path.islink(link_name):
926
      logging.warning("Instance %s is missing symlink %s for disk %d",
927
                      iname, link_name, idx)
928

    
929

    
930
def GetAllInstancesInfo(hypervisor_list):
931
  """Gather data about all instances.
932

933
  This is the equivalent of L{GetInstanceInfo}, except that it
934
  computes data for all instances at once, thus being faster if one
935
  needs data about more than one instance.
936

937
  @type hypervisor_list: list
938
  @param hypervisor_list: list of hypervisors to query for instance data
939

940
  @rtype: dict
941
  @return: dictionary of instance: data, with data having the following keys:
942
      - memory: memory size of instance (int)
943
      - state: xen state of instance (string)
944
      - time: cpu time of instance (float)
945
      - vcpus: the number of vcpus
946

947
  """
948
  output = {}
949

    
950
  for hname in hypervisor_list:
951
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
952
    if iinfo:
953
      for name, _, memory, vcpus, state, times in iinfo:
954
        value = {
955
          "memory": memory,
956
          "vcpus": vcpus,
957
          "state": state,
958
          "time": times,
959
          }
960
        if name in output:
961
          # we only check static parameters, like memory and vcpus,
962
          # and not state and time which can change between the
963
          # invocations of the different hypervisors
964
          for key in "memory", "vcpus":
965
            if value[key] != output[name][key]:
966
              _Fail("Instance %s is running twice"
967
                    " with different parameters", name)
968
        output[name] = value
969

    
970
  return output
971

    
972

    
973
def _InstanceLogName(kind, os_name, instance, component):
974
  """Compute the OS log filename for a given instance and operation.
975

976
  The instance name and os name are passed in as strings since not all
977
  operations have these as part of an instance object.
978

979
  @type kind: string
980
  @param kind: the operation type (e.g. add, import, etc.)
981
  @type os_name: string
982
  @param os_name: the os name
983
  @type instance: string
984
  @param instance: the name of the instance being imported/added/etc.
985
  @type component: string or None
986
  @param component: the name of the component of the instance being
987
      transferred
988

989
  """
990
  # TODO: Use tempfile.mkstemp to create unique filename
991
  if component:
992
    assert "/" not in component
993
    c_msg = "-%s" % component
994
  else:
995
    c_msg = ""
996
  base = ("%s-%s-%s%s-%s.log" %
997
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
998
  return utils.PathJoin(constants.LOG_OS_DIR, base)
999

    
1000

    
1001
def InstanceOsAdd(instance, reinstall, debug):
1002
  """Add an OS to an instance.
1003

1004
  @type instance: L{objects.Instance}
1005
  @param instance: Instance whose OS is to be installed
1006
  @type reinstall: boolean
1007
  @param reinstall: whether this is an instance reinstall
1008
  @type debug: integer
1009
  @param debug: debug level, passed to the OS scripts
1010
  @rtype: None
1011

1012
  """
1013
  inst_os = OSFromDisk(instance.os)
1014

    
1015
  create_env = OSEnvironment(instance, inst_os, debug)
1016
  if reinstall:
1017
    create_env["INSTANCE_REINSTALL"] = "1"
1018

    
1019
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1020

    
1021
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1022
                        cwd=inst_os.path, output=logfile, reset_env=True)
1023
  if result.failed:
1024
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1025
                  " output: %s", result.cmd, result.fail_reason, logfile,
1026
                  result.output)
1027
    lines = [utils.SafeEncode(val)
1028
             for val in utils.TailFile(logfile, lines=20)]
1029
    _Fail("OS create script failed (%s), last lines in the"
1030
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1031

    
1032

    
1033
def RunRenameInstance(instance, old_name, debug):
1034
  """Run the OS rename script for an instance.
1035

1036
  @type instance: L{objects.Instance}
1037
  @param instance: Instance whose OS is to be installed
1038
  @type old_name: string
1039
  @param old_name: previous instance name
1040
  @type debug: integer
1041
  @param debug: debug level, passed to the OS scripts
1042
  @rtype: boolean
1043
  @return: the success of the operation
1044

1045
  """
1046
  inst_os = OSFromDisk(instance.os)
1047

    
1048
  rename_env = OSEnvironment(instance, inst_os, debug)
1049
  rename_env["OLD_INSTANCE_NAME"] = old_name
1050

    
1051
  logfile = _InstanceLogName("rename", instance.os,
1052
                             "%s-%s" % (old_name, instance.name), None)
1053

    
1054
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1055
                        cwd=inst_os.path, output=logfile, reset_env=True)
1056

    
1057
  if result.failed:
1058
    logging.error("os create command '%s' returned error: %s output: %s",
1059
                  result.cmd, result.fail_reason, result.output)
1060
    lines = [utils.SafeEncode(val)
1061
             for val in utils.TailFile(logfile, lines=20)]
1062
    _Fail("OS rename script failed (%s), last lines in the"
1063
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1064

    
1065

    
1066
def _GetBlockDevSymlinkPath(instance_name, idx):
1067
  return utils.PathJoin(constants.DISK_LINKS_DIR, "%s%s%d" %
1068
                        (instance_name, constants.DISK_SEPARATOR, idx))
1069

    
1070

    
1071
def _SymlinkBlockDev(instance_name, device_path, idx):
1072
  """Set up symlinks to a instance's block device.
1073

1074
  This is an auxiliary function run when an instance is start (on the primary
1075
  node) or when an instance is migrated (on the target node).
1076

1077

1078
  @param instance_name: the name of the target instance
1079
  @param device_path: path of the physical block device, on the node
1080
  @param idx: the disk index
1081
  @return: absolute path to the disk's symlink
1082

1083
  """
1084
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1085
  try:
1086
    os.symlink(device_path, link_name)
1087
  except OSError, err:
1088
    if err.errno == errno.EEXIST:
1089
      if (not os.path.islink(link_name) or
1090
          os.readlink(link_name) != device_path):
1091
        os.remove(link_name)
1092
        os.symlink(device_path, link_name)
1093
    else:
1094
      raise
1095

    
1096
  return link_name
1097

    
1098

    
1099
def _RemoveBlockDevLinks(instance_name, disks):
1100
  """Remove the block device symlinks belonging to the given instance.
1101

1102
  """
1103
  for idx, _ in enumerate(disks):
1104
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1105
    if os.path.islink(link_name):
1106
      try:
1107
        os.remove(link_name)
1108
      except OSError:
1109
        logging.exception("Can't remove symlink '%s'", link_name)
1110

    
1111

    
1112
def _GatherAndLinkBlockDevs(instance):
1113
  """Set up an instance's block device(s).
1114

1115
  This is run on the primary node at instance startup. The block
1116
  devices must be already assembled.
1117

1118
  @type instance: L{objects.Instance}
1119
  @param instance: the instance whose disks we shoul assemble
1120
  @rtype: list
1121
  @return: list of (disk_object, device_path)
1122

1123
  """
1124
  block_devices = []
1125
  for idx, disk in enumerate(instance.disks):
1126
    device = _RecursiveFindBD(disk)
1127
    if device is None:
1128
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1129
                                    str(disk))
1130
    device.Open()
1131
    try:
1132
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1133
    except OSError, e:
1134
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1135
                                    e.strerror)
1136

    
1137
    block_devices.append((disk, link_name))
1138

    
1139
  return block_devices
1140

    
1141

    
1142
def StartInstance(instance, startup_paused):
1143
  """Start an instance.
1144

1145
  @type instance: L{objects.Instance}
1146
  @param instance: the instance object
1147
  @type startup_paused: bool
1148
  @param instance: pause instance at startup?
1149
  @rtype: None
1150

1151
  """
1152
  running_instances = GetInstanceList([instance.hypervisor])
1153

    
1154
  if instance.name in running_instances:
1155
    logging.info("Instance %s already running, not starting", instance.name)
1156
    return
1157

    
1158
  try:
1159
    block_devices = _GatherAndLinkBlockDevs(instance)
1160
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1161
    hyper.StartInstance(instance, block_devices, startup_paused)
1162
  except errors.BlockDeviceError, err:
1163
    _Fail("Block device error: %s", err, exc=True)
1164
  except errors.HypervisorError, err:
1165
    _RemoveBlockDevLinks(instance.name, instance.disks)
1166
    _Fail("Hypervisor error: %s", err, exc=True)
1167

    
1168

    
1169
def InstanceShutdown(instance, timeout):
1170
  """Shut an instance down.
1171

1172
  @note: this functions uses polling with a hardcoded timeout.
1173

1174
  @type instance: L{objects.Instance}
1175
  @param instance: the instance object
1176
  @type timeout: integer
1177
  @param timeout: maximum timeout for soft shutdown
1178
  @rtype: None
1179

1180
  """
1181
  hv_name = instance.hypervisor
1182
  hyper = hypervisor.GetHypervisor(hv_name)
1183
  iname = instance.name
1184

    
1185
  if instance.name not in hyper.ListInstances():
1186
    logging.info("Instance %s not running, doing nothing", iname)
1187
    return
1188

    
1189
  class _TryShutdown:
1190
    def __init__(self):
1191
      self.tried_once = False
1192

    
1193
    def __call__(self):
1194
      if iname not in hyper.ListInstances():
1195
        return
1196

    
1197
      try:
1198
        hyper.StopInstance(instance, retry=self.tried_once)
1199
      except errors.HypervisorError, err:
1200
        if iname not in hyper.ListInstances():
1201
          # if the instance is no longer existing, consider this a
1202
          # success and go to cleanup
1203
          return
1204

    
1205
        _Fail("Failed to stop instance %s: %s", iname, err)
1206

    
1207
      self.tried_once = True
1208

    
1209
      raise utils.RetryAgain()
1210

    
1211
  try:
1212
    utils.Retry(_TryShutdown(), 5, timeout)
1213
  except utils.RetryTimeout:
1214
    # the shutdown did not succeed
1215
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1216

    
1217
    try:
1218
      hyper.StopInstance(instance, force=True)
1219
    except errors.HypervisorError, err:
1220
      if iname in hyper.ListInstances():
1221
        # only raise an error if the instance still exists, otherwise
1222
        # the error could simply be "instance ... unknown"!
1223
        _Fail("Failed to force stop instance %s: %s", iname, err)
1224

    
1225
    time.sleep(1)
1226

    
1227
    if iname in hyper.ListInstances():
1228
      _Fail("Could not shutdown instance %s even by destroy", iname)
1229

    
1230
  try:
1231
    hyper.CleanupInstance(instance.name)
1232
  except errors.HypervisorError, err:
1233
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1234

    
1235
  _RemoveBlockDevLinks(iname, instance.disks)
1236

    
1237

    
1238
def InstanceReboot(instance, reboot_type, shutdown_timeout):
1239
  """Reboot an instance.
1240

1241
  @type instance: L{objects.Instance}
1242
  @param instance: the instance object to reboot
1243
  @type reboot_type: str
1244
  @param reboot_type: the type of reboot, one the following
1245
    constants:
1246
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1247
        instance OS, do not recreate the VM
1248
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1249
        restart the VM (at the hypervisor level)
1250
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1251
        not accepted here, since that mode is handled differently, in
1252
        cmdlib, and translates into full stop and start of the
1253
        instance (instead of a call_instance_reboot RPC)
1254
  @type shutdown_timeout: integer
1255
  @param shutdown_timeout: maximum timeout for soft shutdown
1256
  @rtype: None
1257

1258
  """
1259
  running_instances = GetInstanceList([instance.hypervisor])
1260

    
1261
  if instance.name not in running_instances:
1262
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1263

    
1264
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1265
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1266
    try:
1267
      hyper.RebootInstance(instance)
1268
    except errors.HypervisorError, err:
1269
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1270
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1271
    try:
1272
      InstanceShutdown(instance, shutdown_timeout)
1273
      return StartInstance(instance, False)
1274
    except errors.HypervisorError, err:
1275
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1276
  else:
1277
    _Fail("Invalid reboot_type received: %s", reboot_type)
1278

    
1279

    
1280
def MigrationInfo(instance):
1281
  """Gather information about an instance to be migrated.
1282

1283
  @type instance: L{objects.Instance}
1284
  @param instance: the instance definition
1285

1286
  """
1287
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1288
  try:
1289
    info = hyper.MigrationInfo(instance)
1290
  except errors.HypervisorError, err:
1291
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1292
  return info
1293

    
1294

    
1295
def AcceptInstance(instance, info, target):
1296
  """Prepare the node to accept an instance.
1297

1298
  @type instance: L{objects.Instance}
1299
  @param instance: the instance definition
1300
  @type info: string/data (opaque)
1301
  @param info: migration information, from the source node
1302
  @type target: string
1303
  @param target: target host (usually ip), on this node
1304

1305
  """
1306
  # TODO: why is this required only for DTS_EXT_MIRROR?
1307
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1308
    # Create the symlinks, as the disks are not active
1309
    # in any way
1310
    try:
1311
      _GatherAndLinkBlockDevs(instance)
1312
    except errors.BlockDeviceError, err:
1313
      _Fail("Block device error: %s", err, exc=True)
1314

    
1315
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1316
  try:
1317
    hyper.AcceptInstance(instance, info, target)
1318
  except errors.HypervisorError, err:
1319
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1320
      _RemoveBlockDevLinks(instance.name, instance.disks)
1321
    _Fail("Failed to accept instance: %s", err, exc=True)
1322

    
1323

    
1324
def FinalizeMigration(instance, info, success):
1325
  """Finalize any preparation to accept an instance.
1326

1327
  @type instance: L{objects.Instance}
1328
  @param instance: the instance definition
1329
  @type info: string/data (opaque)
1330
  @param info: migration information, from the source node
1331
  @type success: boolean
1332
  @param success: whether the migration was a success or a failure
1333

1334
  """
1335
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1336
  try:
1337
    hyper.FinalizeMigration(instance, info, success)
1338
  except errors.HypervisorError, err:
1339
    _Fail("Failed to finalize migration: %s", err, exc=True)
1340

    
1341

    
1342
def MigrateInstance(instance, target, live):
1343
  """Migrates an instance to another node.
1344

1345
  @type instance: L{objects.Instance}
1346
  @param instance: the instance definition
1347
  @type target: string
1348
  @param target: the target node name
1349
  @type live: boolean
1350
  @param live: whether the migration should be done live or not (the
1351
      interpretation of this parameter is left to the hypervisor)
1352
  @rtype: tuple
1353
  @return: a tuple of (success, msg) where:
1354
      - succes is a boolean denoting the success/failure of the operation
1355
      - msg is a string with details in case of failure
1356

1357
  """
1358
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1359

    
1360
  try:
1361
    hyper.MigrateInstance(instance, target, live)
1362
  except errors.HypervisorError, err:
1363
    _Fail("Failed to migrate instance: %s", err, exc=True)
1364

    
1365

    
1366
def BlockdevCreate(disk, size, owner, on_primary, info):
1367
  """Creates a block device for an instance.
1368

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

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

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

    
1406
  try:
1407
    device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
1408
  except errors.BlockDeviceError, err:
1409
    _Fail("Can't create block device: %s", err)
1410

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

    
1425
  device.SetInfo(info)
1426

    
1427
  return device.unique_id
1428

    
1429

    
1430
def _WipeDevice(path, offset, size):
1431
  """This function actually wipes the device.
1432

1433
  @param path: The path to the device to wipe
1434
  @param offset: The offset in MiB in the file
1435
  @param size: The size in MiB to write
1436

1437
  """
1438
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1439
         "bs=%d" % constants.WIPE_BLOCK_SIZE, "oflag=direct", "of=%s" % path,
1440
         "count=%d" % size]
1441
  result = utils.RunCmd(cmd)
1442

    
1443
  if result.failed:
1444
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1445
          result.fail_reason, result.output)
1446

    
1447

    
1448
def BlockdevWipe(disk, offset, size):
1449
  """Wipes a block device.
1450

1451
  @type disk: L{objects.Disk}
1452
  @param disk: the disk object we want to wipe
1453
  @type offset: int
1454
  @param offset: The offset in MiB in the file
1455
  @type size: int
1456
  @param size: The size in MiB to write
1457

1458
  """
1459
  try:
1460
    rdev = _RecursiveFindBD(disk)
1461
  except errors.BlockDeviceError:
1462
    rdev = None
1463

    
1464
  if not rdev:
1465
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1466

    
1467
  # Do cross verify some of the parameters
1468
  if offset > rdev.size:
1469
    _Fail("Offset is bigger than device size")
1470
  if (offset + size) > rdev.size:
1471
    _Fail("The provided offset and size to wipe is bigger than device size")
1472

    
1473
  _WipeDevice(rdev.dev_path, offset, size)
1474

    
1475

    
1476
def BlockdevPauseResumeSync(disks, pause):
1477
  """Pause or resume the sync of the block device.
1478

1479
  @type disks: list of L{objects.Disk}
1480
  @param disks: the disks object we want to pause/resume
1481
  @type pause: bool
1482
  @param pause: Wheater to pause or resume
1483

1484
  """
1485
  success = []
1486
  for disk in disks:
1487
    try:
1488
      rdev = _RecursiveFindBD(disk)
1489
    except errors.BlockDeviceError:
1490
      rdev = None
1491

    
1492
    if not rdev:
1493
      success.append((False, ("Cannot change sync for device %s:"
1494
                              " device not found" % disk.iv_name)))
1495
      continue
1496

    
1497
    result = rdev.PauseResumeSync(pause)
1498

    
1499
    if result:
1500
      success.append((result, None))
1501
    else:
1502
      if pause:
1503
        msg = "Pause"
1504
      else:
1505
        msg = "Resume"
1506
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1507

    
1508
  return success
1509

    
1510

    
1511
def BlockdevRemove(disk):
1512
  """Remove a block device.
1513

1514
  @note: This is intended to be called recursively.
1515

1516
  @type disk: L{objects.Disk}
1517
  @param disk: the disk object we should remove
1518
  @rtype: boolean
1519
  @return: the success of the operation
1520

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

    
1538
  if disk.children:
1539
    for child in disk.children:
1540
      try:
1541
        BlockdevRemove(child)
1542
      except RPCFail, err:
1543
        msgs.append(str(err))
1544

    
1545
  if msgs:
1546
    _Fail("; ".join(msgs))
1547

    
1548

    
1549
def _RecursiveAssembleBD(disk, owner, as_primary):
1550
  """Activate a block device for an instance.
1551

1552
  This is run on the primary and secondary nodes for an instance.
1553

1554
  @note: this function is called recursively.
1555

1556
  @type disk: L{objects.Disk}
1557
  @param disk: the disk we try to assemble
1558
  @type owner: str
1559
  @param owner: the name of the instance which owns the disk
1560
  @type as_primary: boolean
1561
  @param as_primary: if we should make the block device
1562
      read/write
1563

1564
  @return: the assembled device or None (in case no device
1565
      was assembled)
1566
  @raise errors.BlockDeviceError: in case there is an error
1567
      during the activation of the children or the device
1568
      itself
1569

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

    
1589
  if as_primary or disk.AssembleOnSecondary():
1590
    r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
1591
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1592
    result = r_dev
1593
    if as_primary or disk.OpenOnSecondary():
1594
      r_dev.Open()
1595
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1596
                                as_primary, disk.iv_name)
1597

    
1598
  else:
1599
    result = True
1600
  return result
1601

    
1602

    
1603
def BlockdevAssemble(disk, owner, as_primary, idx):
1604
  """Activate a block device for an instance.
1605

1606
  This is a wrapper over _RecursiveAssembleBD.
1607

1608
  @rtype: str or boolean
1609
  @return: a C{/dev/...} path for primary nodes, and
1610
      C{True} for secondary nodes
1611

1612
  """
1613
  try:
1614
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1615
    if isinstance(result, bdev.BlockDev):
1616
      # pylint: disable=E1103
1617
      result = result.dev_path
1618
      if as_primary:
1619
        _SymlinkBlockDev(owner, result, idx)
1620
  except errors.BlockDeviceError, err:
1621
    _Fail("Error while assembling disk: %s", err, exc=True)
1622
  except OSError, err:
1623
    _Fail("Error while symlinking disk: %s", err, exc=True)
1624

    
1625
  return result
1626

    
1627

    
1628
def BlockdevShutdown(disk):
1629
  """Shut down a block device.
1630

1631
  First, if the device is assembled (Attach() is successful), then
1632
  the device is shutdown. Then the children of the device are
1633
  shutdown.
1634

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

1639
  @type disk: L{objects.Disk}
1640
  @param disk: the description of the disk we should
1641
      shutdown
1642
  @rtype: None
1643

1644
  """
1645
  msgs = []
1646
  r_dev = _RecursiveFindBD(disk)
1647
  if r_dev is not None:
1648
    r_path = r_dev.dev_path
1649
    try:
1650
      r_dev.Shutdown()
1651
      DevCacheManager.RemoveCache(r_path)
1652
    except errors.BlockDeviceError, err:
1653
      msgs.append(str(err))
1654

    
1655
  if disk.children:
1656
    for child in disk.children:
1657
      try:
1658
        BlockdevShutdown(child)
1659
      except RPCFail, err:
1660
        msgs.append(str(err))
1661

    
1662
  if msgs:
1663
    _Fail("; ".join(msgs))
1664

    
1665

    
1666
def BlockdevAddchildren(parent_cdev, new_cdevs):
1667
  """Extend a mirrored block device.
1668

1669
  @type parent_cdev: L{objects.Disk}
1670
  @param parent_cdev: the disk to which we should add children
1671
  @type new_cdevs: list of L{objects.Disk}
1672
  @param new_cdevs: the list of children which we should add
1673
  @rtype: None
1674

1675
  """
1676
  parent_bdev = _RecursiveFindBD(parent_cdev)
1677
  if parent_bdev is None:
1678
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1679
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1680
  if new_bdevs.count(None) > 0:
1681
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1682
  parent_bdev.AddChildren(new_bdevs)
1683

    
1684

    
1685
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1686
  """Shrink a mirrored block device.
1687

1688
  @type parent_cdev: L{objects.Disk}
1689
  @param parent_cdev: the disk from which we should remove children
1690
  @type new_cdevs: list of L{objects.Disk}
1691
  @param new_cdevs: the list of children which we should remove
1692
  @rtype: None
1693

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

    
1713

    
1714
def BlockdevGetmirrorstatus(disks):
1715
  """Get the mirroring status of a list of devices.
1716

1717
  @type disks: list of L{objects.Disk}
1718
  @param disks: the list of disks which we should query
1719
  @rtype: disk
1720
  @return: List of L{objects.BlockDevStatus}, one for each disk
1721
  @raise errors.BlockDeviceError: if any of the disks cannot be
1722
      found
1723

1724
  """
1725
  stats = []
1726
  for dsk in disks:
1727
    rbd = _RecursiveFindBD(dsk)
1728
    if rbd is None:
1729
      _Fail("Can't find device %s", dsk)
1730

    
1731
    stats.append(rbd.CombinedSyncStatus())
1732

    
1733
  return stats
1734

    
1735

    
1736
def BlockdevGetmirrorstatusMulti(disks):
1737
  """Get the mirroring status of a list of devices.
1738

1739
  @type disks: list of L{objects.Disk}
1740
  @param disks: the list of disks which we should query
1741
  @rtype: disk
1742
  @return: List of tuples, (bool, status), one for each disk; bool denotes
1743
    success/failure, status is L{objects.BlockDevStatus} on success, string
1744
    otherwise
1745

1746
  """
1747
  result = []
1748
  for disk in disks:
1749
    try:
1750
      rbd = _RecursiveFindBD(disk)
1751
      if rbd is None:
1752
        result.append((False, "Can't find device %s" % disk))
1753
        continue
1754

    
1755
      status = rbd.CombinedSyncStatus()
1756
    except errors.BlockDeviceError, err:
1757
      logging.exception("Error while getting disk status")
1758
      result.append((False, str(err)))
1759
    else:
1760
      result.append((True, status))
1761

    
1762
  assert len(disks) == len(result)
1763

    
1764
  return result
1765

    
1766

    
1767
def _RecursiveFindBD(disk):
1768
  """Check if a device is activated.
1769

1770
  If so, return information about the real device.
1771

1772
  @type disk: L{objects.Disk}
1773
  @param disk: the disk object we need to find
1774

1775
  @return: None if the device can't be found,
1776
      otherwise the device instance
1777

1778
  """
1779
  children = []
1780
  if disk.children:
1781
    for chdisk in disk.children:
1782
      children.append(_RecursiveFindBD(chdisk))
1783

    
1784
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1785

    
1786

    
1787
def _OpenRealBD(disk):
1788
  """Opens the underlying block device of a disk.
1789

1790
  @type disk: L{objects.Disk}
1791
  @param disk: the disk object we want to open
1792

1793
  """
1794
  real_disk = _RecursiveFindBD(disk)
1795
  if real_disk is None:
1796
    _Fail("Block device '%s' is not set up", disk)
1797

    
1798
  real_disk.Open()
1799

    
1800
  return real_disk
1801

    
1802

    
1803
def BlockdevFind(disk):
1804
  """Check if a device is activated.
1805

1806
  If it is, return information about the real device.
1807

1808
  @type disk: L{objects.Disk}
1809
  @param disk: the disk to find
1810
  @rtype: None or objects.BlockDevStatus
1811
  @return: None if the disk cannot be found, otherwise a the current
1812
           information
1813

1814
  """
1815
  try:
1816
    rbd = _RecursiveFindBD(disk)
1817
  except errors.BlockDeviceError, err:
1818
    _Fail("Failed to find device: %s", err, exc=True)
1819

    
1820
  if rbd is None:
1821
    return None
1822

    
1823
  return rbd.GetSyncStatus()
1824

    
1825

    
1826
def BlockdevGetsize(disks):
1827
  """Computes the size of the given disks.
1828

1829
  If a disk is not found, returns None instead.
1830

1831
  @type disks: list of L{objects.Disk}
1832
  @param disks: the list of disk to compute the size for
1833
  @rtype: list
1834
  @return: list with elements None if the disk cannot be found,
1835
      otherwise the size
1836

1837
  """
1838
  result = []
1839
  for cf in disks:
1840
    try:
1841
      rbd = _RecursiveFindBD(cf)
1842
    except errors.BlockDeviceError:
1843
      result.append(None)
1844
      continue
1845
    if rbd is None:
1846
      result.append(None)
1847
    else:
1848
      result.append(rbd.GetActualSize())
1849
  return result
1850

    
1851

    
1852
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
1853
  """Export a block device to a remote node.
1854

1855
  @type disk: L{objects.Disk}
1856
  @param disk: the description of the disk to export
1857
  @type dest_node: str
1858
  @param dest_node: the destination node to export to
1859
  @type dest_path: str
1860
  @param dest_path: the destination path on the target node
1861
  @type cluster_name: str
1862
  @param cluster_name: the cluster name, needed for SSH hostalias
1863
  @rtype: None
1864

1865
  """
1866
  real_disk = _OpenRealBD(disk)
1867

    
1868
  # the block size on the read dd is 1MiB to match our units
1869
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
1870
                               "dd if=%s bs=1048576 count=%s",
1871
                               real_disk.dev_path, str(disk.size))
1872

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

    
1882
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1883
                                                   constants.GANETI_RUNAS,
1884
                                                   destcmd)
1885

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

    
1889
  result = utils.RunCmd(["bash", "-c", command])
1890

    
1891
  if result.failed:
1892
    _Fail("Disk copy command '%s' returned error: %s"
1893
          " output: %s", command, result.fail_reason, result.output)
1894

    
1895

    
1896
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1897
  """Write a file to the filesystem.
1898

1899
  This allows the master to overwrite(!) a file. It will only perform
1900
  the operation if the file belongs to a list of configuration files.
1901

1902
  @type file_name: str
1903
  @param file_name: the target file name
1904
  @type data: str
1905
  @param data: the new contents of the file
1906
  @type mode: int
1907
  @param mode: the mode to give the file (can be None)
1908
  @type uid: string
1909
  @param uid: the owner of the file
1910
  @type gid: string
1911
  @param gid: the group of the file
1912
  @type atime: float
1913
  @param atime: the atime to set on the file (can be None)
1914
  @type mtime: float
1915
  @param mtime: the mtime to set on the file (can be None)
1916
  @rtype: None
1917

1918
  """
1919
  if not os.path.isabs(file_name):
1920
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
1921

    
1922
  if file_name not in _ALLOWED_UPLOAD_FILES:
1923
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
1924
          file_name)
1925

    
1926
  raw_data = _Decompress(data)
1927

    
1928
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
1929
    _Fail("Invalid username/groupname type")
1930

    
1931
  getents = runtime.GetEnts()
1932
  uid = getents.LookupUser(uid)
1933
  gid = getents.LookupGroup(gid)
1934

    
1935
  utils.SafeWriteFile(file_name, None,
1936
                      data=raw_data, mode=mode, uid=uid, gid=gid,
1937
                      atime=atime, mtime=mtime)
1938

    
1939

    
1940
def RunOob(oob_program, command, node, timeout):
1941
  """Executes oob_program with given command on given node.
1942

1943
  @param oob_program: The path to the executable oob_program
1944
  @param command: The command to invoke on oob_program
1945
  @param node: The node given as an argument to the program
1946
  @param timeout: Timeout after which we kill the oob program
1947

1948
  @return: stdout
1949
  @raise RPCFail: If execution fails for some reason
1950

1951
  """
1952
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
1953

    
1954
  if result.failed:
1955
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
1956
          result.fail_reason, result.output)
1957

    
1958
  return result.stdout
1959

    
1960

    
1961
def WriteSsconfFiles(values):
1962
  """Update all ssconf files.
1963

1964
  Wrapper around the SimpleStore.WriteFiles.
1965

1966
  """
1967
  ssconf.SimpleStore().WriteFiles(values)
1968

    
1969

    
1970
def _ErrnoOrStr(err):
1971
  """Format an EnvironmentError exception.
1972

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

1977
  @type err: L{EnvironmentError}
1978
  @param err: the exception to format
1979

1980
  """
1981
  if hasattr(err, "errno"):
1982
    detail = errno.errorcode[err.errno]
1983
  else:
1984
    detail = str(err)
1985
  return detail
1986

    
1987

    
1988
def _OSOndiskAPIVersion(os_dir):
1989
  """Compute and return the API version of a given OS.
1990

1991
  This function will try to read the API version of the OS residing in
1992
  the 'os_dir' directory.
1993

1994
  @type os_dir: str
1995
  @param os_dir: the directory in which we should look for the OS
1996
  @rtype: tuple
1997
  @return: tuple (status, data) with status denoting the validity and
1998
      data holding either the vaid versions or an error message
1999

2000
  """
2001
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2002

    
2003
  try:
2004
    st = os.stat(api_file)
2005
  except EnvironmentError, err:
2006
    return False, ("Required file '%s' not found under path %s: %s" %
2007
                   (constants.OS_API_FILE, os_dir, _ErrnoOrStr(err)))
2008

    
2009
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2010
    return False, ("File '%s' in %s is not a regular file" %
2011
                   (constants.OS_API_FILE, os_dir))
2012

    
2013
  try:
2014
    api_versions = utils.ReadFile(api_file).splitlines()
2015
  except EnvironmentError, err:
2016
    return False, ("Error while reading the API version file at %s: %s" %
2017
                   (api_file, _ErrnoOrStr(err)))
2018

    
2019
  try:
2020
    api_versions = [int(version.strip()) for version in api_versions]
2021
  except (TypeError, ValueError), err:
2022
    return False, ("API version(s) can't be converted to integer: %s" %
2023
                   str(err))
2024

    
2025
  return True, api_versions
2026

    
2027

    
2028
def DiagnoseOS(top_dirs=None):
2029
  """Compute the validity for all OSes.
2030

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

2047
  """
2048
  if top_dirs is None:
2049
    top_dirs = constants.OS_SEARCH_PATH
2050

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

    
2073
  return result
2074

    
2075

    
2076
def _TryOSFromDisk(name, base_dir=None):
2077
  """Create an OS instance from disk.
2078

2079
  This function will return an OS instance if the given name is a
2080
  valid OS name.
2081

2082
  @type base_dir: string
2083
  @keyword base_dir: Base directory containing OS installations.
2084
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2085
  @rtype: tuple
2086
  @return: success and either the OS instance if we find a valid one,
2087
      or error message
2088

2089
  """
2090
  if base_dir is None:
2091
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
2092
  else:
2093
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2094

    
2095
  if os_dir is None:
2096
    return False, "Directory for OS %s not found in search path" % name
2097

    
2098
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2099
  if not status:
2100
    # push the error up
2101
    return status, api_versions
2102

    
2103
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2104
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2105
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2106

    
2107
  # OS Files dictionary, we will populate it with the absolute path
2108
  # names; if the value is True, then it is a required file, otherwise
2109
  # an optional one
2110
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2111

    
2112
  if max(api_versions) >= constants.OS_API_V15:
2113
    os_files[constants.OS_VARIANTS_FILE] = False
2114

    
2115
  if max(api_versions) >= constants.OS_API_V20:
2116
    os_files[constants.OS_PARAMETERS_FILE] = True
2117
  else:
2118
    del os_files[constants.OS_SCRIPT_VERIFY]
2119

    
2120
  for (filename, required) in os_files.items():
2121
    os_files[filename] = utils.PathJoin(os_dir, filename)
2122

    
2123
    try:
2124
      st = os.stat(os_files[filename])
2125
    except EnvironmentError, err:
2126
      if err.errno == errno.ENOENT and not required:
2127
        del os_files[filename]
2128
        continue
2129
      return False, ("File '%s' under path '%s' is missing (%s)" %
2130
                     (filename, os_dir, _ErrnoOrStr(err)))
2131

    
2132
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2133
      return False, ("File '%s' under path '%s' is not a regular file" %
2134
                     (filename, os_dir))
2135

    
2136
    if filename in constants.OS_SCRIPTS:
2137
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2138
        return False, ("File '%s' under path '%s' is not executable" %
2139
                       (filename, os_dir))
2140

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

    
2152
  parameters = []
2153
  if constants.OS_PARAMETERS_FILE in os_files:
2154
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2155
    try:
2156
      parameters = utils.ReadFile(parameters_file).splitlines()
2157
    except EnvironmentError, err:
2158
      return False, ("Error while reading the OS parameters file at %s: %s" %
2159
                     (parameters_file, _ErrnoOrStr(err)))
2160
    parameters = [v.split(None, 1) for v in parameters]
2161

    
2162
  os_obj = objects.OS(name=name, path=os_dir,
2163
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2164
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2165
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2166
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2167
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2168
                                                 None),
2169
                      supported_variants=variants,
2170
                      supported_parameters=parameters,
2171
                      api_versions=api_versions)
2172
  return True, os_obj
2173

    
2174

    
2175
def OSFromDisk(name, base_dir=None):
2176
  """Create an OS instance from disk.
2177

2178
  This function will return an OS instance if the given name is a
2179
  valid OS name. Otherwise, it will raise an appropriate
2180
  L{RPCFail} exception, detailing why this is not a valid OS.
2181

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

2185
  @type base_dir: string
2186
  @keyword base_dir: Base directory containing OS installations.
2187
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2188
  @rtype: L{objects.OS}
2189
  @return: the OS instance if we find a valid one
2190
  @raise RPCFail: if we don't find a valid OS
2191

2192
  """
2193
  name_only = objects.OS.GetName(name)
2194
  status, payload = _TryOSFromDisk(name_only, base_dir)
2195

    
2196
  if not status:
2197
    _Fail(payload)
2198

    
2199
  return payload
2200

    
2201

    
2202
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2203
  """Calculate the basic environment for an os script.
2204

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

2218
  """
2219
  result = {}
2220
  api_version = \
2221
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2222
  result["OS_API_VERSION"] = "%d" % api_version
2223
  result["OS_NAME"] = inst_os.name
2224
  result["DEBUG_LEVEL"] = "%d" % debug
2225

    
2226
  # OS variants
2227
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2228
    variant = objects.OS.GetVariant(os_name)
2229
    if not variant:
2230
      variant = inst_os.supported_variants[0]
2231
  else:
2232
    variant = ""
2233
  result["OS_VARIANT"] = variant
2234

    
2235
  # OS params
2236
  for pname, pvalue in os_params.items():
2237
    result["OSP_%s" % pname.upper()] = pvalue
2238

    
2239
  return result
2240

    
2241

    
2242
def OSEnvironment(instance, inst_os, debug=0):
2243
  """Calculate the environment for an os script.
2244

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

2256
  """
2257
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2258

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

    
2262
  result["HYPERVISOR"] = instance.hypervisor
2263
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2264
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2265
  result["INSTANCE_SECONDARY_NODES"] = \
2266
      ("%s" % " ".join(instance.secondary_nodes))
2267

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

    
2282
  # NICs
2283
  for idx, nic in enumerate(instance.nics):
2284
    result["NIC_%d_MAC" % idx] = nic.mac
2285
    if nic.ip:
2286
      result["NIC_%d_IP" % idx] = nic.ip
2287
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2288
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2289
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2290
    if nic.nicparams[constants.NIC_LINK]:
2291
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2292
    if constants.HV_NIC_TYPE in instance.hvparams:
2293
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2294
        instance.hvparams[constants.HV_NIC_TYPE]
2295

    
2296
  # HV/BE params
2297
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2298
    for key, value in source.items():
2299
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2300

    
2301
  return result
2302

    
2303

    
2304
def BlockdevGrow(disk, amount, dryrun):
2305
  """Grow a stack of block devices.
2306

2307
  This function is called recursively, with the childrens being the
2308
  first ones to resize.
2309

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

2321
  """
2322
  r_dev = _RecursiveFindBD(disk)
2323
  if r_dev is None:
2324
    _Fail("Cannot find block device %s", disk)
2325

    
2326
  try:
2327
    r_dev.Grow(amount, dryrun)
2328
  except errors.BlockDeviceError, err:
2329
    _Fail("Failed to grow block device: %s", err, exc=True)
2330

    
2331

    
2332
def BlockdevSnapshot(disk):
2333
  """Create a snapshot copy of a block device.
2334

2335
  This function is called recursively, and the snapshot is actually created
2336
  just for the leaf lvm backend device.
2337

2338
  @type disk: L{objects.Disk}
2339
  @param disk: the disk to be snapshotted
2340
  @rtype: string
2341
  @return: snapshot disk ID as (vg, lv)
2342

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

    
2361

    
2362
def FinalizeExport(instance, snap_disks):
2363
  """Write out the export configuration information.
2364

2365
  @type instance: L{objects.Instance}
2366
  @param instance: the instance which we export, used for
2367
      saving configuration
2368
  @type snap_disks: list of L{objects.Disk}
2369
  @param snap_disks: list of snapshot block devices, which
2370
      will be used to get the actual name of the dump file
2371

2372
  @rtype: None
2373

2374
  """
2375
  destdir = utils.PathJoin(constants.EXPORT_DIR, instance.name + ".new")
2376
  finaldestdir = utils.PathJoin(constants.EXPORT_DIR, instance.name)
2377

    
2378
  config = objects.SerializableConfigParser()
2379

    
2380
  config.add_section(constants.INISECT_EXP)
2381
  config.set(constants.INISECT_EXP, "version", "0")
2382
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2383
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2384
  config.set(constants.INISECT_EXP, "os", instance.os)
2385
  config.set(constants.INISECT_EXP, "compression", "none")
2386

    
2387
  config.add_section(constants.INISECT_INS)
2388
  config.set(constants.INISECT_INS, "name", instance.name)
2389
  config.set(constants.INISECT_INS, "memory", "%d" %
2390
             instance.beparams[constants.BE_MEMORY])
2391
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2392
             instance.beparams[constants.BE_VCPUS])
2393
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2394
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2395
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2396

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

    
2409
  disk_total = 0
2410
  for disk_count, disk in enumerate(snap_disks):
2411
    if disk:
2412
      disk_total += 1
2413
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2414
                 ("%s" % disk.iv_name))
2415
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2416
                 ("%s" % disk.physical_id[1]))
2417
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2418
                 ("%d" % disk.size))
2419

    
2420
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2421

    
2422
  # New-style hypervisor/backend parameters
2423

    
2424
  config.add_section(constants.INISECT_HYP)
2425
  for name, value in instance.hvparams.items():
2426
    if name not in constants.HVC_GLOBALS:
2427
      config.set(constants.INISECT_HYP, name, str(value))
2428

    
2429
  config.add_section(constants.INISECT_BEP)
2430
  for name, value in instance.beparams.items():
2431
    config.set(constants.INISECT_BEP, name, str(value))
2432

    
2433
  config.add_section(constants.INISECT_OSP)
2434
  for name, value in instance.osparams.items():
2435
    config.set(constants.INISECT_OSP, name, str(value))
2436

    
2437
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2438
                  data=config.Dumps())
2439
  shutil.rmtree(finaldestdir, ignore_errors=True)
2440
  shutil.move(destdir, finaldestdir)
2441

    
2442

    
2443
def ExportInfo(dest):
2444
  """Get export configuration information.
2445

2446
  @type dest: str
2447
  @param dest: directory containing the export
2448

2449
  @rtype: L{objects.SerializableConfigParser}
2450
  @return: a serializable config file containing the
2451
      export info
2452

2453
  """
2454
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2455

    
2456
  config = objects.SerializableConfigParser()
2457
  config.read(cff)
2458

    
2459
  if (not config.has_section(constants.INISECT_EXP) or
2460
      not config.has_section(constants.INISECT_INS)):
2461
    _Fail("Export info file doesn't have the required fields")
2462

    
2463
  return config.Dumps()
2464

    
2465

    
2466
def ListExports():
2467
  """Return a list of exports currently available on this machine.
2468

2469
  @rtype: list
2470
  @return: list of the exports
2471

2472
  """
2473
  if os.path.isdir(constants.EXPORT_DIR):
2474
    return sorted(utils.ListVisibleFiles(constants.EXPORT_DIR))
2475
  else:
2476
    _Fail("No exports directory")
2477

    
2478

    
2479
def RemoveExport(export):
2480
  """Remove an existing export from the node.
2481

2482
  @type export: str
2483
  @param export: the name of the export to remove
2484
  @rtype: None
2485

2486
  """
2487
  target = utils.PathJoin(constants.EXPORT_DIR, export)
2488

    
2489
  try:
2490
    shutil.rmtree(target)
2491
  except EnvironmentError, err:
2492
    _Fail("Error while removing the export: %s", err, exc=True)
2493

    
2494

    
2495
def BlockdevRename(devlist):
2496
  """Rename a list of block devices.
2497

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

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

    
2535

    
2536
def _TransformFileStorageDir(fs_dir):
2537
  """Checks whether given file_storage_dir is valid.
2538

2539
  Checks wheter the given fs_dir is within the cluster-wide default
2540
  file_storage_dir or the shared_file_storage_dir, which are stored in
2541
  SimpleStore. Only paths under those directories are allowed.
2542

2543
  @type fs_dir: str
2544
  @param fs_dir: the path to check
2545

2546
  @return: the normalized path if valid, None otherwise
2547

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

    
2562

    
2563
def CreateFileStorageDir(file_storage_dir):
2564
  """Create file storage directory.
2565

2566
  @type file_storage_dir: str
2567
  @param file_storage_dir: directory to create
2568

2569
  @rtype: tuple
2570
  @return: tuple with first element a boolean indicating wheter dir
2571
      creation was successful or not
2572

2573
  """
2574
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2575
  if os.path.exists(file_storage_dir):
2576
    if not os.path.isdir(file_storage_dir):
2577
      _Fail("Specified storage dir '%s' is not a directory",
2578
            file_storage_dir)
2579
  else:
2580
    try:
2581
      os.makedirs(file_storage_dir, 0750)
2582
    except OSError, err:
2583
      _Fail("Cannot create file storage directory '%s': %s",
2584
            file_storage_dir, err, exc=True)
2585

    
2586

    
2587
def RemoveFileStorageDir(file_storage_dir):
2588
  """Remove file storage directory.
2589

2590
  Remove it only if it's empty. If not log an error and return.
2591

2592
  @type file_storage_dir: str
2593
  @param file_storage_dir: the directory we should cleanup
2594
  @rtype: tuple (success,)
2595
  @return: tuple of one element, C{success}, denoting
2596
      whether the operation was successful
2597

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

    
2611

    
2612
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2613
  """Rename the file storage directory.
2614

2615
  @type old_file_storage_dir: str
2616
  @param old_file_storage_dir: the current path
2617
  @type new_file_storage_dir: str
2618
  @param new_file_storage_dir: the name we should rename to
2619
  @rtype: tuple (success,)
2620
  @return: tuple of one element, C{success}, denoting
2621
      whether the operation was successful
2622

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

    
2641

    
2642
def _EnsureJobQueueFile(file_name):
2643
  """Checks whether the given filename is in the queue directory.
2644

2645
  @type file_name: str
2646
  @param file_name: the file name we should check
2647
  @rtype: None
2648
  @raises RPCFail: if the file is not valid
2649

2650
  """
2651
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2652
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2653

    
2654
  if not result:
2655
    _Fail("Passed job queue file '%s' does not belong to"
2656
          " the queue directory '%s'", file_name, queue_dir)
2657

    
2658

    
2659
def JobQueueUpdate(file_name, content):
2660
  """Updates a file in the queue directory.
2661

2662
  This is just a wrapper over L{utils.io.WriteFile}, with proper
2663
  checking.
2664

2665
  @type file_name: str
2666
  @param file_name: the job file name
2667
  @type content: str
2668
  @param content: the new job contents
2669
  @rtype: boolean
2670
  @return: the success of the operation
2671

2672
  """
2673
  _EnsureJobQueueFile(file_name)
2674
  getents = runtime.GetEnts()
2675

    
2676
  # Write and replace the file atomically
2677
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
2678
                  gid=getents.masterd_gid)
2679

    
2680

    
2681
def JobQueueRename(old, new):
2682
  """Renames a job queue file.
2683

2684
  This is just a wrapper over os.rename with proper checking.
2685

2686
  @type old: str
2687
  @param old: the old (actual) file name
2688
  @type new: str
2689
  @param new: the desired file name
2690
  @rtype: tuple
2691
  @return: the success of the operation and payload
2692

2693
  """
2694
  _EnsureJobQueueFile(old)
2695
  _EnsureJobQueueFile(new)
2696

    
2697
  getents = runtime.GetEnts()
2698

    
2699
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0700,
2700
                   dir_uid=getents.masterd_uid, dir_gid=getents.masterd_gid)
2701

    
2702

    
2703
def BlockdevClose(instance_name, disks):
2704
  """Closes the given block devices.
2705

2706
  This means they will be switched to secondary mode (in case of
2707
  DRBD).
2708

2709
  @param instance_name: if the argument is not empty, the symlinks
2710
      of this instance will be removed
2711
  @type disks: list of L{objects.Disk}
2712
  @param disks: the list of disks to be closed
2713
  @rtype: tuple (success, message)
2714
  @return: a tuple of success and message, where success
2715
      indicates the succes of the operation, and message
2716
      which will contain the error details in case we
2717
      failed
2718

2719
  """
2720
  bdevs = []
2721
  for cf in disks:
2722
    rd = _RecursiveFindBD(cf)
2723
    if rd is None:
2724
      _Fail("Can't find device %s", cf)
2725
    bdevs.append(rd)
2726

    
2727
  msg = []
2728
  for rd in bdevs:
2729
    try:
2730
      rd.Close()
2731
    except errors.BlockDeviceError, err:
2732
      msg.append(str(err))
2733
  if msg:
2734
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2735
  else:
2736
    if instance_name:
2737
      _RemoveBlockDevLinks(instance_name, disks)
2738

    
2739

    
2740
def ValidateHVParams(hvname, hvparams):
2741
  """Validates the given hypervisor parameters.
2742

2743
  @type hvname: string
2744
  @param hvname: the hypervisor name
2745
  @type hvparams: dict
2746
  @param hvparams: the hypervisor parameters to be validated
2747
  @rtype: None
2748

2749
  """
2750
  try:
2751
    hv_type = hypervisor.GetHypervisor(hvname)
2752
    hv_type.ValidateParameters(hvparams)
2753
  except errors.HypervisorError, err:
2754
    _Fail(str(err), log=False)
2755

    
2756

    
2757
def _CheckOSPList(os_obj, parameters):
2758
  """Check whether a list of parameters is supported by the OS.
2759

2760
  @type os_obj: L{objects.OS}
2761
  @param os_obj: OS object to check
2762
  @type parameters: list
2763
  @param parameters: the list of parameters to check
2764

2765
  """
2766
  supported = [v[0] for v in os_obj.supported_parameters]
2767
  delta = frozenset(parameters).difference(supported)
2768
  if delta:
2769
    _Fail("The following parameters are not supported"
2770
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
2771

    
2772

    
2773
def ValidateOS(required, osname, checks, osparams):
2774
  """Validate the given OS' parameters.
2775

2776
  @type required: boolean
2777
  @param required: whether absence of the OS should translate into
2778
      failure or not
2779
  @type osname: string
2780
  @param osname: the OS to be validated
2781
  @type checks: list
2782
  @param checks: list of the checks to run (currently only 'parameters')
2783
  @type osparams: dict
2784
  @param osparams: dictionary with OS parameters
2785
  @rtype: boolean
2786
  @return: True if the validation passed, or False if the OS was not
2787
      found and L{required} was false
2788

2789
  """
2790
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
2791
    _Fail("Unknown checks required for OS %s: %s", osname,
2792
          set(checks).difference(constants.OS_VALIDATE_CALLS))
2793

    
2794
  name_only = objects.OS.GetName(osname)
2795
  status, tbv = _TryOSFromDisk(name_only, None)
2796

    
2797
  if not status:
2798
    if required:
2799
      _Fail(tbv)
2800
    else:
2801
      return False
2802

    
2803
  if max(tbv.api_versions) < constants.OS_API_V20:
2804
    return True
2805

    
2806
  if constants.OS_VALIDATE_PARAMETERS in checks:
2807
    _CheckOSPList(tbv, osparams.keys())
2808

    
2809
  validate_env = OSCoreEnv(osname, tbv, osparams)
2810
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
2811
                        cwd=tbv.path, reset_env=True)
2812
  if result.failed:
2813
    logging.error("os validate command '%s' returned error: %s output: %s",
2814
                  result.cmd, result.fail_reason, result.output)
2815
    _Fail("OS validation script failed (%s), output: %s",
2816
          result.fail_reason, result.output, log=False)
2817

    
2818
  return True
2819

    
2820

    
2821
def DemoteFromMC():
2822
  """Demotes the current node from master candidate role.
2823

2824
  """
2825
  # try to ensure we're not the master by mistake
2826
  master, myself = ssconf.GetMasterAndMyself()
2827
  if master == myself:
2828
    _Fail("ssconf status shows I'm the master node, will not demote")
2829

    
2830
  result = utils.RunCmd([constants.DAEMON_UTIL, "check", constants.MASTERD])
2831
  if not result.failed:
2832
    _Fail("The master daemon is running, will not demote")
2833

    
2834
  try:
2835
    if os.path.isfile(constants.CLUSTER_CONF_FILE):
2836
      utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2837
  except EnvironmentError, err:
2838
    if err.errno != errno.ENOENT:
2839
      _Fail("Error while backing up cluster file: %s", err, exc=True)
2840

    
2841
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2842

    
2843

    
2844
def _GetX509Filenames(cryptodir, name):
2845
  """Returns the full paths for the private key and certificate.
2846

2847
  """
2848
  return (utils.PathJoin(cryptodir, name),
2849
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
2850
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
2851

    
2852

    
2853
def CreateX509Certificate(validity, cryptodir=constants.CRYPTO_KEYS_DIR):
2854
  """Creates a new X509 certificate for SSL/TLS.
2855

2856
  @type validity: int
2857
  @param validity: Validity in seconds
2858
  @rtype: tuple; (string, string)
2859
  @return: Certificate name and public part
2860

2861
  """
2862
  (key_pem, cert_pem) = \
2863
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
2864
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
2865

    
2866
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
2867
                              prefix="x509-%s-" % utils.TimestampForFilename())
2868
  try:
2869
    name = os.path.basename(cert_dir)
2870
    assert len(name) > 5
2871

    
2872
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2873

    
2874
    utils.WriteFile(key_file, mode=0400, data=key_pem)
2875
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
2876

    
2877
    # Never return private key as it shouldn't leave the node
2878
    return (name, cert_pem)
2879
  except Exception:
2880
    shutil.rmtree(cert_dir, ignore_errors=True)
2881
    raise
2882

    
2883

    
2884
def RemoveX509Certificate(name, cryptodir=constants.CRYPTO_KEYS_DIR):
2885
  """Removes a X509 certificate.
2886

2887
  @type name: string
2888
  @param name: Certificate name
2889

2890
  """
2891
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2892

    
2893
  utils.RemoveFile(key_file)
2894
  utils.RemoveFile(cert_file)
2895

    
2896
  try:
2897
    os.rmdir(cert_dir)
2898
  except EnvironmentError, err:
2899
    _Fail("Cannot remove certificate directory '%s': %s",
2900
          cert_dir, err)
2901

    
2902

    
2903
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
2904
  """Returns the command for the requested input/output.
2905

2906
  @type instance: L{objects.Instance}
2907
  @param instance: The instance object
2908
  @param mode: Import/export mode
2909
  @param ieio: Input/output type
2910
  @param ieargs: Input/output arguments
2911

2912
  """
2913
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
2914

    
2915
  env = None
2916
  prefix = None
2917
  suffix = None
2918
  exp_size = None
2919

    
2920
  if ieio == constants.IEIO_FILE:
2921
    (filename, ) = ieargs
2922

    
2923
    if not utils.IsNormAbsPath(filename):
2924
      _Fail("Path '%s' is not normalized or absolute", filename)
2925

    
2926
    real_filename = os.path.realpath(filename)
2927
    directory = os.path.dirname(real_filename)
2928

    
2929
    if not utils.IsBelowDir(constants.EXPORT_DIR, real_filename):
2930
      _Fail("File '%s' is not under exports directory '%s': %s",
2931
            filename, constants.EXPORT_DIR, real_filename)
2932

    
2933
    # Create directory
2934
    utils.Makedirs(directory, mode=0750)
2935

    
2936
    quoted_filename = utils.ShellQuote(filename)
2937

    
2938
    if mode == constants.IEM_IMPORT:
2939
      suffix = "> %s" % quoted_filename
2940
    elif mode == constants.IEM_EXPORT:
2941
      suffix = "< %s" % quoted_filename
2942

    
2943
      # Retrieve file size
2944
      try:
2945
        st = os.stat(filename)
2946
      except EnvironmentError, err:
2947
        logging.error("Can't stat(2) %s: %s", filename, err)
2948
      else:
2949
        exp_size = utils.BytesToMebibyte(st.st_size)
2950

    
2951
  elif ieio == constants.IEIO_RAW_DISK:
2952
    (disk, ) = ieargs
2953

    
2954
    real_disk = _OpenRealBD(disk)
2955

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

    
2968
    elif mode == constants.IEM_EXPORT:
2969
      # the block size on the read dd is 1MiB to match our units
2970
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
2971
                                   real_disk.dev_path,
2972
                                   str(1024 * 1024), # 1 MB
2973
                                   str(disk.size))
2974
      exp_size = disk.size
2975

    
2976
  elif ieio == constants.IEIO_SCRIPT:
2977
    (disk, disk_index, ) = ieargs
2978

    
2979
    assert isinstance(disk_index, (int, long))
2980

    
2981
    real_disk = _OpenRealBD(disk)
2982

    
2983
    inst_os = OSFromDisk(instance.os)
2984
    env = OSEnvironment(instance, inst_os)
2985

    
2986
    if mode == constants.IEM_IMPORT:
2987
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
2988
      env["IMPORT_INDEX"] = str(disk_index)
2989
      script = inst_os.import_script
2990

    
2991
    elif mode == constants.IEM_EXPORT:
2992
      env["EXPORT_DEVICE"] = real_disk.dev_path
2993
      env["EXPORT_INDEX"] = str(disk_index)
2994
      script = inst_os.export_script
2995

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

    
2999
    if mode == constants.IEM_IMPORT:
3000
      suffix = "| %s" % script_cmd
3001

    
3002
    elif mode == constants.IEM_EXPORT:
3003
      prefix = "%s |" % script_cmd
3004

    
3005
    # Let script predict size
3006
    exp_size = constants.IE_CUSTOM_SIZE
3007

    
3008
  else:
3009
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3010

    
3011
  return (env, prefix, suffix, exp_size)
3012

    
3013

    
3014
def _CreateImportExportStatusDir(prefix):
3015
  """Creates status directory for import/export.
3016

3017
  """
3018
  return tempfile.mkdtemp(dir=constants.IMPORT_EXPORT_DIR,
3019
                          prefix=("%s-%s-" %
3020
                                  (prefix, utils.TimestampForFilename())))
3021

    
3022

    
3023
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3024
                            ieio, ieioargs):
3025
  """Starts an import or export daemon.
3026

3027
  @param mode: Import/output mode
3028
  @type opts: L{objects.ImportExportOptions}
3029
  @param opts: Daemon options
3030
  @type host: string
3031
  @param host: Remote host for export (None for import)
3032
  @type port: int
3033
  @param port: Remote port for export (None for import)
3034
  @type instance: L{objects.Instance}
3035
  @param instance: Instance object
3036
  @type component: string
3037
  @param component: which part of the instance is transferred now,
3038
      e.g. 'disk/0'
3039
  @param ieio: Input/output type
3040
  @param ieioargs: Input/output arguments
3041

3042
  """
3043
  if mode == constants.IEM_IMPORT:
3044
    prefix = "import"
3045

    
3046
    if not (host is None and port is None):
3047
      _Fail("Can not specify host or port on import")
3048

    
3049
  elif mode == constants.IEM_EXPORT:
3050
    prefix = "export"
3051

    
3052
    if host is None or port is None:
3053
      _Fail("Host and port must be specified for an export")
3054

    
3055
  else:
3056
    _Fail("Invalid mode %r", mode)
3057

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

    
3061
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3062
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3063

    
3064
  if opts.key_name is None:
3065
    # Use server.pem
3066
    key_path = constants.NODED_CERT_FILE
3067
    cert_path = constants.NODED_CERT_FILE
3068
    assert opts.ca_pem is None
3069
  else:
3070
    (_, key_path, cert_path) = _GetX509Filenames(constants.CRYPTO_KEYS_DIR,
3071
                                                 opts.key_name)
3072
    assert opts.ca_pem is not None
3073

    
3074
  for i in [key_path, cert_path]:
3075
    if not os.path.exists(i):
3076
      _Fail("File '%s' does not exist" % i)
3077

    
3078
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3079
  try:
3080
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3081
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3082
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3083

    
3084
    if opts.ca_pem is None:
3085
      # Use server.pem
3086
      ca = utils.ReadFile(constants.NODED_CERT_FILE)
3087
    else:
3088
      ca = opts.ca_pem
3089

    
3090
    # Write CA file
3091
    utils.WriteFile(ca_file, data=ca, mode=0400)
3092

    
3093
    cmd = [
3094
      constants.IMPORT_EXPORT_DAEMON,
3095
      status_file, mode,
3096
      "--key=%s" % key_path,
3097
      "--cert=%s" % cert_path,
3098
      "--ca=%s" % ca_file,
3099
      ]
3100

    
3101
    if host:
3102
      cmd.append("--host=%s" % host)
3103

    
3104
    if port:
3105
      cmd.append("--port=%s" % port)
3106

    
3107
    if opts.ipv6:
3108
      cmd.append("--ipv6")
3109
    else:
3110
      cmd.append("--ipv4")
3111

    
3112
    if opts.compress:
3113
      cmd.append("--compress=%s" % opts.compress)
3114

    
3115
    if opts.magic:
3116
      cmd.append("--magic=%s" % opts.magic)
3117

    
3118
    if exp_size is not None:
3119
      cmd.append("--expected-size=%s" % exp_size)
3120

    
3121
    if cmd_prefix:
3122
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3123

    
3124
    if cmd_suffix:
3125
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3126

    
3127
    if mode == constants.IEM_EXPORT:
3128
      # Retry connection a few times when connecting to remote peer
3129
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3130
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3131
    elif opts.connect_timeout is not None:
3132
      assert mode == constants.IEM_IMPORT
3133
      # Overall timeout for establishing connection while listening
3134
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3135

    
3136
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3137

    
3138
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3139
    # support for receiving a file descriptor for output
3140
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3141
                      output=logfile)
3142

    
3143
    # The import/export name is simply the status directory name
3144
    return os.path.basename(status_dir)
3145

    
3146
  except Exception:
3147
    shutil.rmtree(status_dir, ignore_errors=True)
3148
    raise
3149

    
3150

    
3151
def GetImportExportStatus(names):
3152
  """Returns import/export daemon status.
3153

3154
  @type names: sequence
3155
  @param names: List of names
3156
  @rtype: List of dicts
3157
  @return: Returns a list of the state of each named import/export or None if a
3158
           status couldn't be read
3159

3160
  """
3161
  result = []
3162

    
3163
  for name in names:
3164
    status_file = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name,
3165
                                 _IES_STATUS_FILE)
3166

    
3167
    try:
3168
      data = utils.ReadFile(status_file)
3169
    except EnvironmentError, err:
3170
      if err.errno != errno.ENOENT:
3171
        raise
3172
      data = None
3173

    
3174
    if not data:
3175
      result.append(None)
3176
      continue
3177

    
3178
    result.append(serializer.LoadJson(data))
3179

    
3180
  return result
3181

    
3182

    
3183
def AbortImportExport(name):
3184
  """Sends SIGTERM to a running import/export daemon.
3185

3186
  """
3187
  logging.info("Abort import/export %s", name)
3188

    
3189
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3190
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3191

    
3192
  if pid:
3193
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3194
                 name, pid)
3195
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3196

    
3197

    
3198
def CleanupImportExport(name):
3199
  """Cleanup after an import or export.
3200

3201
  If the import/export daemon is still running it's killed. Afterwards the
3202
  whole status directory is removed.
3203

3204
  """
3205
  logging.info("Finalizing import/export %s", name)
3206

    
3207
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3208

    
3209
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3210

    
3211
  if pid:
3212
    logging.info("Import/export %s is still running with PID %s",
3213
                 name, pid)
3214
    utils.KillProcess(pid, waitpid=False)
3215

    
3216
  shutil.rmtree(status_dir, ignore_errors=True)
3217

    
3218

    
3219
def _FindDisks(nodes_ip, disks):
3220
  """Sets the physical ID on disks and returns the block devices.
3221

3222
  """
3223
  # set the correct physical ID
3224
  my_name = netutils.Hostname.GetSysName()
3225
  for cf in disks:
3226
    cf.SetPhysicalID(my_name, nodes_ip)
3227

    
3228
  bdevs = []
3229

    
3230
  for cf in disks:
3231
    rd = _RecursiveFindBD(cf)
3232
    if rd is None:
3233
      _Fail("Can't find device %s", cf)
3234
    bdevs.append(rd)
3235
  return bdevs
3236

    
3237

    
3238
def DrbdDisconnectNet(nodes_ip, disks):
3239
  """Disconnects the network on a list of drbd devices.
3240

3241
  """
3242
  bdevs = _FindDisks(nodes_ip, disks)
3243

    
3244
  # disconnect disks
3245
  for rd in bdevs:
3246
    try:
3247
      rd.DisconnectNet()
3248
    except errors.BlockDeviceError, err:
3249
      _Fail("Can't change network configuration to standalone mode: %s",
3250
            err, exc=True)
3251

    
3252

    
3253
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3254
  """Attaches the network on a list of drbd devices.
3255

3256
  """
3257
  bdevs = _FindDisks(nodes_ip, disks)
3258

    
3259
  if multimaster:
3260
    for idx, rd in enumerate(bdevs):
3261
      try:
3262
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3263
      except EnvironmentError, err:
3264
        _Fail("Can't create symlink: %s", err)
3265
  # reconnect disks, switch to new master configuration and if
3266
  # needed primary mode
3267
  for rd in bdevs:
3268
    try:
3269
      rd.AttachNet(multimaster)
3270
    except errors.BlockDeviceError, err:
3271
      _Fail("Can't change network configuration: %s", err)
3272

    
3273
  # wait until the disks are connected; we need to retry the re-attach
3274
  # if the device becomes standalone, as this might happen if the one
3275
  # node disconnects and reconnects in a different mode before the
3276
  # other node reconnects; in this case, one or both of the nodes will
3277
  # decide it has wrong configuration and switch to standalone
3278

    
3279
  def _Attach():
3280
    all_connected = True
3281

    
3282
    for rd in bdevs:
3283
      stats = rd.GetProcStatus()
3284

    
3285
      all_connected = (all_connected and
3286
                       (stats.is_connected or stats.is_in_resync))
3287

    
3288
      if stats.is_standalone:
3289
        # peer had different config info and this node became
3290
        # standalone, even though this should not happen with the
3291
        # new staged way of changing disk configs
3292
        try:
3293
          rd.AttachNet(multimaster)
3294
        except errors.BlockDeviceError, err:
3295
          _Fail("Can't change network configuration: %s", err)
3296

    
3297
    if not all_connected:
3298
      raise utils.RetryAgain()
3299

    
3300
  try:
3301
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3302
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3303
  except utils.RetryTimeout:
3304
    _Fail("Timeout in disk reconnecting")
3305

    
3306
  if multimaster:
3307
    # change to primary mode
3308
    for rd in bdevs:
3309
      try:
3310
        rd.Open()
3311
      except errors.BlockDeviceError, err:
3312
        _Fail("Can't change to primary mode: %s", err)
3313

    
3314

    
3315
def DrbdWaitSync(nodes_ip, disks):
3316
  """Wait until DRBDs have synchronized.
3317

3318
  """
3319
  def _helper(rd):
3320
    stats = rd.GetProcStatus()
3321
    if not (stats.is_connected or stats.is_in_resync):
3322
      raise utils.RetryAgain()
3323
    return stats
3324

    
3325
  bdevs = _FindDisks(nodes_ip, disks)
3326

    
3327
  min_resync = 100
3328
  alldone = True
3329
  for rd in bdevs:
3330
    try:
3331
      # poll each second for 15 seconds
3332
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3333
    except utils.RetryTimeout:
3334
      stats = rd.GetProcStatus()
3335
      # last check
3336
      if not (stats.is_connected or stats.is_in_resync):
3337
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3338
    alldone = alldone and (not stats.is_in_resync)
3339
    if stats.sync_percent is not None:
3340
      min_resync = min(min_resync, stats.sync_percent)
3341

    
3342
  return (alldone, min_resync)
3343

    
3344

    
3345
def GetDrbdUsermodeHelper():
3346
  """Returns DRBD usermode helper currently configured.
3347

3348
  """
3349
  try:
3350
    return bdev.BaseDRBD.GetUsermodeHelper()
3351
  except errors.BlockDeviceError, err:
3352
    _Fail(str(err))
3353

    
3354

    
3355
def PowercycleNode(hypervisor_type):
3356
  """Hard-powercycle the node.
3357

3358
  Because we need to return first, and schedule the powercycle in the
3359
  background, we won't be able to report failures nicely.
3360

3361
  """
3362
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3363
  try:
3364
    pid = os.fork()
3365
  except OSError:
3366
    # if we can't fork, we'll pretend that we're in the child process
3367
    pid = 0
3368
  if pid > 0:
3369
    return "Reboot scheduled in 5 seconds"
3370
  # ensure the child is running on ram
3371
  try:
3372
    utils.Mlockall()
3373
  except Exception: # pylint: disable=W0703
3374
    pass
3375
  time.sleep(5)
3376
  hyper.PowercycleNode()
3377

    
3378

    
3379
class HooksRunner(object):
3380
  """Hook runner.
3381

3382
  This class is instantiated on the node side (ganeti-noded) and not
3383
  on the master side.
3384

3385
  """
3386
  def __init__(self, hooks_base_dir=None):
3387
    """Constructor for hooks runner.
3388

3389
    @type hooks_base_dir: str or None
3390
    @param hooks_base_dir: if not None, this overrides the
3391
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
3392

3393
    """
3394
    if hooks_base_dir is None:
3395
      hooks_base_dir = constants.HOOKS_BASE_DIR
3396
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3397
    # constant
3398
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
3399

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

3403
    """
3404
    assert len(node_list) == 1
3405
    node = node_list[0]
3406
    _, myself = ssconf.GetMasterAndMyself()
3407
    assert node == myself
3408

    
3409
    results = self.RunHooks(hpath, phase, env)
3410

    
3411
    # Return values in the form expected by HooksMaster
3412
    return {node: (None, False, results)}
3413

    
3414
  def RunHooks(self, hpath, phase, env):
3415
    """Run the scripts in the hooks directory.
3416

3417
    @type hpath: str
3418
    @param hpath: the path to the hooks directory which
3419
        holds the scripts
3420
    @type phase: str
3421
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
3422
        L{constants.HOOKS_PHASE_POST}
3423
    @type env: dict
3424
    @param env: dictionary with the environment for the hook
3425
    @rtype: list
3426
    @return: list of 3-element tuples:
3427
      - script path
3428
      - script result, either L{constants.HKR_SUCCESS} or
3429
        L{constants.HKR_FAIL}
3430
      - output of the script
3431

3432
    @raise errors.ProgrammerError: for invalid input
3433
        parameters
3434

3435
    """
3436
    if phase == constants.HOOKS_PHASE_PRE:
3437
      suffix = "pre"
3438
    elif phase == constants.HOOKS_PHASE_POST:
3439
      suffix = "post"
3440
    else:
3441
      _Fail("Unknown hooks phase '%s'", phase)
3442

    
3443
    subdir = "%s-%s.d" % (hpath, suffix)
3444
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3445

    
3446
    results = []
3447

    
3448
    if not os.path.isdir(dir_name):
3449
      # for non-existing/non-dirs, we simply exit instead of logging a
3450
      # warning at every operation
3451
      return results
3452

    
3453
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3454

    
3455
    for (relname, relstatus, runresult)  in runparts_results:
3456
      if relstatus == constants.RUNPARTS_SKIP:
3457
        rrval = constants.HKR_SKIP
3458
        output = ""
3459
      elif relstatus == constants.RUNPARTS_ERR:
3460
        rrval = constants.HKR_FAIL
3461
        output = "Hook script execution error: %s" % runresult
3462
      elif relstatus == constants.RUNPARTS_RUN:
3463
        if runresult.failed:
3464
          rrval = constants.HKR_FAIL
3465
        else:
3466
          rrval = constants.HKR_SUCCESS
3467
        output = utils.SafeEncode(runresult.output.strip())
3468
      results.append(("%s/%s" % (subdir, relname), rrval, output))
3469

    
3470
    return results
3471

    
3472

    
3473
class IAllocatorRunner(object):
3474
  """IAllocator runner.
3475

3476
  This class is instantiated on the node side (ganeti-noded) and not on
3477
  the master side.
3478

3479
  """
3480
  @staticmethod
3481
  def Run(name, idata):
3482
    """Run an iallocator script.
3483

3484
    @type name: str
3485
    @param name: the iallocator script name
3486
    @type idata: str
3487
    @param idata: the allocator input data
3488

3489
    @rtype: tuple
3490
    @return: two element tuple of:
3491
       - status
3492
       - either error message or stdout of allocator (for success)
3493

3494
    """
3495
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
3496
                                  os.path.isfile)
3497
    if alloc_script is None:
3498
      _Fail("iallocator module '%s' not found in the search path", name)
3499

    
3500
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
3501
    try:
3502
      os.write(fd, idata)
3503
      os.close(fd)
3504
      result = utils.RunCmd([alloc_script, fin_name])
3505
      if result.failed:
3506
        _Fail("iallocator module '%s' failed: %s, output '%s'",
3507
              name, result.fail_reason, result.output)
3508
    finally:
3509
      os.unlink(fin_name)
3510

    
3511
    return result.stdout
3512

    
3513

    
3514
class DevCacheManager(object):
3515
  """Simple class for managing a cache of block device information.
3516

3517
  """
3518
  _DEV_PREFIX = "/dev/"
3519
  _ROOT_DIR = constants.BDEV_CACHE_DIR
3520

    
3521
  @classmethod
3522
  def _ConvertPath(cls, dev_path):
3523
    """Converts a /dev/name path to the cache file name.
3524

3525
    This replaces slashes with underscores and strips the /dev
3526
    prefix. It then returns the full path to the cache file.
3527

3528
    @type dev_path: str
3529
    @param dev_path: the C{/dev/} path name
3530
    @rtype: str
3531
    @return: the converted path name
3532

3533
    """
3534
    if dev_path.startswith(cls._DEV_PREFIX):
3535
      dev_path = dev_path[len(cls._DEV_PREFIX):]
3536
    dev_path = dev_path.replace("/", "_")
3537
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
3538
    return fpath
3539

    
3540
  @classmethod
3541
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
3542
    """Updates the cache information for a given device.
3543

3544
    @type dev_path: str
3545
    @param dev_path: the pathname of the device
3546
    @type owner: str
3547
    @param owner: the owner (instance name) of the device
3548
    @type on_primary: bool
3549
    @param on_primary: whether this is the primary
3550
        node nor not
3551
    @type iv_name: str
3552
    @param iv_name: the instance-visible name of the
3553
        device, as in objects.Disk.iv_name
3554

3555
    @rtype: None
3556

3557
    """
3558
    if dev_path is None:
3559
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
3560
      return
3561
    fpath = cls._ConvertPath(dev_path)
3562
    if on_primary:
3563
      state = "primary"
3564
    else:
3565
      state = "secondary"
3566
    if iv_name is None:
3567
      iv_name = "not_visible"
3568
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
3569
    try:
3570
      utils.WriteFile(fpath, data=fdata)
3571
    except EnvironmentError, err:
3572
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
3573

    
3574
  @classmethod
3575
  def RemoveCache(cls, dev_path):
3576
    """Remove data for a dev_path.
3577

3578
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
3579
    path name and logging.
3580

3581
    @type dev_path: str
3582
    @param dev_path: the pathname of the device
3583

3584
    @rtype: None
3585

3586
    """
3587
    if dev_path is None:
3588
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
3589
      return
3590
    fpath = cls._ConvertPath(dev_path)
3591
    try:
3592
      utils.RemoveFile(fpath)
3593
    except EnvironmentError, err:
3594
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)