Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 9e6014b9

History | View | Annotate | Download (111.5 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
from ganeti import compat
65

    
66

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

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

    
84

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

88
  Its argument is the error message.
89

90
  """
91

    
92

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

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

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

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

    
115

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

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

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

    
125

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

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

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

    
138

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

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

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

    
158

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

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

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

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

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

    
188

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

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

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

    
208
  for hv_name in constants.HYPER_TYPES:
209
    hv_class = hypervisor.GetHypervisorClass(hv_name)
210
    allowed_files.update(hv_class.GetAncillaryFiles()[0])
211

    
212
  return frozenset(allowed_files)
213

    
214

    
215
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
216

    
217

    
218
def JobQueuePurge():
219
  """Removes job queue files and archived jobs.
220

221
  @rtype: tuple
222
  @return: True, None
223

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

    
228

    
229
def GetMasterInfo():
230
  """Returns master information.
231

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

235
  @rtype: tuple
236
  @return: master_netdev, master_ip, master_name, primary_ip_family,
237
    master_netmask
238
  @raise RPCFail: in case of errors
239

240
  """
241
  try:
242
    cfg = _GetConfig()
243
    master_netdev = cfg.GetMasterNetdev()
244
    master_ip = cfg.GetMasterIP()
245
    master_netmask = cfg.GetMasterNetmask()
246
    master_node = cfg.GetMasterNode()
247
    primary_ip_family = cfg.GetPrimaryIPFamily()
248
  except errors.ConfigurationError, err:
249
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
250
  return (master_netdev, master_ip, master_node, primary_ip_family,
251
      master_netmask)
252

    
253

    
254
def RunLocalHooks(hook_opcode, hooks_path, env_builder_fn):
255
  """Decorator that runs hooks before and after the decorated function.
256

257
  @type hook_opcode: string
258
  @param hook_opcode: opcode of the hook
259
  @type hooks_path: string
260
  @param hooks_path: path of the hooks
261
  @type env_builder_fn: function
262
  @param env_builder_fn: function that returns a dictionary containing the
263
    environment variables for the hooks. Will get all the parameters of the
264
    decorated function.
265
  @raise RPCFail: in case of pre-hook failure
266

267
  """
268
  def decorator(fn):
269
    def wrapper(*args, **kwargs):
270
      _, myself = ssconf.GetMasterAndMyself()
271
      nodes = ([myself], [myself])  # these hooks run locally
272

    
273
      env_fn = compat.partial(env_builder_fn, *args, **kwargs)
274

    
275
      cfg = _GetConfig()
276
      hr = HooksRunner()
277
      hm = mcpu.HooksMaster(hook_opcode, hooks_path, nodes, hr.RunLocalHooks,
278
                            None, env_fn, logging.warning, cfg.GetClusterName(),
279
                            cfg.GetMasterNode())
280

    
281
      hm.RunPhase(constants.HOOKS_PHASE_PRE)
282
      result = fn(*args, **kwargs)
283
      hm.RunPhase(constants.HOOKS_PHASE_POST)
284

    
285
      return result
286
    return wrapper
287
  return decorator
288

    
289

    
290
def _BuildMasterIpEnv(master_params):
291
  """Builds environment variables for master IP hooks.
292

293
  @type master_params: L{objects.MasterNetworkParameters}
294
  @param master_params: network parameters of the master
295

296
  """
297
  ver = netutils.IPAddress.GetVersionFromAddressFamily(master_params.ip_family)
298
  env = {
299
    "MASTER_NETDEV": master_params.netdev,
300
    "MASTER_IP": master_params.ip,
301
    "MASTER_NETMASK": master_params.netmask,
302
    "CLUSTER_IP_VERSION": str(ver),
303
  }
304

    
305
  return env
306

    
307

    
308
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNUP, "master-ip-turnup",
309
               _BuildMasterIpEnv)
310
def ActivateMasterIp(master_params):
311
  """Activate the IP address of the master daemon.
312

313
  @type master_params: L{objects.MasterNetworkParameters}
314
  @param master_params: network parameters of the master
315

316
  """
317
  err_msg = None
318
  if netutils.TcpPing(master_params.ip, constants.DEFAULT_NODED_PORT):
319
    if netutils.IPAddress.Own(master_params.ip):
320
      # we already have the ip:
321
      logging.debug("Master IP already configured, doing nothing")
322
    else:
323
      err_msg = "Someone else has the master ip, not activating"
324
      logging.error(err_msg)
325
  else:
326
    ipcls = netutils.IPAddress.GetClassFromIpFamily(master_params.ip_family)
327

    
328
    result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
329
                           "%s/%s" % (master_params.ip, master_params.netmask),
330
                           "dev", master_params.netdev, "label",
331
                           "%s:0" % master_params.netdev])
332
    if result.failed:
333
      err_msg = "Can't activate master IP: %s" % result.output
334
      logging.error(err_msg)
335

    
336
    else:
337
      # we ignore the exit code of the following cmds
338
      if ipcls == netutils.IP4Address:
339
        utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_params.netdev,
340
                      "-s", master_params.ip, master_params.ip])
341
      elif ipcls == netutils.IP6Address:
342
        try:
343
          utils.RunCmd(["ndisc6", "-q", "-r 3", master_params.ip,
344
                        master_params.netdev])
345
        except errors.OpExecError:
346
          # TODO: Better error reporting
347
          logging.warning("Can't execute ndisc6, please install if missing")
348

    
349
  if err_msg:
350
    _Fail(err_msg)
351

    
352

    
353
def StartMasterDaemons(no_voting):
354
  """Activate local node as master node.
355

356
  The function will start the master daemons (ganeti-masterd and ganeti-rapi).
357

358
  @type no_voting: boolean
359
  @param no_voting: whether to start ganeti-masterd without a node vote
360
      but still non-interactively
361
  @rtype: None
362

363
  """
364

    
365
  if no_voting:
366
    masterd_args = "--no-voting --yes-do-it"
367
  else:
368
    masterd_args = ""
369

    
370
  env = {
371
    "EXTRA_MASTERD_ARGS": masterd_args,
372
    }
373

    
374
  result = utils.RunCmd([constants.DAEMON_UTIL, "start-master"], env=env)
375
  if result.failed:
376
    msg = "Can't start Ganeti master: %s" % result.output
377
    logging.error(msg)
378
    _Fail(msg)
379

    
380

    
381
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNDOWN, "master-ip-turndown",
382
               _BuildMasterIpEnv)
383
def DeactivateMasterIp(master_params):
384
  """Deactivate the master IP on this node.
385

386
  @type master_params: L{objects.MasterNetworkParameters}
387
  @param master_params: network parameters of the master
388

389
  """
390
  # TODO: log and report back to the caller the error failures; we
391
  # need to decide in which case we fail the RPC for this
392

    
393
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
394
                         "%s/%s" % (master_params.ip, master_params.netmask),
395
                         "dev", master_params.netdev])
396
  if result.failed:
397
    logging.error("Can't remove the master IP, error: %s", result.output)
398
    # but otherwise ignore the failure
399

    
400

    
401
def StopMasterDaemons():
402
  """Stop the master daemons on this node.
403

404
  Stop the master daemons (ganeti-masterd and ganeti-rapi) on this node.
405

406
  @rtype: None
407

408
  """
409
  # TODO: log and report back to the caller the error failures; we
410
  # need to decide in which case we fail the RPC for this
411

    
412
  result = utils.RunCmd([constants.DAEMON_UTIL, "stop-master"])
413
  if result.failed:
414
    logging.error("Could not stop Ganeti master, command %s had exitcode %s"
415
                  " and error %s",
416
                  result.cmd, result.exit_code, result.output)
417

    
418

    
419
def ChangeMasterNetmask(old_netmask, netmask, master_ip, master_netdev):
420
  """Change the netmask of the master IP.
421

422
  @param old_netmask: the old value of the netmask
423
  @param netmask: the new value of the netmask
424
  @param master_ip: the master IP
425
  @param master_netdev: the master network device
426

427
  """
428
  if old_netmask == netmask:
429
    return
430

    
431
  if not netutils.IPAddress.Own(master_ip):
432
    _Fail("The master IP address is not up, not attempting to change its"
433
          " netmask")
434

    
435
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
436
                         "%s/%s" % (master_ip, netmask),
437
                         "dev", master_netdev, "label",
438
                         "%s:0" % master_netdev])
439
  if result.failed:
440
    _Fail("Could not set the new netmask on the master IP address")
441

    
442
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
443
                         "%s/%s" % (master_ip, old_netmask),
444
                         "dev", master_netdev, "label",
445
                         "%s:0" % master_netdev])
446
  if result.failed:
447
    _Fail("Could not bring down the master IP address with the old netmask")
448

    
449

    
450
def EtcHostsModify(mode, host, ip):
451
  """Modify a host entry in /etc/hosts.
452

453
  @param mode: The mode to operate. Either add or remove entry
454
  @param host: The host to operate on
455
  @param ip: The ip associated with the entry
456

457
  """
458
  if mode == constants.ETC_HOSTS_ADD:
459
    if not ip:
460
      RPCFail("Mode 'add' needs 'ip' parameter, but parameter not"
461
              " present")
462
    utils.AddHostToEtcHosts(host, ip)
463
  elif mode == constants.ETC_HOSTS_REMOVE:
464
    if ip:
465
      RPCFail("Mode 'remove' does not allow 'ip' parameter, but"
466
              " parameter is present")
467
    utils.RemoveHostFromEtcHosts(host)
468
  else:
469
    RPCFail("Mode not supported")
470

    
471

    
472
def LeaveCluster(modify_ssh_setup):
473
  """Cleans up and remove the current node.
474

475
  This function cleans up and prepares the current node to be removed
476
  from the cluster.
477

478
  If processing is successful, then it raises an
479
  L{errors.QuitGanetiException} which is used as a special case to
480
  shutdown the node daemon.
481

482
  @param modify_ssh_setup: boolean
483

484
  """
485
  _CleanDirectory(constants.DATA_DIR)
486
  _CleanDirectory(constants.CRYPTO_KEYS_DIR)
487
  JobQueuePurge()
488

    
489
  if modify_ssh_setup:
490
    try:
491
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
492

    
493
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
494

    
495
      utils.RemoveFile(priv_key)
496
      utils.RemoveFile(pub_key)
497
    except errors.OpExecError:
498
      logging.exception("Error while processing ssh files")
499

    
500
  try:
501
    utils.RemoveFile(constants.CONFD_HMAC_KEY)
502
    utils.RemoveFile(constants.RAPI_CERT_FILE)
503
    utils.RemoveFile(constants.SPICE_CERT_FILE)
504
    utils.RemoveFile(constants.SPICE_CACERT_FILE)
505
    utils.RemoveFile(constants.NODED_CERT_FILE)
506
  except: # pylint: disable=W0702
507
    logging.exception("Error while removing cluster secrets")
508

    
509
  result = utils.RunCmd([constants.DAEMON_UTIL, "stop", constants.CONFD])
510
  if result.failed:
511
    logging.error("Command %s failed with exitcode %s and error %s",
512
                  result.cmd, result.exit_code, result.output)
513

    
514
  # Raise a custom exception (handled in ganeti-noded)
515
  raise errors.QuitGanetiException(True, "Shutdown scheduled")
516

    
517

    
518
def GetNodeInfo(vgname, hypervisor_type):
519
  """Gives back a hash with different information about the node.
520

521
  @type vgname: C{string}
522
  @param vgname: the name of the volume group to ask for disk space information
523
  @type hypervisor_type: C{str}
524
  @param hypervisor_type: the name of the hypervisor to ask for
525
      memory information
526
  @rtype: C{dict}
527
  @return: dictionary with the following keys:
528
      - vg_size is the size of the configured volume group in MiB
529
      - vg_free is the free size of the volume group in MiB
530
      - memory_dom0 is the memory allocated for domain0 in MiB
531
      - memory_free is the currently available (free) ram in MiB
532
      - memory_total is the total number of ram in MiB
533
      - hv_version: the hypervisor version, if available
534

535
  """
536
  outputarray = {}
537

    
538
  if vgname is not None:
539
    vginfo = bdev.LogicalVolume.GetVGInfo([vgname])
540
    vg_free = vg_size = None
541
    if vginfo:
542
      vg_free = int(round(vginfo[0][0], 0))
543
      vg_size = int(round(vginfo[0][1], 0))
544
    outputarray["vg_size"] = vg_size
545
    outputarray["vg_free"] = vg_free
546

    
547
  if hypervisor_type is not None:
548
    hyper = hypervisor.GetHypervisor(hypervisor_type)
549
    hyp_info = hyper.GetNodeInfo()
550
    if hyp_info is not None:
551
      outputarray.update(hyp_info)
552

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

    
555
  return outputarray
556

    
557

    
558
def VerifyNode(what, cluster_name):
559
  """Verify the status of the local node.
560

561
  Based on the input L{what} parameter, various checks are done on the
562
  local node.
563

564
  If the I{filelist} key is present, this list of
565
  files is checksummed and the file/checksum pairs are returned.
566

567
  If the I{nodelist} key is present, we check that we have
568
  connectivity via ssh with the target nodes (and check the hostname
569
  report).
570

571
  If the I{node-net-test} key is present, we check that we have
572
  connectivity to the given nodes via both primary IP and, if
573
  applicable, secondary IPs.
574

575
  @type what: C{dict}
576
  @param what: a dictionary of things to check:
577
      - filelist: list of files for which to compute checksums
578
      - nodelist: list of nodes we should check ssh communication with
579
      - node-net-test: list of nodes we should check node daemon port
580
        connectivity with
581
      - hypervisor: list with hypervisors to run the verify for
582
  @rtype: dict
583
  @return: a dictionary with the same keys as the input dict, and
584
      values representing the result of the checks
585

586
  """
587
  result = {}
588
  my_name = netutils.Hostname.GetSysName()
589
  port = netutils.GetDaemonPort(constants.NODED)
590
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
591

    
592
  if constants.NV_HYPERVISOR in what and vm_capable:
593
    result[constants.NV_HYPERVISOR] = tmp = {}
594
    for hv_name in what[constants.NV_HYPERVISOR]:
595
      try:
596
        val = hypervisor.GetHypervisor(hv_name).Verify()
597
      except errors.HypervisorError, err:
598
        val = "Error while checking hypervisor: %s" % str(err)
599
      tmp[hv_name] = val
600

    
601
  if constants.NV_HVPARAMS in what and vm_capable:
602
    result[constants.NV_HVPARAMS] = tmp = []
603
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
604
      try:
605
        logging.info("Validating hv %s, %s", hv_name, hvparms)
606
        hypervisor.GetHypervisor(hv_name).ValidateParameters(hvparms)
607
      except errors.HypervisorError, err:
608
        tmp.append((source, hv_name, str(err)))
609

    
610
  if constants.NV_FILELIST in what:
611
    result[constants.NV_FILELIST] = utils.FingerprintFiles(
612
      what[constants.NV_FILELIST])
613

    
614
  if constants.NV_NODELIST in what:
615
    (nodes, bynode) = what[constants.NV_NODELIST]
616

    
617
    # Add nodes from other groups (different for each node)
618
    try:
619
      nodes.extend(bynode[my_name])
620
    except KeyError:
621
      pass
622

    
623
    # Use a random order
624
    random.shuffle(nodes)
625

    
626
    # Try to contact all nodes
627
    val = {}
628
    for node in nodes:
629
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
630
      if not success:
631
        val[node] = message
632

    
633
    result[constants.NV_NODELIST] = val
634

    
635
  if constants.NV_NODENETTEST in what:
636
    result[constants.NV_NODENETTEST] = tmp = {}
637
    my_pip = my_sip = None
638
    for name, pip, sip in what[constants.NV_NODENETTEST]:
639
      if name == my_name:
640
        my_pip = pip
641
        my_sip = sip
642
        break
643
    if not my_pip:
644
      tmp[my_name] = ("Can't find my own primary/secondary IP"
645
                      " in the node list")
646
    else:
647
      for name, pip, sip in what[constants.NV_NODENETTEST]:
648
        fail = []
649
        if not netutils.TcpPing(pip, port, source=my_pip):
650
          fail.append("primary")
651
        if sip != pip:
652
          if not netutils.TcpPing(sip, port, source=my_sip):
653
            fail.append("secondary")
654
        if fail:
655
          tmp[name] = ("failure using the %s interface(s)" %
656
                       " and ".join(fail))
657

    
658
  if constants.NV_MASTERIP in what:
659
    # FIXME: add checks on incoming data structures (here and in the
660
    # rest of the function)
661
    master_name, master_ip = what[constants.NV_MASTERIP]
662
    if master_name == my_name:
663
      source = constants.IP4_ADDRESS_LOCALHOST
664
    else:
665
      source = None
666
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
667
                                                  source=source)
668

    
669
  if constants.NV_OOB_PATHS in what:
670
    result[constants.NV_OOB_PATHS] = tmp = []
671
    for path in what[constants.NV_OOB_PATHS]:
672
      try:
673
        st = os.stat(path)
674
      except OSError, err:
675
        tmp.append("error stating out of band helper: %s" % err)
676
      else:
677
        if stat.S_ISREG(st.st_mode):
678
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
679
            tmp.append(None)
680
          else:
681
            tmp.append("out of band helper %s is not executable" % path)
682
        else:
683
          tmp.append("out of band helper %s is not a file" % path)
684

    
685
  if constants.NV_LVLIST in what and vm_capable:
686
    try:
687
      val = GetVolumeList(utils.ListVolumeGroups().keys())
688
    except RPCFail, err:
689
      val = str(err)
690
    result[constants.NV_LVLIST] = val
691

    
692
  if constants.NV_INSTANCELIST in what and vm_capable:
693
    # GetInstanceList can fail
694
    try:
695
      val = GetInstanceList(what[constants.NV_INSTANCELIST])
696
    except RPCFail, err:
697
      val = str(err)
698
    result[constants.NV_INSTANCELIST] = val
699

    
700
  if constants.NV_VGLIST in what and vm_capable:
701
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
702

    
703
  if constants.NV_PVLIST in what and vm_capable:
704
    result[constants.NV_PVLIST] = \
705
      bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
706
                                   filter_allocatable=False)
707

    
708
  if constants.NV_VERSION in what:
709
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
710
                                    constants.RELEASE_VERSION)
711

    
712
  if constants.NV_HVINFO in what and vm_capable:
713
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
714
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
715

    
716
  if constants.NV_DRBDLIST in what and vm_capable:
717
    try:
718
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
719
    except errors.BlockDeviceError, err:
720
      logging.warning("Can't get used minors list", exc_info=True)
721
      used_minors = str(err)
722
    result[constants.NV_DRBDLIST] = used_minors
723

    
724
  if constants.NV_DRBDHELPER in what and vm_capable:
725
    status = True
726
    try:
727
      payload = bdev.BaseDRBD.GetUsermodeHelper()
728
    except errors.BlockDeviceError, err:
729
      logging.error("Can't get DRBD usermode helper: %s", str(err))
730
      status = False
731
      payload = str(err)
732
    result[constants.NV_DRBDHELPER] = (status, payload)
733

    
734
  if constants.NV_NODESETUP in what:
735
    result[constants.NV_NODESETUP] = tmpr = []
736
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
737
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
738
                  " under /sys, missing required directories /sys/block"
739
                  " and /sys/class/net")
740
    if (not os.path.isdir("/proc/sys") or
741
        not os.path.isfile("/proc/sysrq-trigger")):
742
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
743
                  " under /proc, missing required directory /proc/sys and"
744
                  " the file /proc/sysrq-trigger")
745

    
746
  if constants.NV_TIME in what:
747
    result[constants.NV_TIME] = utils.SplitTime(time.time())
748

    
749
  if constants.NV_OSLIST in what and vm_capable:
750
    result[constants.NV_OSLIST] = DiagnoseOS()
751

    
752
  if constants.NV_BRIDGES in what and vm_capable:
753
    result[constants.NV_BRIDGES] = [bridge
754
                                    for bridge in what[constants.NV_BRIDGES]
755
                                    if not utils.BridgeExists(bridge)]
756
  return result
757

    
758

    
759
def GetBlockDevSizes(devices):
760
  """Return the size of the given block devices
761

762
  @type devices: list
763
  @param devices: list of block device nodes to query
764
  @rtype: dict
765
  @return:
766
    dictionary of all block devices under /dev (key). The value is their
767
    size in MiB.
768

769
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
770

771
  """
772
  DEV_PREFIX = "/dev/"
773
  blockdevs = {}
774

    
775
  for devpath in devices:
776
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
777
      continue
778

    
779
    try:
780
      st = os.stat(devpath)
781
    except EnvironmentError, err:
782
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
783
      continue
784

    
785
    if stat.S_ISBLK(st.st_mode):
786
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
787
      if result.failed:
788
        # We don't want to fail, just do not list this device as available
789
        logging.warning("Cannot get size for block device %s", devpath)
790
        continue
791

    
792
      size = int(result.stdout) / (1024 * 1024)
793
      blockdevs[devpath] = size
794
  return blockdevs
795

    
796

    
797
def GetVolumeList(vg_names):
798
  """Compute list of logical volumes and their size.
799

800
  @type vg_names: list
801
  @param vg_names: the volume groups whose LVs we should list, or
802
      empty for all volume groups
803
  @rtype: dict
804
  @return:
805
      dictionary of all partions (key) with value being a tuple of
806
      their size (in MiB), inactive and online status::
807

808
        {'xenvg/test1': ('20.06', True, True)}
809

810
      in case of errors, a string is returned with the error
811
      details.
812

813
  """
814
  lvs = {}
815
  sep = "|"
816
  if not vg_names:
817
    vg_names = []
818
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
819
                         "--separator=%s" % sep,
820
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
821
  if result.failed:
822
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
823

    
824
  for line in result.stdout.splitlines():
825
    line = line.strip()
826
    match = _LVSLINE_REGEX.match(line)
827
    if not match:
828
      logging.error("Invalid line returned from lvs output: '%s'", line)
829
      continue
830
    vg_name, name, size, attr = match.groups()
831
    inactive = attr[4] == "-"
832
    online = attr[5] == "o"
833
    virtual = attr[0] == "v"
834
    if virtual:
835
      # we don't want to report such volumes as existing, since they
836
      # don't really hold data
837
      continue
838
    lvs[vg_name + "/" + name] = (size, inactive, online)
839

    
840
  return lvs
841

    
842

    
843
def ListVolumeGroups():
844
  """List the volume groups and their size.
845

846
  @rtype: dict
847
  @return: dictionary with keys volume name and values the
848
      size of the volume
849

850
  """
851
  return utils.ListVolumeGroups()
852

    
853

    
854
def NodeVolumes():
855
  """List all volumes on this node.
856

857
  @rtype: list
858
  @return:
859
    A list of dictionaries, each having four keys:
860
      - name: the logical volume name,
861
      - size: the size of the logical volume
862
      - dev: the physical device on which the LV lives
863
      - vg: the volume group to which it belongs
864

865
    In case of errors, we return an empty list and log the
866
    error.
867

868
    Note that since a logical volume can live on multiple physical
869
    volumes, the resulting list might include a logical volume
870
    multiple times.
871

872
  """
873
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
874
                         "--separator=|",
875
                         "--options=lv_name,lv_size,devices,vg_name"])
876
  if result.failed:
877
    _Fail("Failed to list logical volumes, lvs output: %s",
878
          result.output)
879

    
880
  def parse_dev(dev):
881
    return dev.split("(")[0]
882

    
883
  def handle_dev(dev):
884
    return [parse_dev(x) for x in dev.split(",")]
885

    
886
  def map_line(line):
887
    line = [v.strip() for v in line]
888
    return [{"name": line[0], "size": line[1],
889
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
890

    
891
  all_devs = []
892
  for line in result.stdout.splitlines():
893
    if line.count("|") >= 3:
894
      all_devs.extend(map_line(line.split("|")))
895
    else:
896
      logging.warning("Strange line in the output from lvs: '%s'", line)
897
  return all_devs
898

    
899

    
900
def BridgesExist(bridges_list):
901
  """Check if a list of bridges exist on the current node.
902

903
  @rtype: boolean
904
  @return: C{True} if all of them exist, C{False} otherwise
905

906
  """
907
  missing = []
908
  for bridge in bridges_list:
909
    if not utils.BridgeExists(bridge):
910
      missing.append(bridge)
911

    
912
  if missing:
913
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
914

    
915

    
916
def GetInstanceList(hypervisor_list):
917
  """Provides a list of instances.
918

919
  @type hypervisor_list: list
920
  @param hypervisor_list: the list of hypervisors to query information
921

922
  @rtype: list
923
  @return: a list of all running instances on the current node
924
    - instance1.example.com
925
    - instance2.example.com
926

927
  """
928
  results = []
929
  for hname in hypervisor_list:
930
    try:
931
      names = hypervisor.GetHypervisor(hname).ListInstances()
932
      results.extend(names)
933
    except errors.HypervisorError, err:
934
      _Fail("Error enumerating instances (hypervisor %s): %s",
935
            hname, err, exc=True)
936

    
937
  return results
938

    
939

    
940
def GetInstanceInfo(instance, hname):
941
  """Gives back the information about an instance as a dictionary.
942

943
  @type instance: string
944
  @param instance: the instance name
945
  @type hname: string
946
  @param hname: the hypervisor type of the instance
947

948
  @rtype: dict
949
  @return: dictionary with the following keys:
950
      - memory: memory size of instance (int)
951
      - state: xen state of instance (string)
952
      - time: cpu time of instance (float)
953

954
  """
955
  output = {}
956

    
957
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
958
  if iinfo is not None:
959
    output["memory"] = iinfo[2]
960
    output["state"] = iinfo[4]
961
    output["time"] = iinfo[5]
962

    
963
  return output
964

    
965

    
966
def GetInstanceMigratable(instance):
967
  """Gives whether an instance can be migrated.
968

969
  @type instance: L{objects.Instance}
970
  @param instance: object representing the instance to be checked.
971

972
  @rtype: tuple
973
  @return: tuple of (result, description) where:
974
      - result: whether the instance can be migrated or not
975
      - description: a description of the issue, if relevant
976

977
  """
978
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
979
  iname = instance.name
980
  if iname not in hyper.ListInstances():
981
    _Fail("Instance %s is not running", iname)
982

    
983
  for idx in range(len(instance.disks)):
984
    link_name = _GetBlockDevSymlinkPath(iname, idx)
985
    if not os.path.islink(link_name):
986
      logging.warning("Instance %s is missing symlink %s for disk %d",
987
                      iname, link_name, idx)
988

    
989

    
990
def GetAllInstancesInfo(hypervisor_list):
991
  """Gather data about all instances.
992

993
  This is the equivalent of L{GetInstanceInfo}, except that it
994
  computes data for all instances at once, thus being faster if one
995
  needs data about more than one instance.
996

997
  @type hypervisor_list: list
998
  @param hypervisor_list: list of hypervisors to query for instance data
999

1000
  @rtype: dict
1001
  @return: dictionary of instance: data, with data having the following keys:
1002
      - memory: memory size of instance (int)
1003
      - state: xen state of instance (string)
1004
      - time: cpu time of instance (float)
1005
      - vcpus: the number of vcpus
1006

1007
  """
1008
  output = {}
1009

    
1010
  for hname in hypervisor_list:
1011
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
1012
    if iinfo:
1013
      for name, _, memory, vcpus, state, times in iinfo:
1014
        value = {
1015
          "memory": memory,
1016
          "vcpus": vcpus,
1017
          "state": state,
1018
          "time": times,
1019
          }
1020
        if name in output:
1021
          # we only check static parameters, like memory and vcpus,
1022
          # and not state and time which can change between the
1023
          # invocations of the different hypervisors
1024
          for key in "memory", "vcpus":
1025
            if value[key] != output[name][key]:
1026
              _Fail("Instance %s is running twice"
1027
                    " with different parameters", name)
1028
        output[name] = value
1029

    
1030
  return output
1031

    
1032

    
1033
def _InstanceLogName(kind, os_name, instance, component):
1034
  """Compute the OS log filename for a given instance and operation.
1035

1036
  The instance name and os name are passed in as strings since not all
1037
  operations have these as part of an instance object.
1038

1039
  @type kind: string
1040
  @param kind: the operation type (e.g. add, import, etc.)
1041
  @type os_name: string
1042
  @param os_name: the os name
1043
  @type instance: string
1044
  @param instance: the name of the instance being imported/added/etc.
1045
  @type component: string or None
1046
  @param component: the name of the component of the instance being
1047
      transferred
1048

1049
  """
1050
  # TODO: Use tempfile.mkstemp to create unique filename
1051
  if component:
1052
    assert "/" not in component
1053
    c_msg = "-%s" % component
1054
  else:
1055
    c_msg = ""
1056
  base = ("%s-%s-%s%s-%s.log" %
1057
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1058
  return utils.PathJoin(constants.LOG_OS_DIR, base)
1059

    
1060

    
1061
def InstanceOsAdd(instance, reinstall, debug):
1062
  """Add an OS to an instance.
1063

1064
  @type instance: L{objects.Instance}
1065
  @param instance: Instance whose OS is to be installed
1066
  @type reinstall: boolean
1067
  @param reinstall: whether this is an instance reinstall
1068
  @type debug: integer
1069
  @param debug: debug level, passed to the OS scripts
1070
  @rtype: None
1071

1072
  """
1073
  inst_os = OSFromDisk(instance.os)
1074

    
1075
  create_env = OSEnvironment(instance, inst_os, debug)
1076
  if reinstall:
1077
    create_env["INSTANCE_REINSTALL"] = "1"
1078

    
1079
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1080

    
1081
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1082
                        cwd=inst_os.path, output=logfile, reset_env=True)
1083
  if result.failed:
1084
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1085
                  " output: %s", result.cmd, result.fail_reason, logfile,
1086
                  result.output)
1087
    lines = [utils.SafeEncode(val)
1088
             for val in utils.TailFile(logfile, lines=20)]
1089
    _Fail("OS create script failed (%s), last lines in the"
1090
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1091

    
1092

    
1093
def RunRenameInstance(instance, old_name, debug):
1094
  """Run the OS rename script for an instance.
1095

1096
  @type instance: L{objects.Instance}
1097
  @param instance: Instance whose OS is to be installed
1098
  @type old_name: string
1099
  @param old_name: previous instance name
1100
  @type debug: integer
1101
  @param debug: debug level, passed to the OS scripts
1102
  @rtype: boolean
1103
  @return: the success of the operation
1104

1105
  """
1106
  inst_os = OSFromDisk(instance.os)
1107

    
1108
  rename_env = OSEnvironment(instance, inst_os, debug)
1109
  rename_env["OLD_INSTANCE_NAME"] = old_name
1110

    
1111
  logfile = _InstanceLogName("rename", instance.os,
1112
                             "%s-%s" % (old_name, instance.name), None)
1113

    
1114
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1115
                        cwd=inst_os.path, output=logfile, reset_env=True)
1116

    
1117
  if result.failed:
1118
    logging.error("os create command '%s' returned error: %s output: %s",
1119
                  result.cmd, result.fail_reason, result.output)
1120
    lines = [utils.SafeEncode(val)
1121
             for val in utils.TailFile(logfile, lines=20)]
1122
    _Fail("OS rename script failed (%s), last lines in the"
1123
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1124

    
1125

    
1126
def _GetBlockDevSymlinkPath(instance_name, idx):
1127
  return utils.PathJoin(constants.DISK_LINKS_DIR, "%s%s%d" %
1128
                        (instance_name, constants.DISK_SEPARATOR, idx))
1129

    
1130

    
1131
def _SymlinkBlockDev(instance_name, device_path, idx):
1132
  """Set up symlinks to a instance's block device.
1133

1134
  This is an auxiliary function run when an instance is start (on the primary
1135
  node) or when an instance is migrated (on the target node).
1136

1137

1138
  @param instance_name: the name of the target instance
1139
  @param device_path: path of the physical block device, on the node
1140
  @param idx: the disk index
1141
  @return: absolute path to the disk's symlink
1142

1143
  """
1144
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1145
  try:
1146
    os.symlink(device_path, link_name)
1147
  except OSError, err:
1148
    if err.errno == errno.EEXIST:
1149
      if (not os.path.islink(link_name) or
1150
          os.readlink(link_name) != device_path):
1151
        os.remove(link_name)
1152
        os.symlink(device_path, link_name)
1153
    else:
1154
      raise
1155

    
1156
  return link_name
1157

    
1158

    
1159
def _RemoveBlockDevLinks(instance_name, disks):
1160
  """Remove the block device symlinks belonging to the given instance.
1161

1162
  """
1163
  for idx, _ in enumerate(disks):
1164
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1165
    if os.path.islink(link_name):
1166
      try:
1167
        os.remove(link_name)
1168
      except OSError:
1169
        logging.exception("Can't remove symlink '%s'", link_name)
1170

    
1171

    
1172
def _GatherAndLinkBlockDevs(instance):
1173
  """Set up an instance's block device(s).
1174

1175
  This is run on the primary node at instance startup. The block
1176
  devices must be already assembled.
1177

1178
  @type instance: L{objects.Instance}
1179
  @param instance: the instance whose disks we shoul assemble
1180
  @rtype: list
1181
  @return: list of (disk_object, device_path)
1182

1183
  """
1184
  block_devices = []
1185
  for idx, disk in enumerate(instance.disks):
1186
    device = _RecursiveFindBD(disk)
1187
    if device is None:
1188
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1189
                                    str(disk))
1190
    device.Open()
1191
    try:
1192
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1193
    except OSError, e:
1194
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1195
                                    e.strerror)
1196

    
1197
    block_devices.append((disk, link_name))
1198

    
1199
  return block_devices
1200

    
1201

    
1202
def StartInstance(instance, startup_paused):
1203
  """Start an instance.
1204

1205
  @type instance: L{objects.Instance}
1206
  @param instance: the instance object
1207
  @type startup_paused: bool
1208
  @param instance: pause instance at startup?
1209
  @rtype: None
1210

1211
  """
1212
  running_instances = GetInstanceList([instance.hypervisor])
1213

    
1214
  if instance.name in running_instances:
1215
    logging.info("Instance %s already running, not starting", instance.name)
1216
    return
1217

    
1218
  try:
1219
    block_devices = _GatherAndLinkBlockDevs(instance)
1220
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1221
    hyper.StartInstance(instance, block_devices, startup_paused)
1222
  except errors.BlockDeviceError, err:
1223
    _Fail("Block device error: %s", err, exc=True)
1224
  except errors.HypervisorError, err:
1225
    _RemoveBlockDevLinks(instance.name, instance.disks)
1226
    _Fail("Hypervisor error: %s", err, exc=True)
1227

    
1228

    
1229
def InstanceShutdown(instance, timeout):
1230
  """Shut an instance down.
1231

1232
  @note: this functions uses polling with a hardcoded timeout.
1233

1234
  @type instance: L{objects.Instance}
1235
  @param instance: the instance object
1236
  @type timeout: integer
1237
  @param timeout: maximum timeout for soft shutdown
1238
  @rtype: None
1239

1240
  """
1241
  hv_name = instance.hypervisor
1242
  hyper = hypervisor.GetHypervisor(hv_name)
1243
  iname = instance.name
1244

    
1245
  if instance.name not in hyper.ListInstances():
1246
    logging.info("Instance %s not running, doing nothing", iname)
1247
    return
1248

    
1249
  class _TryShutdown:
1250
    def __init__(self):
1251
      self.tried_once = False
1252

    
1253
    def __call__(self):
1254
      if iname not in hyper.ListInstances():
1255
        return
1256

    
1257
      try:
1258
        hyper.StopInstance(instance, retry=self.tried_once)
1259
      except errors.HypervisorError, err:
1260
        if iname not in hyper.ListInstances():
1261
          # if the instance is no longer existing, consider this a
1262
          # success and go to cleanup
1263
          return
1264

    
1265
        _Fail("Failed to stop instance %s: %s", iname, err)
1266

    
1267
      self.tried_once = True
1268

    
1269
      raise utils.RetryAgain()
1270

    
1271
  try:
1272
    utils.Retry(_TryShutdown(), 5, timeout)
1273
  except utils.RetryTimeout:
1274
    # the shutdown did not succeed
1275
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1276

    
1277
    try:
1278
      hyper.StopInstance(instance, force=True)
1279
    except errors.HypervisorError, err:
1280
      if iname in hyper.ListInstances():
1281
        # only raise an error if the instance still exists, otherwise
1282
        # the error could simply be "instance ... unknown"!
1283
        _Fail("Failed to force stop instance %s: %s", iname, err)
1284

    
1285
    time.sleep(1)
1286

    
1287
    if iname in hyper.ListInstances():
1288
      _Fail("Could not shutdown instance %s even by destroy", iname)
1289

    
1290
  try:
1291
    hyper.CleanupInstance(instance.name)
1292
  except errors.HypervisorError, err:
1293
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1294

    
1295
  _RemoveBlockDevLinks(iname, instance.disks)
1296

    
1297

    
1298
def InstanceReboot(instance, reboot_type, shutdown_timeout):
1299
  """Reboot an instance.
1300

1301
  @type instance: L{objects.Instance}
1302
  @param instance: the instance object to reboot
1303
  @type reboot_type: str
1304
  @param reboot_type: the type of reboot, one the following
1305
    constants:
1306
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1307
        instance OS, do not recreate the VM
1308
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1309
        restart the VM (at the hypervisor level)
1310
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1311
        not accepted here, since that mode is handled differently, in
1312
        cmdlib, and translates into full stop and start of the
1313
        instance (instead of a call_instance_reboot RPC)
1314
  @type shutdown_timeout: integer
1315
  @param shutdown_timeout: maximum timeout for soft shutdown
1316
  @rtype: None
1317

1318
  """
1319
  running_instances = GetInstanceList([instance.hypervisor])
1320

    
1321
  if instance.name not in running_instances:
1322
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1323

    
1324
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1325
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1326
    try:
1327
      hyper.RebootInstance(instance)
1328
    except errors.HypervisorError, err:
1329
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1330
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1331
    try:
1332
      InstanceShutdown(instance, shutdown_timeout)
1333
      return StartInstance(instance, False)
1334
    except errors.HypervisorError, err:
1335
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1336
  else:
1337
    _Fail("Invalid reboot_type received: %s", reboot_type)
1338

    
1339

    
1340
def MigrationInfo(instance):
1341
  """Gather information about an instance to be migrated.
1342

1343
  @type instance: L{objects.Instance}
1344
  @param instance: the instance definition
1345

1346
  """
1347
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1348
  try:
1349
    info = hyper.MigrationInfo(instance)
1350
  except errors.HypervisorError, err:
1351
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1352
  return info
1353

    
1354

    
1355
def AcceptInstance(instance, info, target):
1356
  """Prepare the node to accept an instance.
1357

1358
  @type instance: L{objects.Instance}
1359
  @param instance: the instance definition
1360
  @type info: string/data (opaque)
1361
  @param info: migration information, from the source node
1362
  @type target: string
1363
  @param target: target host (usually ip), on this node
1364

1365
  """
1366
  # TODO: why is this required only for DTS_EXT_MIRROR?
1367
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1368
    # Create the symlinks, as the disks are not active
1369
    # in any way
1370
    try:
1371
      _GatherAndLinkBlockDevs(instance)
1372
    except errors.BlockDeviceError, err:
1373
      _Fail("Block device error: %s", err, exc=True)
1374

    
1375
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1376
  try:
1377
    hyper.AcceptInstance(instance, info, target)
1378
  except errors.HypervisorError, err:
1379
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1380
      _RemoveBlockDevLinks(instance.name, instance.disks)
1381
    _Fail("Failed to accept instance: %s", err, exc=True)
1382

    
1383

    
1384
def FinalizeMigrationDst(instance, info, success):
1385
  """Finalize any preparation to accept an instance.
1386

1387
  @type instance: L{objects.Instance}
1388
  @param instance: the instance definition
1389
  @type info: string/data (opaque)
1390
  @param info: migration information, from the source node
1391
  @type success: boolean
1392
  @param success: whether the migration was a success or a failure
1393

1394
  """
1395
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1396
  try:
1397
    hyper.FinalizeMigrationDst(instance, info, success)
1398
  except errors.HypervisorError, err:
1399
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1400

    
1401

    
1402
def MigrateInstance(instance, target, live):
1403
  """Migrates an instance to another node.
1404

1405
  @type instance: L{objects.Instance}
1406
  @param instance: the instance definition
1407
  @type target: string
1408
  @param target: the target node name
1409
  @type live: boolean
1410
  @param live: whether the migration should be done live or not (the
1411
      interpretation of this parameter is left to the hypervisor)
1412
  @raise RPCFail: if migration fails for some reason
1413

1414
  """
1415
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1416

    
1417
  try:
1418
    hyper.MigrateInstance(instance, target, live)
1419
  except errors.HypervisorError, err:
1420
    _Fail("Failed to migrate instance: %s", err, exc=True)
1421

    
1422

    
1423
def FinalizeMigrationSource(instance, success, live):
1424
  """Finalize the instance migration on the source node.
1425

1426
  @type instance: L{objects.Instance}
1427
  @param instance: the instance definition of the migrated instance
1428
  @type success: bool
1429
  @param success: whether the migration succeeded or not
1430
  @type live: bool
1431
  @param live: whether the user requested a live migration or not
1432
  @raise RPCFail: If the execution fails for some reason
1433

1434
  """
1435
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1436

    
1437
  try:
1438
    hyper.FinalizeMigrationSource(instance, success, live)
1439
  except Exception, err:  # pylint: disable=W0703
1440
    _Fail("Failed to finalize the migration on the source node: %s", err,
1441
          exc=True)
1442

    
1443

    
1444
def GetMigrationStatus(instance):
1445
  """Get the migration status
1446

1447
  @type instance: L{objects.Instance}
1448
  @param instance: the instance that is being migrated
1449
  @rtype: L{objects.MigrationStatus}
1450
  @return: the status of the current migration (one of
1451
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1452
           progress info that can be retrieved from the hypervisor
1453
  @raise RPCFail: If the migration status cannot be retrieved
1454

1455
  """
1456
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1457
  try:
1458
    return hyper.GetMigrationStatus(instance)
1459
  except Exception, err:  # pylint: disable=W0703
1460
    _Fail("Failed to get migration status: %s", err, exc=True)
1461

    
1462

    
1463
def BlockdevCreate(disk, size, owner, on_primary, info):
1464
  """Creates a block device for an instance.
1465

1466
  @type disk: L{objects.Disk}
1467
  @param disk: the object describing the disk we should create
1468
  @type size: int
1469
  @param size: the size of the physical underlying device, in MiB
1470
  @type owner: str
1471
  @param owner: the name of the instance for which disk is created,
1472
      used for device cache data
1473
  @type on_primary: boolean
1474
  @param on_primary:  indicates if it is the primary node or not
1475
  @type info: string
1476
  @param info: string that will be sent to the physical device
1477
      creation, used for example to set (LVM) tags on LVs
1478

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

1483
  """
1484
  # TODO: remove the obsolete "size" argument
1485
  # pylint: disable=W0613
1486
  clist = []
1487
  if disk.children:
1488
    for child in disk.children:
1489
      try:
1490
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1491
      except errors.BlockDeviceError, err:
1492
        _Fail("Can't assemble device %s: %s", child, err)
1493
      if on_primary or disk.AssembleOnSecondary():
1494
        # we need the children open in case the device itself has to
1495
        # be assembled
1496
        try:
1497
          # pylint: disable=E1103
1498
          crdev.Open()
1499
        except errors.BlockDeviceError, err:
1500
          _Fail("Can't make child '%s' read-write: %s", child, err)
1501
      clist.append(crdev)
1502

    
1503
  try:
1504
    device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
1505
  except errors.BlockDeviceError, err:
1506
    _Fail("Can't create block device: %s", err)
1507

    
1508
  if on_primary or disk.AssembleOnSecondary():
1509
    try:
1510
      device.Assemble()
1511
    except errors.BlockDeviceError, err:
1512
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1513
    device.SetSyncSpeed(constants.SYNC_SPEED)
1514
    if on_primary or disk.OpenOnSecondary():
1515
      try:
1516
        device.Open(force=True)
1517
      except errors.BlockDeviceError, err:
1518
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1519
    DevCacheManager.UpdateCache(device.dev_path, owner,
1520
                                on_primary, disk.iv_name)
1521

    
1522
  device.SetInfo(info)
1523

    
1524
  return device.unique_id
1525

    
1526

    
1527
def _WipeDevice(path, offset, size):
1528
  """This function actually wipes the device.
1529

1530
  @param path: The path to the device to wipe
1531
  @param offset: The offset in MiB in the file
1532
  @param size: The size in MiB to write
1533

1534
  """
1535
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1536
         "bs=%d" % constants.WIPE_BLOCK_SIZE, "oflag=direct", "of=%s" % path,
1537
         "count=%d" % size]
1538
  result = utils.RunCmd(cmd)
1539

    
1540
  if result.failed:
1541
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1542
          result.fail_reason, result.output)
1543

    
1544

    
1545
def BlockdevWipe(disk, offset, size):
1546
  """Wipes a block device.
1547

1548
  @type disk: L{objects.Disk}
1549
  @param disk: the disk object we want to wipe
1550
  @type offset: int
1551
  @param offset: The offset in MiB in the file
1552
  @type size: int
1553
  @param size: The size in MiB to write
1554

1555
  """
1556
  try:
1557
    rdev = _RecursiveFindBD(disk)
1558
  except errors.BlockDeviceError:
1559
    rdev = None
1560

    
1561
  if not rdev:
1562
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1563

    
1564
  # Do cross verify some of the parameters
1565
  if offset > rdev.size:
1566
    _Fail("Offset is bigger than device size")
1567
  if (offset + size) > rdev.size:
1568
    _Fail("The provided offset and size to wipe is bigger than device size")
1569

    
1570
  _WipeDevice(rdev.dev_path, offset, size)
1571

    
1572

    
1573
def BlockdevPauseResumeSync(disks, pause):
1574
  """Pause or resume the sync of the block device.
1575

1576
  @type disks: list of L{objects.Disk}
1577
  @param disks: the disks object we want to pause/resume
1578
  @type pause: bool
1579
  @param pause: Wheater to pause or resume
1580

1581
  """
1582
  success = []
1583
  for disk in disks:
1584
    try:
1585
      rdev = _RecursiveFindBD(disk)
1586
    except errors.BlockDeviceError:
1587
      rdev = None
1588

    
1589
    if not rdev:
1590
      success.append((False, ("Cannot change sync for device %s:"
1591
                              " device not found" % disk.iv_name)))
1592
      continue
1593

    
1594
    result = rdev.PauseResumeSync(pause)
1595

    
1596
    if result:
1597
      success.append((result, None))
1598
    else:
1599
      if pause:
1600
        msg = "Pause"
1601
      else:
1602
        msg = "Resume"
1603
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1604

    
1605
  return success
1606

    
1607

    
1608
def BlockdevRemove(disk):
1609
  """Remove a block device.
1610

1611
  @note: This is intended to be called recursively.
1612

1613
  @type disk: L{objects.Disk}
1614
  @param disk: the disk object we should remove
1615
  @rtype: boolean
1616
  @return: the success of the operation
1617

1618
  """
1619
  msgs = []
1620
  try:
1621
    rdev = _RecursiveFindBD(disk)
1622
  except errors.BlockDeviceError, err:
1623
    # probably can't attach
1624
    logging.info("Can't attach to device %s in remove", disk)
1625
    rdev = None
1626
  if rdev is not None:
1627
    r_path = rdev.dev_path
1628
    try:
1629
      rdev.Remove()
1630
    except errors.BlockDeviceError, err:
1631
      msgs.append(str(err))
1632
    if not msgs:
1633
      DevCacheManager.RemoveCache(r_path)
1634

    
1635
  if disk.children:
1636
    for child in disk.children:
1637
      try:
1638
        BlockdevRemove(child)
1639
      except RPCFail, err:
1640
        msgs.append(str(err))
1641

    
1642
  if msgs:
1643
    _Fail("; ".join(msgs))
1644

    
1645

    
1646
def _RecursiveAssembleBD(disk, owner, as_primary):
1647
  """Activate a block device for an instance.
1648

1649
  This is run on the primary and secondary nodes for an instance.
1650

1651
  @note: this function is called recursively.
1652

1653
  @type disk: L{objects.Disk}
1654
  @param disk: the disk we try to assemble
1655
  @type owner: str
1656
  @param owner: the name of the instance which owns the disk
1657
  @type as_primary: boolean
1658
  @param as_primary: if we should make the block device
1659
      read/write
1660

1661
  @return: the assembled device or None (in case no device
1662
      was assembled)
1663
  @raise errors.BlockDeviceError: in case there is an error
1664
      during the activation of the children or the device
1665
      itself
1666

1667
  """
1668
  children = []
1669
  if disk.children:
1670
    mcn = disk.ChildrenNeeded()
1671
    if mcn == -1:
1672
      mcn = 0 # max number of Nones allowed
1673
    else:
1674
      mcn = len(disk.children) - mcn # max number of Nones
1675
    for chld_disk in disk.children:
1676
      try:
1677
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1678
      except errors.BlockDeviceError, err:
1679
        if children.count(None) >= mcn:
1680
          raise
1681
        cdev = None
1682
        logging.error("Error in child activation (but continuing): %s",
1683
                      str(err))
1684
      children.append(cdev)
1685

    
1686
  if as_primary or disk.AssembleOnSecondary():
1687
    r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
1688
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1689
    result = r_dev
1690
    if as_primary or disk.OpenOnSecondary():
1691
      r_dev.Open()
1692
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1693
                                as_primary, disk.iv_name)
1694

    
1695
  else:
1696
    result = True
1697
  return result
1698

    
1699

    
1700
def BlockdevAssemble(disk, owner, as_primary, idx):
1701
  """Activate a block device for an instance.
1702

1703
  This is a wrapper over _RecursiveAssembleBD.
1704

1705
  @rtype: str or boolean
1706
  @return: a C{/dev/...} path for primary nodes, and
1707
      C{True} for secondary nodes
1708

1709
  """
1710
  try:
1711
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1712
    if isinstance(result, bdev.BlockDev):
1713
      # pylint: disable=E1103
1714
      result = result.dev_path
1715
      if as_primary:
1716
        _SymlinkBlockDev(owner, result, idx)
1717
  except errors.BlockDeviceError, err:
1718
    _Fail("Error while assembling disk: %s", err, exc=True)
1719
  except OSError, err:
1720
    _Fail("Error while symlinking disk: %s", err, exc=True)
1721

    
1722
  return result
1723

    
1724

    
1725
def BlockdevShutdown(disk):
1726
  """Shut down a block device.
1727

1728
  First, if the device is assembled (Attach() is successful), then
1729
  the device is shutdown. Then the children of the device are
1730
  shutdown.
1731

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

1736
  @type disk: L{objects.Disk}
1737
  @param disk: the description of the disk we should
1738
      shutdown
1739
  @rtype: None
1740

1741
  """
1742
  msgs = []
1743
  r_dev = _RecursiveFindBD(disk)
1744
  if r_dev is not None:
1745
    r_path = r_dev.dev_path
1746
    try:
1747
      r_dev.Shutdown()
1748
      DevCacheManager.RemoveCache(r_path)
1749
    except errors.BlockDeviceError, err:
1750
      msgs.append(str(err))
1751

    
1752
  if disk.children:
1753
    for child in disk.children:
1754
      try:
1755
        BlockdevShutdown(child)
1756
      except RPCFail, err:
1757
        msgs.append(str(err))
1758

    
1759
  if msgs:
1760
    _Fail("; ".join(msgs))
1761

    
1762

    
1763
def BlockdevAddchildren(parent_cdev, new_cdevs):
1764
  """Extend a mirrored block device.
1765

1766
  @type parent_cdev: L{objects.Disk}
1767
  @param parent_cdev: the disk to which we should add children
1768
  @type new_cdevs: list of L{objects.Disk}
1769
  @param new_cdevs: the list of children which we should add
1770
  @rtype: None
1771

1772
  """
1773
  parent_bdev = _RecursiveFindBD(parent_cdev)
1774
  if parent_bdev is None:
1775
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1776
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1777
  if new_bdevs.count(None) > 0:
1778
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1779
  parent_bdev.AddChildren(new_bdevs)
1780

    
1781

    
1782
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1783
  """Shrink a mirrored block device.
1784

1785
  @type parent_cdev: L{objects.Disk}
1786
  @param parent_cdev: the disk from which we should remove children
1787
  @type new_cdevs: list of L{objects.Disk}
1788
  @param new_cdevs: the list of children which we should remove
1789
  @rtype: None
1790

1791
  """
1792
  parent_bdev = _RecursiveFindBD(parent_cdev)
1793
  if parent_bdev is None:
1794
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1795
  devs = []
1796
  for disk in new_cdevs:
1797
    rpath = disk.StaticDevPath()
1798
    if rpath is None:
1799
      bd = _RecursiveFindBD(disk)
1800
      if bd is None:
1801
        _Fail("Can't find device %s while removing children", disk)
1802
      else:
1803
        devs.append(bd.dev_path)
1804
    else:
1805
      if not utils.IsNormAbsPath(rpath):
1806
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
1807
      devs.append(rpath)
1808
  parent_bdev.RemoveChildren(devs)
1809

    
1810

    
1811
def BlockdevGetmirrorstatus(disks):
1812
  """Get the mirroring status of a list of devices.
1813

1814
  @type disks: list of L{objects.Disk}
1815
  @param disks: the list of disks which we should query
1816
  @rtype: disk
1817
  @return: List of L{objects.BlockDevStatus}, one for each disk
1818
  @raise errors.BlockDeviceError: if any of the disks cannot be
1819
      found
1820

1821
  """
1822
  stats = []
1823
  for dsk in disks:
1824
    rbd = _RecursiveFindBD(dsk)
1825
    if rbd is None:
1826
      _Fail("Can't find device %s", dsk)
1827

    
1828
    stats.append(rbd.CombinedSyncStatus())
1829

    
1830
  return stats
1831

    
1832

    
1833
def BlockdevGetmirrorstatusMulti(disks):
1834
  """Get the mirroring status of a list of devices.
1835

1836
  @type disks: list of L{objects.Disk}
1837
  @param disks: the list of disks which we should query
1838
  @rtype: disk
1839
  @return: List of tuples, (bool, status), one for each disk; bool denotes
1840
    success/failure, status is L{objects.BlockDevStatus} on success, string
1841
    otherwise
1842

1843
  """
1844
  result = []
1845
  for disk in disks:
1846
    try:
1847
      rbd = _RecursiveFindBD(disk)
1848
      if rbd is None:
1849
        result.append((False, "Can't find device %s" % disk))
1850
        continue
1851

    
1852
      status = rbd.CombinedSyncStatus()
1853
    except errors.BlockDeviceError, err:
1854
      logging.exception("Error while getting disk status")
1855
      result.append((False, str(err)))
1856
    else:
1857
      result.append((True, status))
1858

    
1859
  assert len(disks) == len(result)
1860

    
1861
  return result
1862

    
1863

    
1864
def _RecursiveFindBD(disk):
1865
  """Check if a device is activated.
1866

1867
  If so, return information about the real device.
1868

1869
  @type disk: L{objects.Disk}
1870
  @param disk: the disk object we need to find
1871

1872
  @return: None if the device can't be found,
1873
      otherwise the device instance
1874

1875
  """
1876
  children = []
1877
  if disk.children:
1878
    for chdisk in disk.children:
1879
      children.append(_RecursiveFindBD(chdisk))
1880

    
1881
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1882

    
1883

    
1884
def _OpenRealBD(disk):
1885
  """Opens the underlying block device of a disk.
1886

1887
  @type disk: L{objects.Disk}
1888
  @param disk: the disk object we want to open
1889

1890
  """
1891
  real_disk = _RecursiveFindBD(disk)
1892
  if real_disk is None:
1893
    _Fail("Block device '%s' is not set up", disk)
1894

    
1895
  real_disk.Open()
1896

    
1897
  return real_disk
1898

    
1899

    
1900
def BlockdevFind(disk):
1901
  """Check if a device is activated.
1902

1903
  If it is, return information about the real device.
1904

1905
  @type disk: L{objects.Disk}
1906
  @param disk: the disk to find
1907
  @rtype: None or objects.BlockDevStatus
1908
  @return: None if the disk cannot be found, otherwise a the current
1909
           information
1910

1911
  """
1912
  try:
1913
    rbd = _RecursiveFindBD(disk)
1914
  except errors.BlockDeviceError, err:
1915
    _Fail("Failed to find device: %s", err, exc=True)
1916

    
1917
  if rbd is None:
1918
    return None
1919

    
1920
  return rbd.GetSyncStatus()
1921

    
1922

    
1923
def BlockdevGetsize(disks):
1924
  """Computes the size of the given disks.
1925

1926
  If a disk is not found, returns None instead.
1927

1928
  @type disks: list of L{objects.Disk}
1929
  @param disks: the list of disk to compute the size for
1930
  @rtype: list
1931
  @return: list with elements None if the disk cannot be found,
1932
      otherwise the size
1933

1934
  """
1935
  result = []
1936
  for cf in disks:
1937
    try:
1938
      rbd = _RecursiveFindBD(cf)
1939
    except errors.BlockDeviceError:
1940
      result.append(None)
1941
      continue
1942
    if rbd is None:
1943
      result.append(None)
1944
    else:
1945
      result.append(rbd.GetActualSize())
1946
  return result
1947

    
1948

    
1949
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
1950
  """Export a block device to a remote node.
1951

1952
  @type disk: L{objects.Disk}
1953
  @param disk: the description of the disk to export
1954
  @type dest_node: str
1955
  @param dest_node: the destination node to export to
1956
  @type dest_path: str
1957
  @param dest_path: the destination path on the target node
1958
  @type cluster_name: str
1959
  @param cluster_name: the cluster name, needed for SSH hostalias
1960
  @rtype: None
1961

1962
  """
1963
  real_disk = _OpenRealBD(disk)
1964

    
1965
  # the block size on the read dd is 1MiB to match our units
1966
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
1967
                               "dd if=%s bs=1048576 count=%s",
1968
                               real_disk.dev_path, str(disk.size))
1969

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

    
1979
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1980
                                                   constants.GANETI_RUNAS,
1981
                                                   destcmd)
1982

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

    
1986
  result = utils.RunCmd(["bash", "-c", command])
1987

    
1988
  if result.failed:
1989
    _Fail("Disk copy command '%s' returned error: %s"
1990
          " output: %s", command, result.fail_reason, result.output)
1991

    
1992

    
1993
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1994
  """Write a file to the filesystem.
1995

1996
  This allows the master to overwrite(!) a file. It will only perform
1997
  the operation if the file belongs to a list of configuration files.
1998

1999
  @type file_name: str
2000
  @param file_name: the target file name
2001
  @type data: str
2002
  @param data: the new contents of the file
2003
  @type mode: int
2004
  @param mode: the mode to give the file (can be None)
2005
  @type uid: string
2006
  @param uid: the owner of the file
2007
  @type gid: string
2008
  @param gid: the group of the file
2009
  @type atime: float
2010
  @param atime: the atime to set on the file (can be None)
2011
  @type mtime: float
2012
  @param mtime: the mtime to set on the file (can be None)
2013
  @rtype: None
2014

2015
  """
2016
  if not os.path.isabs(file_name):
2017
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2018

    
2019
  if file_name not in _ALLOWED_UPLOAD_FILES:
2020
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2021
          file_name)
2022

    
2023
  raw_data = _Decompress(data)
2024

    
2025
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2026
    _Fail("Invalid username/groupname type")
2027

    
2028
  getents = runtime.GetEnts()
2029
  uid = getents.LookupUser(uid)
2030
  gid = getents.LookupGroup(gid)
2031

    
2032
  utils.SafeWriteFile(file_name, None,
2033
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2034
                      atime=atime, mtime=mtime)
2035

    
2036

    
2037
def RunOob(oob_program, command, node, timeout):
2038
  """Executes oob_program with given command on given node.
2039

2040
  @param oob_program: The path to the executable oob_program
2041
  @param command: The command to invoke on oob_program
2042
  @param node: The node given as an argument to the program
2043
  @param timeout: Timeout after which we kill the oob program
2044

2045
  @return: stdout
2046
  @raise RPCFail: If execution fails for some reason
2047

2048
  """
2049
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2050

    
2051
  if result.failed:
2052
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2053
          result.fail_reason, result.output)
2054

    
2055
  return result.stdout
2056

    
2057

    
2058
def WriteSsconfFiles(values):
2059
  """Update all ssconf files.
2060

2061
  Wrapper around the SimpleStore.WriteFiles.
2062

2063
  """
2064
  ssconf.SimpleStore().WriteFiles(values)
2065

    
2066

    
2067
def _ErrnoOrStr(err):
2068
  """Format an EnvironmentError exception.
2069

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

2074
  @type err: L{EnvironmentError}
2075
  @param err: the exception to format
2076

2077
  """
2078
  if hasattr(err, "errno"):
2079
    detail = errno.errorcode[err.errno]
2080
  else:
2081
    detail = str(err)
2082
  return detail
2083

    
2084

    
2085
def _OSOndiskAPIVersion(os_dir):
2086
  """Compute and return the API version of a given OS.
2087

2088
  This function will try to read the API version of the OS residing in
2089
  the 'os_dir' directory.
2090

2091
  @type os_dir: str
2092
  @param os_dir: the directory in which we should look for the OS
2093
  @rtype: tuple
2094
  @return: tuple (status, data) with status denoting the validity and
2095
      data holding either the vaid versions or an error message
2096

2097
  """
2098
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2099

    
2100
  try:
2101
    st = os.stat(api_file)
2102
  except EnvironmentError, err:
2103
    return False, ("Required file '%s' not found under path %s: %s" %
2104
                   (constants.OS_API_FILE, os_dir, _ErrnoOrStr(err)))
2105

    
2106
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2107
    return False, ("File '%s' in %s is not a regular file" %
2108
                   (constants.OS_API_FILE, os_dir))
2109

    
2110
  try:
2111
    api_versions = utils.ReadFile(api_file).splitlines()
2112
  except EnvironmentError, err:
2113
    return False, ("Error while reading the API version file at %s: %s" %
2114
                   (api_file, _ErrnoOrStr(err)))
2115

    
2116
  try:
2117
    api_versions = [int(version.strip()) for version in api_versions]
2118
  except (TypeError, ValueError), err:
2119
    return False, ("API version(s) can't be converted to integer: %s" %
2120
                   str(err))
2121

    
2122
  return True, api_versions
2123

    
2124

    
2125
def DiagnoseOS(top_dirs=None):
2126
  """Compute the validity for all OSes.
2127

2128
  @type top_dirs: list
2129
  @param top_dirs: the list of directories in which to
2130
      search (if not given defaults to
2131
      L{constants.OS_SEARCH_PATH})
2132
  @rtype: list of L{objects.OS}
2133
  @return: a list of tuples (name, path, status, diagnose, variants,
2134
      parameters, api_version) for all (potential) OSes under all
2135
      search paths, where:
2136
          - name is the (potential) OS name
2137
          - path is the full path to the OS
2138
          - status True/False is the validity of the OS
2139
          - diagnose is the error message for an invalid OS, otherwise empty
2140
          - variants is a list of supported OS variants, if any
2141
          - parameters is a list of (name, help) parameters, if any
2142
          - api_version is a list of support OS API versions
2143

2144
  """
2145
  if top_dirs is None:
2146
    top_dirs = constants.OS_SEARCH_PATH
2147

    
2148
  result = []
2149
  for dir_name in top_dirs:
2150
    if os.path.isdir(dir_name):
2151
      try:
2152
        f_names = utils.ListVisibleFiles(dir_name)
2153
      except EnvironmentError, err:
2154
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2155
        break
2156
      for name in f_names:
2157
        os_path = utils.PathJoin(dir_name, name)
2158
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2159
        if status:
2160
          diagnose = ""
2161
          variants = os_inst.supported_variants
2162
          parameters = os_inst.supported_parameters
2163
          api_versions = os_inst.api_versions
2164
        else:
2165
          diagnose = os_inst
2166
          variants = parameters = api_versions = []
2167
        result.append((name, os_path, status, diagnose, variants,
2168
                       parameters, api_versions))
2169

    
2170
  return result
2171

    
2172

    
2173
def _TryOSFromDisk(name, base_dir=None):
2174
  """Create an OS instance from disk.
2175

2176
  This function will return an OS instance if the given name is a
2177
  valid OS name.
2178

2179
  @type base_dir: string
2180
  @keyword base_dir: Base directory containing OS installations.
2181
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2182
  @rtype: tuple
2183
  @return: success and either the OS instance if we find a valid one,
2184
      or error message
2185

2186
  """
2187
  if base_dir is None:
2188
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
2189
  else:
2190
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2191

    
2192
  if os_dir is None:
2193
    return False, "Directory for OS %s not found in search path" % name
2194

    
2195
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2196
  if not status:
2197
    # push the error up
2198
    return status, api_versions
2199

    
2200
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2201
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2202
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2203

    
2204
  # OS Files dictionary, we will populate it with the absolute path
2205
  # names; if the value is True, then it is a required file, otherwise
2206
  # an optional one
2207
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2208

    
2209
  if max(api_versions) >= constants.OS_API_V15:
2210
    os_files[constants.OS_VARIANTS_FILE] = False
2211

    
2212
  if max(api_versions) >= constants.OS_API_V20:
2213
    os_files[constants.OS_PARAMETERS_FILE] = True
2214
  else:
2215
    del os_files[constants.OS_SCRIPT_VERIFY]
2216

    
2217
  for (filename, required) in os_files.items():
2218
    os_files[filename] = utils.PathJoin(os_dir, filename)
2219

    
2220
    try:
2221
      st = os.stat(os_files[filename])
2222
    except EnvironmentError, err:
2223
      if err.errno == errno.ENOENT and not required:
2224
        del os_files[filename]
2225
        continue
2226
      return False, ("File '%s' under path '%s' is missing (%s)" %
2227
                     (filename, os_dir, _ErrnoOrStr(err)))
2228

    
2229
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2230
      return False, ("File '%s' under path '%s' is not a regular file" %
2231
                     (filename, os_dir))
2232

    
2233
    if filename in constants.OS_SCRIPTS:
2234
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2235
        return False, ("File '%s' under path '%s' is not executable" %
2236
                       (filename, os_dir))
2237

    
2238
  variants = []
2239
  if constants.OS_VARIANTS_FILE in os_files:
2240
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2241
    try:
2242
      variants = utils.ReadFile(variants_file).splitlines()
2243
    except EnvironmentError, err:
2244
      # we accept missing files, but not other errors
2245
      if err.errno != errno.ENOENT:
2246
        return False, ("Error while reading the OS variants file at %s: %s" %
2247
                       (variants_file, _ErrnoOrStr(err)))
2248

    
2249
  parameters = []
2250
  if constants.OS_PARAMETERS_FILE in os_files:
2251
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2252
    try:
2253
      parameters = utils.ReadFile(parameters_file).splitlines()
2254
    except EnvironmentError, err:
2255
      return False, ("Error while reading the OS parameters file at %s: %s" %
2256
                     (parameters_file, _ErrnoOrStr(err)))
2257
    parameters = [v.split(None, 1) for v in parameters]
2258

    
2259
  os_obj = objects.OS(name=name, path=os_dir,
2260
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2261
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2262
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2263
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2264
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2265
                                                 None),
2266
                      supported_variants=variants,
2267
                      supported_parameters=parameters,
2268
                      api_versions=api_versions)
2269
  return True, os_obj
2270

    
2271

    
2272
def OSFromDisk(name, base_dir=None):
2273
  """Create an OS instance from disk.
2274

2275
  This function will return an OS instance if the given name is a
2276
  valid OS name. Otherwise, it will raise an appropriate
2277
  L{RPCFail} exception, detailing why this is not a valid OS.
2278

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

2282
  @type base_dir: string
2283
  @keyword base_dir: Base directory containing OS installations.
2284
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2285
  @rtype: L{objects.OS}
2286
  @return: the OS instance if we find a valid one
2287
  @raise RPCFail: if we don't find a valid OS
2288

2289
  """
2290
  name_only = objects.OS.GetName(name)
2291
  status, payload = _TryOSFromDisk(name_only, base_dir)
2292

    
2293
  if not status:
2294
    _Fail(payload)
2295

    
2296
  return payload
2297

    
2298

    
2299
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2300
  """Calculate the basic environment for an os script.
2301

2302
  @type os_name: str
2303
  @param os_name: full operating system name (including variant)
2304
  @type inst_os: L{objects.OS}
2305
  @param inst_os: operating system for which the environment is being built
2306
  @type os_params: dict
2307
  @param os_params: the OS parameters
2308
  @type debug: integer
2309
  @param debug: debug level (0 or 1, for OS Api 10)
2310
  @rtype: dict
2311
  @return: dict of environment variables
2312
  @raise errors.BlockDeviceError: if the block device
2313
      cannot be found
2314

2315
  """
2316
  result = {}
2317
  api_version = \
2318
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2319
  result["OS_API_VERSION"] = "%d" % api_version
2320
  result["OS_NAME"] = inst_os.name
2321
  result["DEBUG_LEVEL"] = "%d" % debug
2322

    
2323
  # OS variants
2324
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2325
    variant = objects.OS.GetVariant(os_name)
2326
    if not variant:
2327
      variant = inst_os.supported_variants[0]
2328
  else:
2329
    variant = ""
2330
  result["OS_VARIANT"] = variant
2331

    
2332
  # OS params
2333
  for pname, pvalue in os_params.items():
2334
    result["OSP_%s" % pname.upper()] = pvalue
2335

    
2336
  return result
2337

    
2338

    
2339
def OSEnvironment(instance, inst_os, debug=0):
2340
  """Calculate the environment for an os script.
2341

2342
  @type instance: L{objects.Instance}
2343
  @param instance: target instance for the os script run
2344
  @type inst_os: L{objects.OS}
2345
  @param inst_os: operating system for which the environment is being built
2346
  @type debug: integer
2347
  @param debug: debug level (0 or 1, for OS Api 10)
2348
  @rtype: dict
2349
  @return: dict of environment variables
2350
  @raise errors.BlockDeviceError: if the block device
2351
      cannot be found
2352

2353
  """
2354
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2355

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

    
2359
  result["HYPERVISOR"] = instance.hypervisor
2360
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2361
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2362
  result["INSTANCE_SECONDARY_NODES"] = \
2363
      ("%s" % " ".join(instance.secondary_nodes))
2364

    
2365
  # Disks
2366
  for idx, disk in enumerate(instance.disks):
2367
    real_disk = _OpenRealBD(disk)
2368
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2369
    result["DISK_%d_ACCESS" % idx] = disk.mode
2370
    if constants.HV_DISK_TYPE in instance.hvparams:
2371
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2372
        instance.hvparams[constants.HV_DISK_TYPE]
2373
    if disk.dev_type in constants.LDS_BLOCK:
2374
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2375
    elif disk.dev_type == constants.LD_FILE:
2376
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2377
        "file:%s" % disk.physical_id[0]
2378

    
2379
  # NICs
2380
  for idx, nic in enumerate(instance.nics):
2381
    result["NIC_%d_MAC" % idx] = nic.mac
2382
    if nic.ip:
2383
      result["NIC_%d_IP" % idx] = nic.ip
2384
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2385
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2386
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2387
    if nic.nicparams[constants.NIC_LINK]:
2388
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2389
    if constants.HV_NIC_TYPE in instance.hvparams:
2390
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2391
        instance.hvparams[constants.HV_NIC_TYPE]
2392

    
2393
  # HV/BE params
2394
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2395
    for key, value in source.items():
2396
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2397

    
2398
  return result
2399

    
2400

    
2401
def BlockdevGrow(disk, amount, dryrun):
2402
  """Grow a stack of block devices.
2403

2404
  This function is called recursively, with the childrens being the
2405
  first ones to resize.
2406

2407
  @type disk: L{objects.Disk}
2408
  @param disk: the disk to be grown
2409
  @type amount: integer
2410
  @param amount: the amount (in mebibytes) to grow with
2411
  @type dryrun: boolean
2412
  @param dryrun: whether to execute the operation in simulation mode
2413
      only, without actually increasing the size
2414
  @rtype: (status, result)
2415
  @return: a tuple with the status of the operation (True/False), and
2416
      the errors message if status is False
2417

2418
  """
2419
  r_dev = _RecursiveFindBD(disk)
2420
  if r_dev is None:
2421
    _Fail("Cannot find block device %s", disk)
2422

    
2423
  try:
2424
    r_dev.Grow(amount, dryrun)
2425
  except errors.BlockDeviceError, err:
2426
    _Fail("Failed to grow block device: %s", err, exc=True)
2427

    
2428

    
2429
def BlockdevSnapshot(disk):
2430
  """Create a snapshot copy of a block device.
2431

2432
  This function is called recursively, and the snapshot is actually created
2433
  just for the leaf lvm backend device.
2434

2435
  @type disk: L{objects.Disk}
2436
  @param disk: the disk to be snapshotted
2437
  @rtype: string
2438
  @return: snapshot disk ID as (vg, lv)
2439

2440
  """
2441
  if disk.dev_type == constants.LD_DRBD8:
2442
    if not disk.children:
2443
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2444
            disk.unique_id)
2445
    return BlockdevSnapshot(disk.children[0])
2446
  elif disk.dev_type == constants.LD_LV:
2447
    r_dev = _RecursiveFindBD(disk)
2448
    if r_dev is not None:
2449
      # FIXME: choose a saner value for the snapshot size
2450
      # let's stay on the safe side and ask for the full size, for now
2451
      return r_dev.Snapshot(disk.size)
2452
    else:
2453
      _Fail("Cannot find block device %s", disk)
2454
  else:
2455
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2456
          disk.unique_id, disk.dev_type)
2457

    
2458

    
2459
def FinalizeExport(instance, snap_disks):
2460
  """Write out the export configuration information.
2461

2462
  @type instance: L{objects.Instance}
2463
  @param instance: the instance which we export, used for
2464
      saving configuration
2465
  @type snap_disks: list of L{objects.Disk}
2466
  @param snap_disks: list of snapshot block devices, which
2467
      will be used to get the actual name of the dump file
2468

2469
  @rtype: None
2470

2471
  """
2472
  destdir = utils.PathJoin(constants.EXPORT_DIR, instance.name + ".new")
2473
  finaldestdir = utils.PathJoin(constants.EXPORT_DIR, instance.name)
2474

    
2475
  config = objects.SerializableConfigParser()
2476

    
2477
  config.add_section(constants.INISECT_EXP)
2478
  config.set(constants.INISECT_EXP, "version", "0")
2479
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2480
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2481
  config.set(constants.INISECT_EXP, "os", instance.os)
2482
  config.set(constants.INISECT_EXP, "compression", "none")
2483

    
2484
  config.add_section(constants.INISECT_INS)
2485
  config.set(constants.INISECT_INS, "name", instance.name)
2486
  config.set(constants.INISECT_INS, "memory", "%d" %
2487
             instance.beparams[constants.BE_MEMORY])
2488
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2489
             instance.beparams[constants.BE_VCPUS])
2490
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2491
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2492
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2493

    
2494
  nic_total = 0
2495
  for nic_count, nic in enumerate(instance.nics):
2496
    nic_total += 1
2497
    config.set(constants.INISECT_INS, "nic%d_mac" %
2498
               nic_count, "%s" % nic.mac)
2499
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2500
    for param in constants.NICS_PARAMETER_TYPES:
2501
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2502
                 "%s" % nic.nicparams.get(param, None))
2503
  # TODO: redundant: on load can read nics until it doesn't exist
2504
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2505

    
2506
  disk_total = 0
2507
  for disk_count, disk in enumerate(snap_disks):
2508
    if disk:
2509
      disk_total += 1
2510
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2511
                 ("%s" % disk.iv_name))
2512
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2513
                 ("%s" % disk.physical_id[1]))
2514
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2515
                 ("%d" % disk.size))
2516

    
2517
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2518

    
2519
  # New-style hypervisor/backend parameters
2520

    
2521
  config.add_section(constants.INISECT_HYP)
2522
  for name, value in instance.hvparams.items():
2523
    if name not in constants.HVC_GLOBALS:
2524
      config.set(constants.INISECT_HYP, name, str(value))
2525

    
2526
  config.add_section(constants.INISECT_BEP)
2527
  for name, value in instance.beparams.items():
2528
    config.set(constants.INISECT_BEP, name, str(value))
2529

    
2530
  config.add_section(constants.INISECT_OSP)
2531
  for name, value in instance.osparams.items():
2532
    config.set(constants.INISECT_OSP, name, str(value))
2533

    
2534
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2535
                  data=config.Dumps())
2536
  shutil.rmtree(finaldestdir, ignore_errors=True)
2537
  shutil.move(destdir, finaldestdir)
2538

    
2539

    
2540
def ExportInfo(dest):
2541
  """Get export configuration information.
2542

2543
  @type dest: str
2544
  @param dest: directory containing the export
2545

2546
  @rtype: L{objects.SerializableConfigParser}
2547
  @return: a serializable config file containing the
2548
      export info
2549

2550
  """
2551
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2552

    
2553
  config = objects.SerializableConfigParser()
2554
  config.read(cff)
2555

    
2556
  if (not config.has_section(constants.INISECT_EXP) or
2557
      not config.has_section(constants.INISECT_INS)):
2558
    _Fail("Export info file doesn't have the required fields")
2559

    
2560
  return config.Dumps()
2561

    
2562

    
2563
def ListExports():
2564
  """Return a list of exports currently available on this machine.
2565

2566
  @rtype: list
2567
  @return: list of the exports
2568

2569
  """
2570
  if os.path.isdir(constants.EXPORT_DIR):
2571
    return sorted(utils.ListVisibleFiles(constants.EXPORT_DIR))
2572
  else:
2573
    _Fail("No exports directory")
2574

    
2575

    
2576
def RemoveExport(export):
2577
  """Remove an existing export from the node.
2578

2579
  @type export: str
2580
  @param export: the name of the export to remove
2581
  @rtype: None
2582

2583
  """
2584
  target = utils.PathJoin(constants.EXPORT_DIR, export)
2585

    
2586
  try:
2587
    shutil.rmtree(target)
2588
  except EnvironmentError, err:
2589
    _Fail("Error while removing the export: %s", err, exc=True)
2590

    
2591

    
2592
def BlockdevRename(devlist):
2593
  """Rename a list of block devices.
2594

2595
  @type devlist: list of tuples
2596
  @param devlist: list of tuples of the form  (disk,
2597
      new_logical_id, new_physical_id); disk is an
2598
      L{objects.Disk} object describing the current disk,
2599
      and new logical_id/physical_id is the name we
2600
      rename it to
2601
  @rtype: boolean
2602
  @return: True if all renames succeeded, False otherwise
2603

2604
  """
2605
  msgs = []
2606
  result = True
2607
  for disk, unique_id in devlist:
2608
    dev = _RecursiveFindBD(disk)
2609
    if dev is None:
2610
      msgs.append("Can't find device %s in rename" % str(disk))
2611
      result = False
2612
      continue
2613
    try:
2614
      old_rpath = dev.dev_path
2615
      dev.Rename(unique_id)
2616
      new_rpath = dev.dev_path
2617
      if old_rpath != new_rpath:
2618
        DevCacheManager.RemoveCache(old_rpath)
2619
        # FIXME: we should add the new cache information here, like:
2620
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2621
        # but we don't have the owner here - maybe parse from existing
2622
        # cache? for now, we only lose lvm data when we rename, which
2623
        # is less critical than DRBD or MD
2624
    except errors.BlockDeviceError, err:
2625
      msgs.append("Can't rename device '%s' to '%s': %s" %
2626
                  (dev, unique_id, err))
2627
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2628
      result = False
2629
  if not result:
2630
    _Fail("; ".join(msgs))
2631

    
2632

    
2633
def _TransformFileStorageDir(fs_dir):
2634
  """Checks whether given file_storage_dir is valid.
2635

2636
  Checks wheter the given fs_dir is within the cluster-wide default
2637
  file_storage_dir or the shared_file_storage_dir, which are stored in
2638
  SimpleStore. Only paths under those directories are allowed.
2639

2640
  @type fs_dir: str
2641
  @param fs_dir: the path to check
2642

2643
  @return: the normalized path if valid, None otherwise
2644

2645
  """
2646
  if not constants.ENABLE_FILE_STORAGE:
2647
    _Fail("File storage disabled at configure time")
2648
  cfg = _GetConfig()
2649
  fs_dir = os.path.normpath(fs_dir)
2650
  base_fstore = cfg.GetFileStorageDir()
2651
  base_shared = cfg.GetSharedFileStorageDir()
2652
  if not (utils.IsBelowDir(base_fstore, fs_dir) or
2653
          utils.IsBelowDir(base_shared, fs_dir)):
2654
    _Fail("File storage directory '%s' is not under base file"
2655
          " storage directory '%s' or shared storage directory '%s'",
2656
          fs_dir, base_fstore, base_shared)
2657
  return fs_dir
2658

    
2659

    
2660
def CreateFileStorageDir(file_storage_dir):
2661
  """Create file storage directory.
2662

2663
  @type file_storage_dir: str
2664
  @param file_storage_dir: directory to create
2665

2666
  @rtype: tuple
2667
  @return: tuple with first element a boolean indicating wheter dir
2668
      creation was successful or not
2669

2670
  """
2671
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2672
  if os.path.exists(file_storage_dir):
2673
    if not os.path.isdir(file_storage_dir):
2674
      _Fail("Specified storage dir '%s' is not a directory",
2675
            file_storage_dir)
2676
  else:
2677
    try:
2678
      os.makedirs(file_storage_dir, 0750)
2679
    except OSError, err:
2680
      _Fail("Cannot create file storage directory '%s': %s",
2681
            file_storage_dir, err, exc=True)
2682

    
2683

    
2684
def RemoveFileStorageDir(file_storage_dir):
2685
  """Remove file storage directory.
2686

2687
  Remove it only if it's empty. If not log an error and return.
2688

2689
  @type file_storage_dir: str
2690
  @param file_storage_dir: the directory we should cleanup
2691
  @rtype: tuple (success,)
2692
  @return: tuple of one element, C{success}, denoting
2693
      whether the operation was successful
2694

2695
  """
2696
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2697
  if os.path.exists(file_storage_dir):
2698
    if not os.path.isdir(file_storage_dir):
2699
      _Fail("Specified Storage directory '%s' is not a directory",
2700
            file_storage_dir)
2701
    # deletes dir only if empty, otherwise we want to fail the rpc call
2702
    try:
2703
      os.rmdir(file_storage_dir)
2704
    except OSError, err:
2705
      _Fail("Cannot remove file storage directory '%s': %s",
2706
            file_storage_dir, err)
2707

    
2708

    
2709
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2710
  """Rename the file storage directory.
2711

2712
  @type old_file_storage_dir: str
2713
  @param old_file_storage_dir: the current path
2714
  @type new_file_storage_dir: str
2715
  @param new_file_storage_dir: the name we should rename to
2716
  @rtype: tuple (success,)
2717
  @return: tuple of one element, C{success}, denoting
2718
      whether the operation was successful
2719

2720
  """
2721
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2722
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2723
  if not os.path.exists(new_file_storage_dir):
2724
    if os.path.isdir(old_file_storage_dir):
2725
      try:
2726
        os.rename(old_file_storage_dir, new_file_storage_dir)
2727
      except OSError, err:
2728
        _Fail("Cannot rename '%s' to '%s': %s",
2729
              old_file_storage_dir, new_file_storage_dir, err)
2730
    else:
2731
      _Fail("Specified storage dir '%s' is not a directory",
2732
            old_file_storage_dir)
2733
  else:
2734
    if os.path.exists(old_file_storage_dir):
2735
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2736
            old_file_storage_dir, new_file_storage_dir)
2737

    
2738

    
2739
def _EnsureJobQueueFile(file_name):
2740
  """Checks whether the given filename is in the queue directory.
2741

2742
  @type file_name: str
2743
  @param file_name: the file name we should check
2744
  @rtype: None
2745
  @raises RPCFail: if the file is not valid
2746

2747
  """
2748
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2749
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2750

    
2751
  if not result:
2752
    _Fail("Passed job queue file '%s' does not belong to"
2753
          " the queue directory '%s'", file_name, queue_dir)
2754

    
2755

    
2756
def JobQueueUpdate(file_name, content):
2757
  """Updates a file in the queue directory.
2758

2759
  This is just a wrapper over L{utils.io.WriteFile}, with proper
2760
  checking.
2761

2762
  @type file_name: str
2763
  @param file_name: the job file name
2764
  @type content: str
2765
  @param content: the new job contents
2766
  @rtype: boolean
2767
  @return: the success of the operation
2768

2769
  """
2770
  _EnsureJobQueueFile(file_name)
2771
  getents = runtime.GetEnts()
2772

    
2773
  # Write and replace the file atomically
2774
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
2775
                  gid=getents.masterd_gid)
2776

    
2777

    
2778
def JobQueueRename(old, new):
2779
  """Renames a job queue file.
2780

2781
  This is just a wrapper over os.rename with proper checking.
2782

2783
  @type old: str
2784
  @param old: the old (actual) file name
2785
  @type new: str
2786
  @param new: the desired file name
2787
  @rtype: tuple
2788
  @return: the success of the operation and payload
2789

2790
  """
2791
  _EnsureJobQueueFile(old)
2792
  _EnsureJobQueueFile(new)
2793

    
2794
  getents = runtime.GetEnts()
2795

    
2796
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0700,
2797
                   dir_uid=getents.masterd_uid, dir_gid=getents.masterd_gid)
2798

    
2799

    
2800
def BlockdevClose(instance_name, disks):
2801
  """Closes the given block devices.
2802

2803
  This means they will be switched to secondary mode (in case of
2804
  DRBD).
2805

2806
  @param instance_name: if the argument is not empty, the symlinks
2807
      of this instance will be removed
2808
  @type disks: list of L{objects.Disk}
2809
  @param disks: the list of disks to be closed
2810
  @rtype: tuple (success, message)
2811
  @return: a tuple of success and message, where success
2812
      indicates the succes of the operation, and message
2813
      which will contain the error details in case we
2814
      failed
2815

2816
  """
2817
  bdevs = []
2818
  for cf in disks:
2819
    rd = _RecursiveFindBD(cf)
2820
    if rd is None:
2821
      _Fail("Can't find device %s", cf)
2822
    bdevs.append(rd)
2823

    
2824
  msg = []
2825
  for rd in bdevs:
2826
    try:
2827
      rd.Close()
2828
    except errors.BlockDeviceError, err:
2829
      msg.append(str(err))
2830
  if msg:
2831
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2832
  else:
2833
    if instance_name:
2834
      _RemoveBlockDevLinks(instance_name, disks)
2835

    
2836

    
2837
def ValidateHVParams(hvname, hvparams):
2838
  """Validates the given hypervisor parameters.
2839

2840
  @type hvname: string
2841
  @param hvname: the hypervisor name
2842
  @type hvparams: dict
2843
  @param hvparams: the hypervisor parameters to be validated
2844
  @rtype: None
2845

2846
  """
2847
  try:
2848
    hv_type = hypervisor.GetHypervisor(hvname)
2849
    hv_type.ValidateParameters(hvparams)
2850
  except errors.HypervisorError, err:
2851
    _Fail(str(err), log=False)
2852

    
2853

    
2854
def _CheckOSPList(os_obj, parameters):
2855
  """Check whether a list of parameters is supported by the OS.
2856

2857
  @type os_obj: L{objects.OS}
2858
  @param os_obj: OS object to check
2859
  @type parameters: list
2860
  @param parameters: the list of parameters to check
2861

2862
  """
2863
  supported = [v[0] for v in os_obj.supported_parameters]
2864
  delta = frozenset(parameters).difference(supported)
2865
  if delta:
2866
    _Fail("The following parameters are not supported"
2867
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
2868

    
2869

    
2870
def ValidateOS(required, osname, checks, osparams):
2871
  """Validate the given OS' parameters.
2872

2873
  @type required: boolean
2874
  @param required: whether absence of the OS should translate into
2875
      failure or not
2876
  @type osname: string
2877
  @param osname: the OS to be validated
2878
  @type checks: list
2879
  @param checks: list of the checks to run (currently only 'parameters')
2880
  @type osparams: dict
2881
  @param osparams: dictionary with OS parameters
2882
  @rtype: boolean
2883
  @return: True if the validation passed, or False if the OS was not
2884
      found and L{required} was false
2885

2886
  """
2887
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
2888
    _Fail("Unknown checks required for OS %s: %s", osname,
2889
          set(checks).difference(constants.OS_VALIDATE_CALLS))
2890

    
2891
  name_only = objects.OS.GetName(osname)
2892
  status, tbv = _TryOSFromDisk(name_only, None)
2893

    
2894
  if not status:
2895
    if required:
2896
      _Fail(tbv)
2897
    else:
2898
      return False
2899

    
2900
  if max(tbv.api_versions) < constants.OS_API_V20:
2901
    return True
2902

    
2903
  if constants.OS_VALIDATE_PARAMETERS in checks:
2904
    _CheckOSPList(tbv, osparams.keys())
2905

    
2906
  validate_env = OSCoreEnv(osname, tbv, osparams)
2907
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
2908
                        cwd=tbv.path, reset_env=True)
2909
  if result.failed:
2910
    logging.error("os validate command '%s' returned error: %s output: %s",
2911
                  result.cmd, result.fail_reason, result.output)
2912
    _Fail("OS validation script failed (%s), output: %s",
2913
          result.fail_reason, result.output, log=False)
2914

    
2915
  return True
2916

    
2917

    
2918
def DemoteFromMC():
2919
  """Demotes the current node from master candidate role.
2920

2921
  """
2922
  # try to ensure we're not the master by mistake
2923
  master, myself = ssconf.GetMasterAndMyself()
2924
  if master == myself:
2925
    _Fail("ssconf status shows I'm the master node, will not demote")
2926

    
2927
  result = utils.RunCmd([constants.DAEMON_UTIL, "check", constants.MASTERD])
2928
  if not result.failed:
2929
    _Fail("The master daemon is running, will not demote")
2930

    
2931
  try:
2932
    if os.path.isfile(constants.CLUSTER_CONF_FILE):
2933
      utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2934
  except EnvironmentError, err:
2935
    if err.errno != errno.ENOENT:
2936
      _Fail("Error while backing up cluster file: %s", err, exc=True)
2937

    
2938
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2939

    
2940

    
2941
def _GetX509Filenames(cryptodir, name):
2942
  """Returns the full paths for the private key and certificate.
2943

2944
  """
2945
  return (utils.PathJoin(cryptodir, name),
2946
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
2947
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
2948

    
2949

    
2950
def CreateX509Certificate(validity, cryptodir=constants.CRYPTO_KEYS_DIR):
2951
  """Creates a new X509 certificate for SSL/TLS.
2952

2953
  @type validity: int
2954
  @param validity: Validity in seconds
2955
  @rtype: tuple; (string, string)
2956
  @return: Certificate name and public part
2957

2958
  """
2959
  (key_pem, cert_pem) = \
2960
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
2961
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
2962

    
2963
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
2964
                              prefix="x509-%s-" % utils.TimestampForFilename())
2965
  try:
2966
    name = os.path.basename(cert_dir)
2967
    assert len(name) > 5
2968

    
2969
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2970

    
2971
    utils.WriteFile(key_file, mode=0400, data=key_pem)
2972
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
2973

    
2974
    # Never return private key as it shouldn't leave the node
2975
    return (name, cert_pem)
2976
  except Exception:
2977
    shutil.rmtree(cert_dir, ignore_errors=True)
2978
    raise
2979

    
2980

    
2981
def RemoveX509Certificate(name, cryptodir=constants.CRYPTO_KEYS_DIR):
2982
  """Removes a X509 certificate.
2983

2984
  @type name: string
2985
  @param name: Certificate name
2986

2987
  """
2988
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2989

    
2990
  utils.RemoveFile(key_file)
2991
  utils.RemoveFile(cert_file)
2992

    
2993
  try:
2994
    os.rmdir(cert_dir)
2995
  except EnvironmentError, err:
2996
    _Fail("Cannot remove certificate directory '%s': %s",
2997
          cert_dir, err)
2998

    
2999

    
3000
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3001
  """Returns the command for the requested input/output.
3002

3003
  @type instance: L{objects.Instance}
3004
  @param instance: The instance object
3005
  @param mode: Import/export mode
3006
  @param ieio: Input/output type
3007
  @param ieargs: Input/output arguments
3008

3009
  """
3010
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3011

    
3012
  env = None
3013
  prefix = None
3014
  suffix = None
3015
  exp_size = None
3016

    
3017
  if ieio == constants.IEIO_FILE:
3018
    (filename, ) = ieargs
3019

    
3020
    if not utils.IsNormAbsPath(filename):
3021
      _Fail("Path '%s' is not normalized or absolute", filename)
3022

    
3023
    real_filename = os.path.realpath(filename)
3024
    directory = os.path.dirname(real_filename)
3025

    
3026
    if not utils.IsBelowDir(constants.EXPORT_DIR, real_filename):
3027
      _Fail("File '%s' is not under exports directory '%s': %s",
3028
            filename, constants.EXPORT_DIR, real_filename)
3029

    
3030
    # Create directory
3031
    utils.Makedirs(directory, mode=0750)
3032

    
3033
    quoted_filename = utils.ShellQuote(filename)
3034

    
3035
    if mode == constants.IEM_IMPORT:
3036
      suffix = "> %s" % quoted_filename
3037
    elif mode == constants.IEM_EXPORT:
3038
      suffix = "< %s" % quoted_filename
3039

    
3040
      # Retrieve file size
3041
      try:
3042
        st = os.stat(filename)
3043
      except EnvironmentError, err:
3044
        logging.error("Can't stat(2) %s: %s", filename, err)
3045
      else:
3046
        exp_size = utils.BytesToMebibyte(st.st_size)
3047

    
3048
  elif ieio == constants.IEIO_RAW_DISK:
3049
    (disk, ) = ieargs
3050

    
3051
    real_disk = _OpenRealBD(disk)
3052

    
3053
    if mode == constants.IEM_IMPORT:
3054
      # we set here a smaller block size as, due to transport buffering, more
3055
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3056
      # is not already there or we pass a wrong path; we use notrunc to no
3057
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3058
      # much memory; this means that at best, we flush every 64k, which will
3059
      # not be very fast
3060
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3061
                                    " bs=%s oflag=dsync"),
3062
                                    real_disk.dev_path,
3063
                                    str(64 * 1024))
3064

    
3065
    elif mode == constants.IEM_EXPORT:
3066
      # the block size on the read dd is 1MiB to match our units
3067
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3068
                                   real_disk.dev_path,
3069
                                   str(1024 * 1024), # 1 MB
3070
                                   str(disk.size))
3071
      exp_size = disk.size
3072

    
3073
  elif ieio == constants.IEIO_SCRIPT:
3074
    (disk, disk_index, ) = ieargs
3075

    
3076
    assert isinstance(disk_index, (int, long))
3077

    
3078
    real_disk = _OpenRealBD(disk)
3079

    
3080
    inst_os = OSFromDisk(instance.os)
3081
    env = OSEnvironment(instance, inst_os)
3082

    
3083
    if mode == constants.IEM_IMPORT:
3084
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3085
      env["IMPORT_INDEX"] = str(disk_index)
3086
      script = inst_os.import_script
3087

    
3088
    elif mode == constants.IEM_EXPORT:
3089
      env["EXPORT_DEVICE"] = real_disk.dev_path
3090
      env["EXPORT_INDEX"] = str(disk_index)
3091
      script = inst_os.export_script
3092

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

    
3096
    if mode == constants.IEM_IMPORT:
3097
      suffix = "| %s" % script_cmd
3098

    
3099
    elif mode == constants.IEM_EXPORT:
3100
      prefix = "%s |" % script_cmd
3101

    
3102
    # Let script predict size
3103
    exp_size = constants.IE_CUSTOM_SIZE
3104

    
3105
  else:
3106
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3107

    
3108
  return (env, prefix, suffix, exp_size)
3109

    
3110

    
3111
def _CreateImportExportStatusDir(prefix):
3112
  """Creates status directory for import/export.
3113

3114
  """
3115
  return tempfile.mkdtemp(dir=constants.IMPORT_EXPORT_DIR,
3116
                          prefix=("%s-%s-" %
3117
                                  (prefix, utils.TimestampForFilename())))
3118

    
3119

    
3120
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3121
                            ieio, ieioargs):
3122
  """Starts an import or export daemon.
3123

3124
  @param mode: Import/output mode
3125
  @type opts: L{objects.ImportExportOptions}
3126
  @param opts: Daemon options
3127
  @type host: string
3128
  @param host: Remote host for export (None for import)
3129
  @type port: int
3130
  @param port: Remote port for export (None for import)
3131
  @type instance: L{objects.Instance}
3132
  @param instance: Instance object
3133
  @type component: string
3134
  @param component: which part of the instance is transferred now,
3135
      e.g. 'disk/0'
3136
  @param ieio: Input/output type
3137
  @param ieioargs: Input/output arguments
3138

3139
  """
3140
  if mode == constants.IEM_IMPORT:
3141
    prefix = "import"
3142

    
3143
    if not (host is None and port is None):
3144
      _Fail("Can not specify host or port on import")
3145

    
3146
  elif mode == constants.IEM_EXPORT:
3147
    prefix = "export"
3148

    
3149
    if host is None or port is None:
3150
      _Fail("Host and port must be specified for an export")
3151

    
3152
  else:
3153
    _Fail("Invalid mode %r", mode)
3154

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

    
3158
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3159
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3160

    
3161
  if opts.key_name is None:
3162
    # Use server.pem
3163
    key_path = constants.NODED_CERT_FILE
3164
    cert_path = constants.NODED_CERT_FILE
3165
    assert opts.ca_pem is None
3166
  else:
3167
    (_, key_path, cert_path) = _GetX509Filenames(constants.CRYPTO_KEYS_DIR,
3168
                                                 opts.key_name)
3169
    assert opts.ca_pem is not None
3170

    
3171
  for i in [key_path, cert_path]:
3172
    if not os.path.exists(i):
3173
      _Fail("File '%s' does not exist" % i)
3174

    
3175
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3176
  try:
3177
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3178
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3179
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3180

    
3181
    if opts.ca_pem is None:
3182
      # Use server.pem
3183
      ca = utils.ReadFile(constants.NODED_CERT_FILE)
3184
    else:
3185
      ca = opts.ca_pem
3186

    
3187
    # Write CA file
3188
    utils.WriteFile(ca_file, data=ca, mode=0400)
3189

    
3190
    cmd = [
3191
      constants.IMPORT_EXPORT_DAEMON,
3192
      status_file, mode,
3193
      "--key=%s" % key_path,
3194
      "--cert=%s" % cert_path,
3195
      "--ca=%s" % ca_file,
3196
      ]
3197

    
3198
    if host:
3199
      cmd.append("--host=%s" % host)
3200

    
3201
    if port:
3202
      cmd.append("--port=%s" % port)
3203

    
3204
    if opts.ipv6:
3205
      cmd.append("--ipv6")
3206
    else:
3207
      cmd.append("--ipv4")
3208

    
3209
    if opts.compress:
3210
      cmd.append("--compress=%s" % opts.compress)
3211

    
3212
    if opts.magic:
3213
      cmd.append("--magic=%s" % opts.magic)
3214

    
3215
    if exp_size is not None:
3216
      cmd.append("--expected-size=%s" % exp_size)
3217

    
3218
    if cmd_prefix:
3219
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3220

    
3221
    if cmd_suffix:
3222
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3223

    
3224
    if mode == constants.IEM_EXPORT:
3225
      # Retry connection a few times when connecting to remote peer
3226
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3227
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3228
    elif opts.connect_timeout is not None:
3229
      assert mode == constants.IEM_IMPORT
3230
      # Overall timeout for establishing connection while listening
3231
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3232

    
3233
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3234

    
3235
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3236
    # support for receiving a file descriptor for output
3237
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3238
                      output=logfile)
3239

    
3240
    # The import/export name is simply the status directory name
3241
    return os.path.basename(status_dir)
3242

    
3243
  except Exception:
3244
    shutil.rmtree(status_dir, ignore_errors=True)
3245
    raise
3246

    
3247

    
3248
def GetImportExportStatus(names):
3249
  """Returns import/export daemon status.
3250

3251
  @type names: sequence
3252
  @param names: List of names
3253
  @rtype: List of dicts
3254
  @return: Returns a list of the state of each named import/export or None if a
3255
           status couldn't be read
3256

3257
  """
3258
  result = []
3259

    
3260
  for name in names:
3261
    status_file = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name,
3262
                                 _IES_STATUS_FILE)
3263

    
3264
    try:
3265
      data = utils.ReadFile(status_file)
3266
    except EnvironmentError, err:
3267
      if err.errno != errno.ENOENT:
3268
        raise
3269
      data = None
3270

    
3271
    if not data:
3272
      result.append(None)
3273
      continue
3274

    
3275
    result.append(serializer.LoadJson(data))
3276

    
3277
  return result
3278

    
3279

    
3280
def AbortImportExport(name):
3281
  """Sends SIGTERM to a running import/export daemon.
3282

3283
  """
3284
  logging.info("Abort import/export %s", name)
3285

    
3286
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3287
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3288

    
3289
  if pid:
3290
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3291
                 name, pid)
3292
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3293

    
3294

    
3295
def CleanupImportExport(name):
3296
  """Cleanup after an import or export.
3297

3298
  If the import/export daemon is still running it's killed. Afterwards the
3299
  whole status directory is removed.
3300

3301
  """
3302
  logging.info("Finalizing import/export %s", name)
3303

    
3304
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3305

    
3306
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3307

    
3308
  if pid:
3309
    logging.info("Import/export %s is still running with PID %s",
3310
                 name, pid)
3311
    utils.KillProcess(pid, waitpid=False)
3312

    
3313
  shutil.rmtree(status_dir, ignore_errors=True)
3314

    
3315

    
3316
def _FindDisks(nodes_ip, disks):
3317
  """Sets the physical ID on disks and returns the block devices.
3318

3319
  """
3320
  # set the correct physical ID
3321
  my_name = netutils.Hostname.GetSysName()
3322
  for cf in disks:
3323
    cf.SetPhysicalID(my_name, nodes_ip)
3324

    
3325
  bdevs = []
3326

    
3327
  for cf in disks:
3328
    rd = _RecursiveFindBD(cf)
3329
    if rd is None:
3330
      _Fail("Can't find device %s", cf)
3331
    bdevs.append(rd)
3332
  return bdevs
3333

    
3334

    
3335
def DrbdDisconnectNet(nodes_ip, disks):
3336
  """Disconnects the network on a list of drbd devices.
3337

3338
  """
3339
  bdevs = _FindDisks(nodes_ip, disks)
3340

    
3341
  # disconnect disks
3342
  for rd in bdevs:
3343
    try:
3344
      rd.DisconnectNet()
3345
    except errors.BlockDeviceError, err:
3346
      _Fail("Can't change network configuration to standalone mode: %s",
3347
            err, exc=True)
3348

    
3349

    
3350
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3351
  """Attaches the network on a list of drbd devices.
3352

3353
  """
3354
  bdevs = _FindDisks(nodes_ip, disks)
3355

    
3356
  if multimaster:
3357
    for idx, rd in enumerate(bdevs):
3358
      try:
3359
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3360
      except EnvironmentError, err:
3361
        _Fail("Can't create symlink: %s", err)
3362
  # reconnect disks, switch to new master configuration and if
3363
  # needed primary mode
3364
  for rd in bdevs:
3365
    try:
3366
      rd.AttachNet(multimaster)
3367
    except errors.BlockDeviceError, err:
3368
      _Fail("Can't change network configuration: %s", err)
3369

    
3370
  # wait until the disks are connected; we need to retry the re-attach
3371
  # if the device becomes standalone, as this might happen if the one
3372
  # node disconnects and reconnects in a different mode before the
3373
  # other node reconnects; in this case, one or both of the nodes will
3374
  # decide it has wrong configuration and switch to standalone
3375

    
3376
  def _Attach():
3377
    all_connected = True
3378

    
3379
    for rd in bdevs:
3380
      stats = rd.GetProcStatus()
3381

    
3382
      all_connected = (all_connected and
3383
                       (stats.is_connected or stats.is_in_resync))
3384

    
3385
      if stats.is_standalone:
3386
        # peer had different config info and this node became
3387
        # standalone, even though this should not happen with the
3388
        # new staged way of changing disk configs
3389
        try:
3390
          rd.AttachNet(multimaster)
3391
        except errors.BlockDeviceError, err:
3392
          _Fail("Can't change network configuration: %s", err)
3393

    
3394
    if not all_connected:
3395
      raise utils.RetryAgain()
3396

    
3397
  try:
3398
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3399
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3400
  except utils.RetryTimeout:
3401
    _Fail("Timeout in disk reconnecting")
3402

    
3403
  if multimaster:
3404
    # change to primary mode
3405
    for rd in bdevs:
3406
      try:
3407
        rd.Open()
3408
      except errors.BlockDeviceError, err:
3409
        _Fail("Can't change to primary mode: %s", err)
3410

    
3411

    
3412
def DrbdWaitSync(nodes_ip, disks):
3413
  """Wait until DRBDs have synchronized.
3414

3415
  """
3416
  def _helper(rd):
3417
    stats = rd.GetProcStatus()
3418
    if not (stats.is_connected or stats.is_in_resync):
3419
      raise utils.RetryAgain()
3420
    return stats
3421

    
3422
  bdevs = _FindDisks(nodes_ip, disks)
3423

    
3424
  min_resync = 100
3425
  alldone = True
3426
  for rd in bdevs:
3427
    try:
3428
      # poll each second for 15 seconds
3429
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3430
    except utils.RetryTimeout:
3431
      stats = rd.GetProcStatus()
3432
      # last check
3433
      if not (stats.is_connected or stats.is_in_resync):
3434
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3435
    alldone = alldone and (not stats.is_in_resync)
3436
    if stats.sync_percent is not None:
3437
      min_resync = min(min_resync, stats.sync_percent)
3438

    
3439
  return (alldone, min_resync)
3440

    
3441

    
3442
def GetDrbdUsermodeHelper():
3443
  """Returns DRBD usermode helper currently configured.
3444

3445
  """
3446
  try:
3447
    return bdev.BaseDRBD.GetUsermodeHelper()
3448
  except errors.BlockDeviceError, err:
3449
    _Fail(str(err))
3450

    
3451

    
3452
def PowercycleNode(hypervisor_type):
3453
  """Hard-powercycle the node.
3454

3455
  Because we need to return first, and schedule the powercycle in the
3456
  background, we won't be able to report failures nicely.
3457

3458
  """
3459
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3460
  try:
3461
    pid = os.fork()
3462
  except OSError:
3463
    # if we can't fork, we'll pretend that we're in the child process
3464
    pid = 0
3465
  if pid > 0:
3466
    return "Reboot scheduled in 5 seconds"
3467
  # ensure the child is running on ram
3468
  try:
3469
    utils.Mlockall()
3470
  except Exception: # pylint: disable=W0703
3471
    pass
3472
  time.sleep(5)
3473
  hyper.PowercycleNode()
3474

    
3475

    
3476
class HooksRunner(object):
3477
  """Hook runner.
3478

3479
  This class is instantiated on the node side (ganeti-noded) and not
3480
  on the master side.
3481

3482
  """
3483
  def __init__(self, hooks_base_dir=None):
3484
    """Constructor for hooks runner.
3485

3486
    @type hooks_base_dir: str or None
3487
    @param hooks_base_dir: if not None, this overrides the
3488
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
3489

3490
    """
3491
    if hooks_base_dir is None:
3492
      hooks_base_dir = constants.HOOKS_BASE_DIR
3493
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3494
    # constant
3495
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
3496

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

3500
    """
3501
    assert len(node_list) == 1
3502
    node = node_list[0]
3503
    _, myself = ssconf.GetMasterAndMyself()
3504
    assert node == myself
3505

    
3506
    results = self.RunHooks(hpath, phase, env)
3507

    
3508
    # Return values in the form expected by HooksMaster
3509
    return {node: (None, False, results)}
3510

    
3511
  def RunHooks(self, hpath, phase, env):
3512
    """Run the scripts in the hooks directory.
3513

3514
    @type hpath: str
3515
    @param hpath: the path to the hooks directory which
3516
        holds the scripts
3517
    @type phase: str
3518
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
3519
        L{constants.HOOKS_PHASE_POST}
3520
    @type env: dict
3521
    @param env: dictionary with the environment for the hook
3522
    @rtype: list
3523
    @return: list of 3-element tuples:
3524
      - script path
3525
      - script result, either L{constants.HKR_SUCCESS} or
3526
        L{constants.HKR_FAIL}
3527
      - output of the script
3528

3529
    @raise errors.ProgrammerError: for invalid input
3530
        parameters
3531

3532
    """
3533
    if phase == constants.HOOKS_PHASE_PRE:
3534
      suffix = "pre"
3535
    elif phase == constants.HOOKS_PHASE_POST:
3536
      suffix = "post"
3537
    else:
3538
      _Fail("Unknown hooks phase '%s'", phase)
3539

    
3540
    subdir = "%s-%s.d" % (hpath, suffix)
3541
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3542

    
3543
    results = []
3544

    
3545
    if not os.path.isdir(dir_name):
3546
      # for non-existing/non-dirs, we simply exit instead of logging a
3547
      # warning at every operation
3548
      return results
3549

    
3550
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3551

    
3552
    for (relname, relstatus, runresult)  in runparts_results:
3553
      if relstatus == constants.RUNPARTS_SKIP:
3554
        rrval = constants.HKR_SKIP
3555
        output = ""
3556
      elif relstatus == constants.RUNPARTS_ERR:
3557
        rrval = constants.HKR_FAIL
3558
        output = "Hook script execution error: %s" % runresult
3559
      elif relstatus == constants.RUNPARTS_RUN:
3560
        if runresult.failed:
3561
          rrval = constants.HKR_FAIL
3562
        else:
3563
          rrval = constants.HKR_SUCCESS
3564
        output = utils.SafeEncode(runresult.output.strip())
3565
      results.append(("%s/%s" % (subdir, relname), rrval, output))
3566

    
3567
    return results
3568

    
3569

    
3570
class IAllocatorRunner(object):
3571
  """IAllocator runner.
3572

3573
  This class is instantiated on the node side (ganeti-noded) and not on
3574
  the master side.
3575

3576
  """
3577
  @staticmethod
3578
  def Run(name, idata):
3579
    """Run an iallocator script.
3580

3581
    @type name: str
3582
    @param name: the iallocator script name
3583
    @type idata: str
3584
    @param idata: the allocator input data
3585

3586
    @rtype: tuple
3587
    @return: two element tuple of:
3588
       - status
3589
       - either error message or stdout of allocator (for success)
3590

3591
    """
3592
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
3593
                                  os.path.isfile)
3594
    if alloc_script is None:
3595
      _Fail("iallocator module '%s' not found in the search path", name)
3596

    
3597
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
3598
    try:
3599
      os.write(fd, idata)
3600
      os.close(fd)
3601
      result = utils.RunCmd([alloc_script, fin_name])
3602
      if result.failed:
3603
        _Fail("iallocator module '%s' failed: %s, output '%s'",
3604
              name, result.fail_reason, result.output)
3605
    finally:
3606
      os.unlink(fin_name)
3607

    
3608
    return result.stdout
3609

    
3610

    
3611
class DevCacheManager(object):
3612
  """Simple class for managing a cache of block device information.
3613

3614
  """
3615
  _DEV_PREFIX = "/dev/"
3616
  _ROOT_DIR = constants.BDEV_CACHE_DIR
3617

    
3618
  @classmethod
3619
  def _ConvertPath(cls, dev_path):
3620
    """Converts a /dev/name path to the cache file name.
3621

3622
    This replaces slashes with underscores and strips the /dev
3623
    prefix. It then returns the full path to the cache file.
3624

3625
    @type dev_path: str
3626
    @param dev_path: the C{/dev/} path name
3627
    @rtype: str
3628
    @return: the converted path name
3629

3630
    """
3631
    if dev_path.startswith(cls._DEV_PREFIX):
3632
      dev_path = dev_path[len(cls._DEV_PREFIX):]
3633
    dev_path = dev_path.replace("/", "_")
3634
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
3635
    return fpath
3636

    
3637
  @classmethod
3638
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
3639
    """Updates the cache information for a given device.
3640

3641
    @type dev_path: str
3642
    @param dev_path: the pathname of the device
3643
    @type owner: str
3644
    @param owner: the owner (instance name) of the device
3645
    @type on_primary: bool
3646
    @param on_primary: whether this is the primary
3647
        node nor not
3648
    @type iv_name: str
3649
    @param iv_name: the instance-visible name of the
3650
        device, as in objects.Disk.iv_name
3651

3652
    @rtype: None
3653

3654
    """
3655
    if dev_path is None:
3656
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
3657
      return
3658
    fpath = cls._ConvertPath(dev_path)
3659
    if on_primary:
3660
      state = "primary"
3661
    else:
3662
      state = "secondary"
3663
    if iv_name is None:
3664
      iv_name = "not_visible"
3665
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
3666
    try:
3667
      utils.WriteFile(fpath, data=fdata)
3668
    except EnvironmentError, err:
3669
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
3670

    
3671
  @classmethod
3672
  def RemoveCache(cls, dev_path):
3673
    """Remove data for a dev_path.
3674

3675
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
3676
    path name and logging.
3677

3678
    @type dev_path: str
3679
    @param dev_path: the pathname of the device
3680

3681
    @rtype: None
3682

3683
    """
3684
    if dev_path is None:
3685
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
3686
      return
3687
    fpath = cls._ConvertPath(dev_path)
3688
    try:
3689
      utils.RemoveFile(fpath)
3690
    except EnvironmentError, err:
3691
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)