Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 17b0b812

History | View | Annotate | Download (111.7 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_USERSCRIPTS in what:
670
    result[constants.NV_USERSCRIPTS] = \
671
      [script for script in what[constants.NV_USERSCRIPTS]
672
       if not (os.path.exists(script) and os.access(script, os.X_OK))]
673

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

    
690
  if constants.NV_LVLIST in what and vm_capable:
691
    try:
692
      val = GetVolumeList(utils.ListVolumeGroups().keys())
693
    except RPCFail, err:
694
      val = str(err)
695
    result[constants.NV_LVLIST] = val
696

    
697
  if constants.NV_INSTANCELIST in what and vm_capable:
698
    # GetInstanceList can fail
699
    try:
700
      val = GetInstanceList(what[constants.NV_INSTANCELIST])
701
    except RPCFail, err:
702
      val = str(err)
703
    result[constants.NV_INSTANCELIST] = val
704

    
705
  if constants.NV_VGLIST in what and vm_capable:
706
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
707

    
708
  if constants.NV_PVLIST in what and vm_capable:
709
    result[constants.NV_PVLIST] = \
710
      bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
711
                                   filter_allocatable=False)
712

    
713
  if constants.NV_VERSION in what:
714
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
715
                                    constants.RELEASE_VERSION)
716

    
717
  if constants.NV_HVINFO in what and vm_capable:
718
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
719
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
720

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

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

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

    
751
  if constants.NV_TIME in what:
752
    result[constants.NV_TIME] = utils.SplitTime(time.time())
753

    
754
  if constants.NV_OSLIST in what and vm_capable:
755
    result[constants.NV_OSLIST] = DiagnoseOS()
756

    
757
  if constants.NV_BRIDGES in what and vm_capable:
758
    result[constants.NV_BRIDGES] = [bridge
759
                                    for bridge in what[constants.NV_BRIDGES]
760
                                    if not utils.BridgeExists(bridge)]
761
  return result
762

    
763

    
764
def GetBlockDevSizes(devices):
765
  """Return the size of the given block devices
766

767
  @type devices: list
768
  @param devices: list of block device nodes to query
769
  @rtype: dict
770
  @return:
771
    dictionary of all block devices under /dev (key). The value is their
772
    size in MiB.
773

774
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
775

776
  """
777
  DEV_PREFIX = "/dev/"
778
  blockdevs = {}
779

    
780
  for devpath in devices:
781
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
782
      continue
783

    
784
    try:
785
      st = os.stat(devpath)
786
    except EnvironmentError, err:
787
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
788
      continue
789

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

    
797
      size = int(result.stdout) / (1024 * 1024)
798
      blockdevs[devpath] = size
799
  return blockdevs
800

    
801

    
802
def GetVolumeList(vg_names):
803
  """Compute list of logical volumes and their size.
804

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

813
        {'xenvg/test1': ('20.06', True, True)}
814

815
      in case of errors, a string is returned with the error
816
      details.
817

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

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

    
845
  return lvs
846

    
847

    
848
def ListVolumeGroups():
849
  """List the volume groups and their size.
850

851
  @rtype: dict
852
  @return: dictionary with keys volume name and values the
853
      size of the volume
854

855
  """
856
  return utils.ListVolumeGroups()
857

    
858

    
859
def NodeVolumes():
860
  """List all volumes on this node.
861

862
  @rtype: list
863
  @return:
864
    A list of dictionaries, each having four keys:
865
      - name: the logical volume name,
866
      - size: the size of the logical volume
867
      - dev: the physical device on which the LV lives
868
      - vg: the volume group to which it belongs
869

870
    In case of errors, we return an empty list and log the
871
    error.
872

873
    Note that since a logical volume can live on multiple physical
874
    volumes, the resulting list might include a logical volume
875
    multiple times.
876

877
  """
878
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
879
                         "--separator=|",
880
                         "--options=lv_name,lv_size,devices,vg_name"])
881
  if result.failed:
882
    _Fail("Failed to list logical volumes, lvs output: %s",
883
          result.output)
884

    
885
  def parse_dev(dev):
886
    return dev.split("(")[0]
887

    
888
  def handle_dev(dev):
889
    return [parse_dev(x) for x in dev.split(",")]
890

    
891
  def map_line(line):
892
    line = [v.strip() for v in line]
893
    return [{"name": line[0], "size": line[1],
894
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
895

    
896
  all_devs = []
897
  for line in result.stdout.splitlines():
898
    if line.count("|") >= 3:
899
      all_devs.extend(map_line(line.split("|")))
900
    else:
901
      logging.warning("Strange line in the output from lvs: '%s'", line)
902
  return all_devs
903

    
904

    
905
def BridgesExist(bridges_list):
906
  """Check if a list of bridges exist on the current node.
907

908
  @rtype: boolean
909
  @return: C{True} if all of them exist, C{False} otherwise
910

911
  """
912
  missing = []
913
  for bridge in bridges_list:
914
    if not utils.BridgeExists(bridge):
915
      missing.append(bridge)
916

    
917
  if missing:
918
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
919

    
920

    
921
def GetInstanceList(hypervisor_list):
922
  """Provides a list of instances.
923

924
  @type hypervisor_list: list
925
  @param hypervisor_list: the list of hypervisors to query information
926

927
  @rtype: list
928
  @return: a list of all running instances on the current node
929
    - instance1.example.com
930
    - instance2.example.com
931

932
  """
933
  results = []
934
  for hname in hypervisor_list:
935
    try:
936
      names = hypervisor.GetHypervisor(hname).ListInstances()
937
      results.extend(names)
938
    except errors.HypervisorError, err:
939
      _Fail("Error enumerating instances (hypervisor %s): %s",
940
            hname, err, exc=True)
941

    
942
  return results
943

    
944

    
945
def GetInstanceInfo(instance, hname):
946
  """Gives back the information about an instance as a dictionary.
947

948
  @type instance: string
949
  @param instance: the instance name
950
  @type hname: string
951
  @param hname: the hypervisor type of the instance
952

953
  @rtype: dict
954
  @return: dictionary with the following keys:
955
      - memory: memory size of instance (int)
956
      - state: xen state of instance (string)
957
      - time: cpu time of instance (float)
958

959
  """
960
  output = {}
961

    
962
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
963
  if iinfo is not None:
964
    output["memory"] = iinfo[2]
965
    output["state"] = iinfo[4]
966
    output["time"] = iinfo[5]
967

    
968
  return output
969

    
970

    
971
def GetInstanceMigratable(instance):
972
  """Gives whether an instance can be migrated.
973

974
  @type instance: L{objects.Instance}
975
  @param instance: object representing the instance to be checked.
976

977
  @rtype: tuple
978
  @return: tuple of (result, description) where:
979
      - result: whether the instance can be migrated or not
980
      - description: a description of the issue, if relevant
981

982
  """
983
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
984
  iname = instance.name
985
  if iname not in hyper.ListInstances():
986
    _Fail("Instance %s is not running", iname)
987

    
988
  for idx in range(len(instance.disks)):
989
    link_name = _GetBlockDevSymlinkPath(iname, idx)
990
    if not os.path.islink(link_name):
991
      logging.warning("Instance %s is missing symlink %s for disk %d",
992
                      iname, link_name, idx)
993

    
994

    
995
def GetAllInstancesInfo(hypervisor_list):
996
  """Gather data about all instances.
997

998
  This is the equivalent of L{GetInstanceInfo}, except that it
999
  computes data for all instances at once, thus being faster if one
1000
  needs data about more than one instance.
1001

1002
  @type hypervisor_list: list
1003
  @param hypervisor_list: list of hypervisors to query for instance data
1004

1005
  @rtype: dict
1006
  @return: dictionary of instance: data, with data having the following keys:
1007
      - memory: memory size of instance (int)
1008
      - state: xen state of instance (string)
1009
      - time: cpu time of instance (float)
1010
      - vcpus: the number of vcpus
1011

1012
  """
1013
  output = {}
1014

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

    
1035
  return output
1036

    
1037

    
1038
def _InstanceLogName(kind, os_name, instance, component):
1039
  """Compute the OS log filename for a given instance and operation.
1040

1041
  The instance name and os name are passed in as strings since not all
1042
  operations have these as part of an instance object.
1043

1044
  @type kind: string
1045
  @param kind: the operation type (e.g. add, import, etc.)
1046
  @type os_name: string
1047
  @param os_name: the os name
1048
  @type instance: string
1049
  @param instance: the name of the instance being imported/added/etc.
1050
  @type component: string or None
1051
  @param component: the name of the component of the instance being
1052
      transferred
1053

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

    
1065

    
1066
def InstanceOsAdd(instance, reinstall, debug):
1067
  """Add an OS to an instance.
1068

1069
  @type instance: L{objects.Instance}
1070
  @param instance: Instance whose OS is to be installed
1071
  @type reinstall: boolean
1072
  @param reinstall: whether this is an instance reinstall
1073
  @type debug: integer
1074
  @param debug: debug level, passed to the OS scripts
1075
  @rtype: None
1076

1077
  """
1078
  inst_os = OSFromDisk(instance.os)
1079

    
1080
  create_env = OSEnvironment(instance, inst_os, debug)
1081
  if reinstall:
1082
    create_env["INSTANCE_REINSTALL"] = "1"
1083

    
1084
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1085

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

    
1097

    
1098
def RunRenameInstance(instance, old_name, debug):
1099
  """Run the OS rename script for an instance.
1100

1101
  @type instance: L{objects.Instance}
1102
  @param instance: Instance whose OS is to be installed
1103
  @type old_name: string
1104
  @param old_name: previous instance name
1105
  @type debug: integer
1106
  @param debug: debug level, passed to the OS scripts
1107
  @rtype: boolean
1108
  @return: the success of the operation
1109

1110
  """
1111
  inst_os = OSFromDisk(instance.os)
1112

    
1113
  rename_env = OSEnvironment(instance, inst_os, debug)
1114
  rename_env["OLD_INSTANCE_NAME"] = old_name
1115

    
1116
  logfile = _InstanceLogName("rename", instance.os,
1117
                             "%s-%s" % (old_name, instance.name), None)
1118

    
1119
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1120
                        cwd=inst_os.path, output=logfile, reset_env=True)
1121

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

    
1130

    
1131
def _GetBlockDevSymlinkPath(instance_name, idx):
1132
  return utils.PathJoin(constants.DISK_LINKS_DIR, "%s%s%d" %
1133
                        (instance_name, constants.DISK_SEPARATOR, idx))
1134

    
1135

    
1136
def _SymlinkBlockDev(instance_name, device_path, idx):
1137
  """Set up symlinks to a instance's block device.
1138

1139
  This is an auxiliary function run when an instance is start (on the primary
1140
  node) or when an instance is migrated (on the target node).
1141

1142

1143
  @param instance_name: the name of the target instance
1144
  @param device_path: path of the physical block device, on the node
1145
  @param idx: the disk index
1146
  @return: absolute path to the disk's symlink
1147

1148
  """
1149
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1150
  try:
1151
    os.symlink(device_path, link_name)
1152
  except OSError, err:
1153
    if err.errno == errno.EEXIST:
1154
      if (not os.path.islink(link_name) or
1155
          os.readlink(link_name) != device_path):
1156
        os.remove(link_name)
1157
        os.symlink(device_path, link_name)
1158
    else:
1159
      raise
1160

    
1161
  return link_name
1162

    
1163

    
1164
def _RemoveBlockDevLinks(instance_name, disks):
1165
  """Remove the block device symlinks belonging to the given instance.
1166

1167
  """
1168
  for idx, _ in enumerate(disks):
1169
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1170
    if os.path.islink(link_name):
1171
      try:
1172
        os.remove(link_name)
1173
      except OSError:
1174
        logging.exception("Can't remove symlink '%s'", link_name)
1175

    
1176

    
1177
def _GatherAndLinkBlockDevs(instance):
1178
  """Set up an instance's block device(s).
1179

1180
  This is run on the primary node at instance startup. The block
1181
  devices must be already assembled.
1182

1183
  @type instance: L{objects.Instance}
1184
  @param instance: the instance whose disks we shoul assemble
1185
  @rtype: list
1186
  @return: list of (disk_object, device_path)
1187

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

    
1202
    block_devices.append((disk, link_name))
1203

    
1204
  return block_devices
1205

    
1206

    
1207
def StartInstance(instance, startup_paused):
1208
  """Start an instance.
1209

1210
  @type instance: L{objects.Instance}
1211
  @param instance: the instance object
1212
  @type startup_paused: bool
1213
  @param instance: pause instance at startup?
1214
  @rtype: None
1215

1216
  """
1217
  running_instances = GetInstanceList([instance.hypervisor])
1218

    
1219
  if instance.name in running_instances:
1220
    logging.info("Instance %s already running, not starting", instance.name)
1221
    return
1222

    
1223
  try:
1224
    block_devices = _GatherAndLinkBlockDevs(instance)
1225
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1226
    hyper.StartInstance(instance, block_devices, startup_paused)
1227
  except errors.BlockDeviceError, err:
1228
    _Fail("Block device error: %s", err, exc=True)
1229
  except errors.HypervisorError, err:
1230
    _RemoveBlockDevLinks(instance.name, instance.disks)
1231
    _Fail("Hypervisor error: %s", err, exc=True)
1232

    
1233

    
1234
def InstanceShutdown(instance, timeout):
1235
  """Shut an instance down.
1236

1237
  @note: this functions uses polling with a hardcoded timeout.
1238

1239
  @type instance: L{objects.Instance}
1240
  @param instance: the instance object
1241
  @type timeout: integer
1242
  @param timeout: maximum timeout for soft shutdown
1243
  @rtype: None
1244

1245
  """
1246
  hv_name = instance.hypervisor
1247
  hyper = hypervisor.GetHypervisor(hv_name)
1248
  iname = instance.name
1249

    
1250
  if instance.name not in hyper.ListInstances():
1251
    logging.info("Instance %s not running, doing nothing", iname)
1252
    return
1253

    
1254
  class _TryShutdown:
1255
    def __init__(self):
1256
      self.tried_once = False
1257

    
1258
    def __call__(self):
1259
      if iname not in hyper.ListInstances():
1260
        return
1261

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

    
1270
        _Fail("Failed to stop instance %s: %s", iname, err)
1271

    
1272
      self.tried_once = True
1273

    
1274
      raise utils.RetryAgain()
1275

    
1276
  try:
1277
    utils.Retry(_TryShutdown(), 5, timeout)
1278
  except utils.RetryTimeout:
1279
    # the shutdown did not succeed
1280
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1281

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

    
1290
    time.sleep(1)
1291

    
1292
    if iname in hyper.ListInstances():
1293
      _Fail("Could not shutdown instance %s even by destroy", iname)
1294

    
1295
  try:
1296
    hyper.CleanupInstance(instance.name)
1297
  except errors.HypervisorError, err:
1298
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1299

    
1300
  _RemoveBlockDevLinks(iname, instance.disks)
1301

    
1302

    
1303
def InstanceReboot(instance, reboot_type, shutdown_timeout):
1304
  """Reboot an instance.
1305

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

1323
  """
1324
  running_instances = GetInstanceList([instance.hypervisor])
1325

    
1326
  if instance.name not in running_instances:
1327
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1328

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

    
1344

    
1345
def MigrationInfo(instance):
1346
  """Gather information about an instance to be migrated.
1347

1348
  @type instance: L{objects.Instance}
1349
  @param instance: the instance definition
1350

1351
  """
1352
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1353
  try:
1354
    info = hyper.MigrationInfo(instance)
1355
  except errors.HypervisorError, err:
1356
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1357
  return info
1358

    
1359

    
1360
def AcceptInstance(instance, info, target):
1361
  """Prepare the node to accept an instance.
1362

1363
  @type instance: L{objects.Instance}
1364
  @param instance: the instance definition
1365
  @type info: string/data (opaque)
1366
  @param info: migration information, from the source node
1367
  @type target: string
1368
  @param target: target host (usually ip), on this node
1369

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

    
1380
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1381
  try:
1382
    hyper.AcceptInstance(instance, info, target)
1383
  except errors.HypervisorError, err:
1384
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1385
      _RemoveBlockDevLinks(instance.name, instance.disks)
1386
    _Fail("Failed to accept instance: %s", err, exc=True)
1387

    
1388

    
1389
def FinalizeMigrationDst(instance, info, success):
1390
  """Finalize any preparation to accept an instance.
1391

1392
  @type instance: L{objects.Instance}
1393
  @param instance: the instance definition
1394
  @type info: string/data (opaque)
1395
  @param info: migration information, from the source node
1396
  @type success: boolean
1397
  @param success: whether the migration was a success or a failure
1398

1399
  """
1400
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1401
  try:
1402
    hyper.FinalizeMigrationDst(instance, info, success)
1403
  except errors.HypervisorError, err:
1404
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1405

    
1406

    
1407
def MigrateInstance(instance, target, live):
1408
  """Migrates an instance to another node.
1409

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

1419
  """
1420
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1421

    
1422
  try:
1423
    hyper.MigrateInstance(instance, target, live)
1424
  except errors.HypervisorError, err:
1425
    _Fail("Failed to migrate instance: %s", err, exc=True)
1426

    
1427

    
1428
def FinalizeMigrationSource(instance, success, live):
1429
  """Finalize the instance migration on the source node.
1430

1431
  @type instance: L{objects.Instance}
1432
  @param instance: the instance definition of the migrated instance
1433
  @type success: bool
1434
  @param success: whether the migration succeeded or not
1435
  @type live: bool
1436
  @param live: whether the user requested a live migration or not
1437
  @raise RPCFail: If the execution fails for some reason
1438

1439
  """
1440
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1441

    
1442
  try:
1443
    hyper.FinalizeMigrationSource(instance, success, live)
1444
  except Exception, err:  # pylint: disable=W0703
1445
    _Fail("Failed to finalize the migration on the source node: %s", err,
1446
          exc=True)
1447

    
1448

    
1449
def GetMigrationStatus(instance):
1450
  """Get the migration status
1451

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

1460
  """
1461
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1462
  try:
1463
    return hyper.GetMigrationStatus(instance)
1464
  except Exception, err:  # pylint: disable=W0703
1465
    _Fail("Failed to get migration status: %s", err, exc=True)
1466

    
1467

    
1468
def BlockdevCreate(disk, size, owner, on_primary, info):
1469
  """Creates a block device for an instance.
1470

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

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

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

    
1508
  try:
1509
    device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
1510
  except errors.BlockDeviceError, err:
1511
    _Fail("Can't create block device: %s", err)
1512

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

    
1527
  device.SetInfo(info)
1528

    
1529
  return device.unique_id
1530

    
1531

    
1532
def _WipeDevice(path, offset, size):
1533
  """This function actually wipes the device.
1534

1535
  @param path: The path to the device to wipe
1536
  @param offset: The offset in MiB in the file
1537
  @param size: The size in MiB to write
1538

1539
  """
1540
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1541
         "bs=%d" % constants.WIPE_BLOCK_SIZE, "oflag=direct", "of=%s" % path,
1542
         "count=%d" % size]
1543
  result = utils.RunCmd(cmd)
1544

    
1545
  if result.failed:
1546
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1547
          result.fail_reason, result.output)
1548

    
1549

    
1550
def BlockdevWipe(disk, offset, size):
1551
  """Wipes a block device.
1552

1553
  @type disk: L{objects.Disk}
1554
  @param disk: the disk object we want to wipe
1555
  @type offset: int
1556
  @param offset: The offset in MiB in the file
1557
  @type size: int
1558
  @param size: The size in MiB to write
1559

1560
  """
1561
  try:
1562
    rdev = _RecursiveFindBD(disk)
1563
  except errors.BlockDeviceError:
1564
    rdev = None
1565

    
1566
  if not rdev:
1567
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1568

    
1569
  # Do cross verify some of the parameters
1570
  if offset > rdev.size:
1571
    _Fail("Offset is bigger than device size")
1572
  if (offset + size) > rdev.size:
1573
    _Fail("The provided offset and size to wipe is bigger than device size")
1574

    
1575
  _WipeDevice(rdev.dev_path, offset, size)
1576

    
1577

    
1578
def BlockdevPauseResumeSync(disks, pause):
1579
  """Pause or resume the sync of the block device.
1580

1581
  @type disks: list of L{objects.Disk}
1582
  @param disks: the disks object we want to pause/resume
1583
  @type pause: bool
1584
  @param pause: Wheater to pause or resume
1585

1586
  """
1587
  success = []
1588
  for disk in disks:
1589
    try:
1590
      rdev = _RecursiveFindBD(disk)
1591
    except errors.BlockDeviceError:
1592
      rdev = None
1593

    
1594
    if not rdev:
1595
      success.append((False, ("Cannot change sync for device %s:"
1596
                              " device not found" % disk.iv_name)))
1597
      continue
1598

    
1599
    result = rdev.PauseResumeSync(pause)
1600

    
1601
    if result:
1602
      success.append((result, None))
1603
    else:
1604
      if pause:
1605
        msg = "Pause"
1606
      else:
1607
        msg = "Resume"
1608
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1609

    
1610
  return success
1611

    
1612

    
1613
def BlockdevRemove(disk):
1614
  """Remove a block device.
1615

1616
  @note: This is intended to be called recursively.
1617

1618
  @type disk: L{objects.Disk}
1619
  @param disk: the disk object we should remove
1620
  @rtype: boolean
1621
  @return: the success of the operation
1622

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

    
1640
  if disk.children:
1641
    for child in disk.children:
1642
      try:
1643
        BlockdevRemove(child)
1644
      except RPCFail, err:
1645
        msgs.append(str(err))
1646

    
1647
  if msgs:
1648
    _Fail("; ".join(msgs))
1649

    
1650

    
1651
def _RecursiveAssembleBD(disk, owner, as_primary):
1652
  """Activate a block device for an instance.
1653

1654
  This is run on the primary and secondary nodes for an instance.
1655

1656
  @note: this function is called recursively.
1657

1658
  @type disk: L{objects.Disk}
1659
  @param disk: the disk we try to assemble
1660
  @type owner: str
1661
  @param owner: the name of the instance which owns the disk
1662
  @type as_primary: boolean
1663
  @param as_primary: if we should make the block device
1664
      read/write
1665

1666
  @return: the assembled device or None (in case no device
1667
      was assembled)
1668
  @raise errors.BlockDeviceError: in case there is an error
1669
      during the activation of the children or the device
1670
      itself
1671

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

    
1691
  if as_primary or disk.AssembleOnSecondary():
1692
    r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
1693
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1694
    result = r_dev
1695
    if as_primary or disk.OpenOnSecondary():
1696
      r_dev.Open()
1697
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1698
                                as_primary, disk.iv_name)
1699

    
1700
  else:
1701
    result = True
1702
  return result
1703

    
1704

    
1705
def BlockdevAssemble(disk, owner, as_primary, idx):
1706
  """Activate a block device for an instance.
1707

1708
  This is a wrapper over _RecursiveAssembleBD.
1709

1710
  @rtype: str or boolean
1711
  @return: a C{/dev/...} path for primary nodes, and
1712
      C{True} for secondary nodes
1713

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

    
1727
  return result
1728

    
1729

    
1730
def BlockdevShutdown(disk):
1731
  """Shut down a block device.
1732

1733
  First, if the device is assembled (Attach() is successful), then
1734
  the device is shutdown. Then the children of the device are
1735
  shutdown.
1736

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

1741
  @type disk: L{objects.Disk}
1742
  @param disk: the description of the disk we should
1743
      shutdown
1744
  @rtype: None
1745

1746
  """
1747
  msgs = []
1748
  r_dev = _RecursiveFindBD(disk)
1749
  if r_dev is not None:
1750
    r_path = r_dev.dev_path
1751
    try:
1752
      r_dev.Shutdown()
1753
      DevCacheManager.RemoveCache(r_path)
1754
    except errors.BlockDeviceError, err:
1755
      msgs.append(str(err))
1756

    
1757
  if disk.children:
1758
    for child in disk.children:
1759
      try:
1760
        BlockdevShutdown(child)
1761
      except RPCFail, err:
1762
        msgs.append(str(err))
1763

    
1764
  if msgs:
1765
    _Fail("; ".join(msgs))
1766

    
1767

    
1768
def BlockdevAddchildren(parent_cdev, new_cdevs):
1769
  """Extend a mirrored block device.
1770

1771
  @type parent_cdev: L{objects.Disk}
1772
  @param parent_cdev: the disk to which we should add children
1773
  @type new_cdevs: list of L{objects.Disk}
1774
  @param new_cdevs: the list of children which we should add
1775
  @rtype: None
1776

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

    
1786

    
1787
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1788
  """Shrink a mirrored block device.
1789

1790
  @type parent_cdev: L{objects.Disk}
1791
  @param parent_cdev: the disk from which we should remove children
1792
  @type new_cdevs: list of L{objects.Disk}
1793
  @param new_cdevs: the list of children which we should remove
1794
  @rtype: None
1795

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

    
1815

    
1816
def BlockdevGetmirrorstatus(disks):
1817
  """Get the mirroring status of a list of devices.
1818

1819
  @type disks: list of L{objects.Disk}
1820
  @param disks: the list of disks which we should query
1821
  @rtype: disk
1822
  @return: List of L{objects.BlockDevStatus}, one for each disk
1823
  @raise errors.BlockDeviceError: if any of the disks cannot be
1824
      found
1825

1826
  """
1827
  stats = []
1828
  for dsk in disks:
1829
    rbd = _RecursiveFindBD(dsk)
1830
    if rbd is None:
1831
      _Fail("Can't find device %s", dsk)
1832

    
1833
    stats.append(rbd.CombinedSyncStatus())
1834

    
1835
  return stats
1836

    
1837

    
1838
def BlockdevGetmirrorstatusMulti(disks):
1839
  """Get the mirroring status of a list of devices.
1840

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

1848
  """
1849
  result = []
1850
  for disk in disks:
1851
    try:
1852
      rbd = _RecursiveFindBD(disk)
1853
      if rbd is None:
1854
        result.append((False, "Can't find device %s" % disk))
1855
        continue
1856

    
1857
      status = rbd.CombinedSyncStatus()
1858
    except errors.BlockDeviceError, err:
1859
      logging.exception("Error while getting disk status")
1860
      result.append((False, str(err)))
1861
    else:
1862
      result.append((True, status))
1863

    
1864
  assert len(disks) == len(result)
1865

    
1866
  return result
1867

    
1868

    
1869
def _RecursiveFindBD(disk):
1870
  """Check if a device is activated.
1871

1872
  If so, return information about the real device.
1873

1874
  @type disk: L{objects.Disk}
1875
  @param disk: the disk object we need to find
1876

1877
  @return: None if the device can't be found,
1878
      otherwise the device instance
1879

1880
  """
1881
  children = []
1882
  if disk.children:
1883
    for chdisk in disk.children:
1884
      children.append(_RecursiveFindBD(chdisk))
1885

    
1886
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1887

    
1888

    
1889
def _OpenRealBD(disk):
1890
  """Opens the underlying block device of a disk.
1891

1892
  @type disk: L{objects.Disk}
1893
  @param disk: the disk object we want to open
1894

1895
  """
1896
  real_disk = _RecursiveFindBD(disk)
1897
  if real_disk is None:
1898
    _Fail("Block device '%s' is not set up", disk)
1899

    
1900
  real_disk.Open()
1901

    
1902
  return real_disk
1903

    
1904

    
1905
def BlockdevFind(disk):
1906
  """Check if a device is activated.
1907

1908
  If it is, return information about the real device.
1909

1910
  @type disk: L{objects.Disk}
1911
  @param disk: the disk to find
1912
  @rtype: None or objects.BlockDevStatus
1913
  @return: None if the disk cannot be found, otherwise a the current
1914
           information
1915

1916
  """
1917
  try:
1918
    rbd = _RecursiveFindBD(disk)
1919
  except errors.BlockDeviceError, err:
1920
    _Fail("Failed to find device: %s", err, exc=True)
1921

    
1922
  if rbd is None:
1923
    return None
1924

    
1925
  return rbd.GetSyncStatus()
1926

    
1927

    
1928
def BlockdevGetsize(disks):
1929
  """Computes the size of the given disks.
1930

1931
  If a disk is not found, returns None instead.
1932

1933
  @type disks: list of L{objects.Disk}
1934
  @param disks: the list of disk to compute the size for
1935
  @rtype: list
1936
  @return: list with elements None if the disk cannot be found,
1937
      otherwise the size
1938

1939
  """
1940
  result = []
1941
  for cf in disks:
1942
    try:
1943
      rbd = _RecursiveFindBD(cf)
1944
    except errors.BlockDeviceError:
1945
      result.append(None)
1946
      continue
1947
    if rbd is None:
1948
      result.append(None)
1949
    else:
1950
      result.append(rbd.GetActualSize())
1951
  return result
1952

    
1953

    
1954
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
1955
  """Export a block device to a remote node.
1956

1957
  @type disk: L{objects.Disk}
1958
  @param disk: the description of the disk to export
1959
  @type dest_node: str
1960
  @param dest_node: the destination node to export to
1961
  @type dest_path: str
1962
  @param dest_path: the destination path on the target node
1963
  @type cluster_name: str
1964
  @param cluster_name: the cluster name, needed for SSH hostalias
1965
  @rtype: None
1966

1967
  """
1968
  real_disk = _OpenRealBD(disk)
1969

    
1970
  # the block size on the read dd is 1MiB to match our units
1971
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
1972
                               "dd if=%s bs=1048576 count=%s",
1973
                               real_disk.dev_path, str(disk.size))
1974

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

    
1984
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1985
                                                   constants.GANETI_RUNAS,
1986
                                                   destcmd)
1987

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

    
1991
  result = utils.RunCmd(["bash", "-c", command])
1992

    
1993
  if result.failed:
1994
    _Fail("Disk copy command '%s' returned error: %s"
1995
          " output: %s", command, result.fail_reason, result.output)
1996

    
1997

    
1998
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1999
  """Write a file to the filesystem.
2000

2001
  This allows the master to overwrite(!) a file. It will only perform
2002
  the operation if the file belongs to a list of configuration files.
2003

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

2020
  """
2021
  if not os.path.isabs(file_name):
2022
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2023

    
2024
  if file_name not in _ALLOWED_UPLOAD_FILES:
2025
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2026
          file_name)
2027

    
2028
  raw_data = _Decompress(data)
2029

    
2030
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2031
    _Fail("Invalid username/groupname type")
2032

    
2033
  getents = runtime.GetEnts()
2034
  uid = getents.LookupUser(uid)
2035
  gid = getents.LookupGroup(gid)
2036

    
2037
  utils.SafeWriteFile(file_name, None,
2038
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2039
                      atime=atime, mtime=mtime)
2040

    
2041

    
2042
def RunOob(oob_program, command, node, timeout):
2043
  """Executes oob_program with given command on given node.
2044

2045
  @param oob_program: The path to the executable oob_program
2046
  @param command: The command to invoke on oob_program
2047
  @param node: The node given as an argument to the program
2048
  @param timeout: Timeout after which we kill the oob program
2049

2050
  @return: stdout
2051
  @raise RPCFail: If execution fails for some reason
2052

2053
  """
2054
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2055

    
2056
  if result.failed:
2057
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2058
          result.fail_reason, result.output)
2059

    
2060
  return result.stdout
2061

    
2062

    
2063
def WriteSsconfFiles(values):
2064
  """Update all ssconf files.
2065

2066
  Wrapper around the SimpleStore.WriteFiles.
2067

2068
  """
2069
  ssconf.SimpleStore().WriteFiles(values)
2070

    
2071

    
2072
def _ErrnoOrStr(err):
2073
  """Format an EnvironmentError exception.
2074

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

2079
  @type err: L{EnvironmentError}
2080
  @param err: the exception to format
2081

2082
  """
2083
  if hasattr(err, "errno"):
2084
    detail = errno.errorcode[err.errno]
2085
  else:
2086
    detail = str(err)
2087
  return detail
2088

    
2089

    
2090
def _OSOndiskAPIVersion(os_dir):
2091
  """Compute and return the API version of a given OS.
2092

2093
  This function will try to read the API version of the OS residing in
2094
  the 'os_dir' directory.
2095

2096
  @type os_dir: str
2097
  @param os_dir: the directory in which we should look for the OS
2098
  @rtype: tuple
2099
  @return: tuple (status, data) with status denoting the validity and
2100
      data holding either the vaid versions or an error message
2101

2102
  """
2103
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2104

    
2105
  try:
2106
    st = os.stat(api_file)
2107
  except EnvironmentError, err:
2108
    return False, ("Required file '%s' not found under path %s: %s" %
2109
                   (constants.OS_API_FILE, os_dir, _ErrnoOrStr(err)))
2110

    
2111
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2112
    return False, ("File '%s' in %s is not a regular file" %
2113
                   (constants.OS_API_FILE, os_dir))
2114

    
2115
  try:
2116
    api_versions = utils.ReadFile(api_file).splitlines()
2117
  except EnvironmentError, err:
2118
    return False, ("Error while reading the API version file at %s: %s" %
2119
                   (api_file, _ErrnoOrStr(err)))
2120

    
2121
  try:
2122
    api_versions = [int(version.strip()) for version in api_versions]
2123
  except (TypeError, ValueError), err:
2124
    return False, ("API version(s) can't be converted to integer: %s" %
2125
                   str(err))
2126

    
2127
  return True, api_versions
2128

    
2129

    
2130
def DiagnoseOS(top_dirs=None):
2131
  """Compute the validity for all OSes.
2132

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

2149
  """
2150
  if top_dirs is None:
2151
    top_dirs = constants.OS_SEARCH_PATH
2152

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

    
2175
  return result
2176

    
2177

    
2178
def _TryOSFromDisk(name, base_dir=None):
2179
  """Create an OS instance from disk.
2180

2181
  This function will return an OS instance if the given name is a
2182
  valid OS name.
2183

2184
  @type base_dir: string
2185
  @keyword base_dir: Base directory containing OS installations.
2186
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2187
  @rtype: tuple
2188
  @return: success and either the OS instance if we find a valid one,
2189
      or error message
2190

2191
  """
2192
  if base_dir is None:
2193
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
2194
  else:
2195
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2196

    
2197
  if os_dir is None:
2198
    return False, "Directory for OS %s not found in search path" % name
2199

    
2200
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2201
  if not status:
2202
    # push the error up
2203
    return status, api_versions
2204

    
2205
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2206
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2207
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2208

    
2209
  # OS Files dictionary, we will populate it with the absolute path
2210
  # names; if the value is True, then it is a required file, otherwise
2211
  # an optional one
2212
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2213

    
2214
  if max(api_versions) >= constants.OS_API_V15:
2215
    os_files[constants.OS_VARIANTS_FILE] = False
2216

    
2217
  if max(api_versions) >= constants.OS_API_V20:
2218
    os_files[constants.OS_PARAMETERS_FILE] = True
2219
  else:
2220
    del os_files[constants.OS_SCRIPT_VERIFY]
2221

    
2222
  for (filename, required) in os_files.items():
2223
    os_files[filename] = utils.PathJoin(os_dir, filename)
2224

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

    
2234
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2235
      return False, ("File '%s' under path '%s' is not a regular file" %
2236
                     (filename, os_dir))
2237

    
2238
    if filename in constants.OS_SCRIPTS:
2239
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2240
        return False, ("File '%s' under path '%s' is not executable" %
2241
                       (filename, os_dir))
2242

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

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

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

    
2276

    
2277
def OSFromDisk(name, base_dir=None):
2278
  """Create an OS instance from disk.
2279

2280
  This function will return an OS instance if the given name is a
2281
  valid OS name. Otherwise, it will raise an appropriate
2282
  L{RPCFail} exception, detailing why this is not a valid OS.
2283

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

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

2294
  """
2295
  name_only = objects.OS.GetName(name)
2296
  status, payload = _TryOSFromDisk(name_only, base_dir)
2297

    
2298
  if not status:
2299
    _Fail(payload)
2300

    
2301
  return payload
2302

    
2303

    
2304
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2305
  """Calculate the basic environment for an os script.
2306

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

2320
  """
2321
  result = {}
2322
  api_version = \
2323
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2324
  result["OS_API_VERSION"] = "%d" % api_version
2325
  result["OS_NAME"] = inst_os.name
2326
  result["DEBUG_LEVEL"] = "%d" % debug
2327

    
2328
  # OS variants
2329
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2330
    variant = objects.OS.GetVariant(os_name)
2331
    if not variant:
2332
      variant = inst_os.supported_variants[0]
2333
  else:
2334
    variant = ""
2335
  result["OS_VARIANT"] = variant
2336

    
2337
  # OS params
2338
  for pname, pvalue in os_params.items():
2339
    result["OSP_%s" % pname.upper()] = pvalue
2340

    
2341
  return result
2342

    
2343

    
2344
def OSEnvironment(instance, inst_os, debug=0):
2345
  """Calculate the environment for an os script.
2346

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

2358
  """
2359
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2360

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

    
2364
  result["HYPERVISOR"] = instance.hypervisor
2365
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2366
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2367
  result["INSTANCE_SECONDARY_NODES"] = \
2368
      ("%s" % " ".join(instance.secondary_nodes))
2369

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

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

    
2398
  # HV/BE params
2399
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2400
    for key, value in source.items():
2401
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2402

    
2403
  return result
2404

    
2405

    
2406
def BlockdevGrow(disk, amount, dryrun):
2407
  """Grow a stack of block devices.
2408

2409
  This function is called recursively, with the childrens being the
2410
  first ones to resize.
2411

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

2423
  """
2424
  r_dev = _RecursiveFindBD(disk)
2425
  if r_dev is None:
2426
    _Fail("Cannot find block device %s", disk)
2427

    
2428
  try:
2429
    r_dev.Grow(amount, dryrun)
2430
  except errors.BlockDeviceError, err:
2431
    _Fail("Failed to grow block device: %s", err, exc=True)
2432

    
2433

    
2434
def BlockdevSnapshot(disk):
2435
  """Create a snapshot copy of a block device.
2436

2437
  This function is called recursively, and the snapshot is actually created
2438
  just for the leaf lvm backend device.
2439

2440
  @type disk: L{objects.Disk}
2441
  @param disk: the disk to be snapshotted
2442
  @rtype: string
2443
  @return: snapshot disk ID as (vg, lv)
2444

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

    
2463

    
2464
def FinalizeExport(instance, snap_disks):
2465
  """Write out the export configuration information.
2466

2467
  @type instance: L{objects.Instance}
2468
  @param instance: the instance which we export, used for
2469
      saving configuration
2470
  @type snap_disks: list of L{objects.Disk}
2471
  @param snap_disks: list of snapshot block devices, which
2472
      will be used to get the actual name of the dump file
2473

2474
  @rtype: None
2475

2476
  """
2477
  destdir = utils.PathJoin(constants.EXPORT_DIR, instance.name + ".new")
2478
  finaldestdir = utils.PathJoin(constants.EXPORT_DIR, instance.name)
2479

    
2480
  config = objects.SerializableConfigParser()
2481

    
2482
  config.add_section(constants.INISECT_EXP)
2483
  config.set(constants.INISECT_EXP, "version", "0")
2484
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2485
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2486
  config.set(constants.INISECT_EXP, "os", instance.os)
2487
  config.set(constants.INISECT_EXP, "compression", "none")
2488

    
2489
  config.add_section(constants.INISECT_INS)
2490
  config.set(constants.INISECT_INS, "name", instance.name)
2491
  config.set(constants.INISECT_INS, "memory", "%d" %
2492
             instance.beparams[constants.BE_MEMORY])
2493
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2494
             instance.beparams[constants.BE_VCPUS])
2495
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2496
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2497
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2498

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

    
2511
  disk_total = 0
2512
  for disk_count, disk in enumerate(snap_disks):
2513
    if disk:
2514
      disk_total += 1
2515
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2516
                 ("%s" % disk.iv_name))
2517
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2518
                 ("%s" % disk.physical_id[1]))
2519
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2520
                 ("%d" % disk.size))
2521

    
2522
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2523

    
2524
  # New-style hypervisor/backend parameters
2525

    
2526
  config.add_section(constants.INISECT_HYP)
2527
  for name, value in instance.hvparams.items():
2528
    if name not in constants.HVC_GLOBALS:
2529
      config.set(constants.INISECT_HYP, name, str(value))
2530

    
2531
  config.add_section(constants.INISECT_BEP)
2532
  for name, value in instance.beparams.items():
2533
    config.set(constants.INISECT_BEP, name, str(value))
2534

    
2535
  config.add_section(constants.INISECT_OSP)
2536
  for name, value in instance.osparams.items():
2537
    config.set(constants.INISECT_OSP, name, str(value))
2538

    
2539
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2540
                  data=config.Dumps())
2541
  shutil.rmtree(finaldestdir, ignore_errors=True)
2542
  shutil.move(destdir, finaldestdir)
2543

    
2544

    
2545
def ExportInfo(dest):
2546
  """Get export configuration information.
2547

2548
  @type dest: str
2549
  @param dest: directory containing the export
2550

2551
  @rtype: L{objects.SerializableConfigParser}
2552
  @return: a serializable config file containing the
2553
      export info
2554

2555
  """
2556
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2557

    
2558
  config = objects.SerializableConfigParser()
2559
  config.read(cff)
2560

    
2561
  if (not config.has_section(constants.INISECT_EXP) or
2562
      not config.has_section(constants.INISECT_INS)):
2563
    _Fail("Export info file doesn't have the required fields")
2564

    
2565
  return config.Dumps()
2566

    
2567

    
2568
def ListExports():
2569
  """Return a list of exports currently available on this machine.
2570

2571
  @rtype: list
2572
  @return: list of the exports
2573

2574
  """
2575
  if os.path.isdir(constants.EXPORT_DIR):
2576
    return sorted(utils.ListVisibleFiles(constants.EXPORT_DIR))
2577
  else:
2578
    _Fail("No exports directory")
2579

    
2580

    
2581
def RemoveExport(export):
2582
  """Remove an existing export from the node.
2583

2584
  @type export: str
2585
  @param export: the name of the export to remove
2586
  @rtype: None
2587

2588
  """
2589
  target = utils.PathJoin(constants.EXPORT_DIR, export)
2590

    
2591
  try:
2592
    shutil.rmtree(target)
2593
  except EnvironmentError, err:
2594
    _Fail("Error while removing the export: %s", err, exc=True)
2595

    
2596

    
2597
def BlockdevRename(devlist):
2598
  """Rename a list of block devices.
2599

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

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

    
2637

    
2638
def _TransformFileStorageDir(fs_dir):
2639
  """Checks whether given file_storage_dir is valid.
2640

2641
  Checks wheter the given fs_dir is within the cluster-wide default
2642
  file_storage_dir or the shared_file_storage_dir, which are stored in
2643
  SimpleStore. Only paths under those directories are allowed.
2644

2645
  @type fs_dir: str
2646
  @param fs_dir: the path to check
2647

2648
  @return: the normalized path if valid, None otherwise
2649

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

    
2664

    
2665
def CreateFileStorageDir(file_storage_dir):
2666
  """Create file storage directory.
2667

2668
  @type file_storage_dir: str
2669
  @param file_storage_dir: directory to create
2670

2671
  @rtype: tuple
2672
  @return: tuple with first element a boolean indicating wheter dir
2673
      creation was successful or not
2674

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

    
2688

    
2689
def RemoveFileStorageDir(file_storage_dir):
2690
  """Remove file storage directory.
2691

2692
  Remove it only if it's empty. If not log an error and return.
2693

2694
  @type file_storage_dir: str
2695
  @param file_storage_dir: the directory we should cleanup
2696
  @rtype: tuple (success,)
2697
  @return: tuple of one element, C{success}, denoting
2698
      whether the operation was successful
2699

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

    
2713

    
2714
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2715
  """Rename the file storage directory.
2716

2717
  @type old_file_storage_dir: str
2718
  @param old_file_storage_dir: the current path
2719
  @type new_file_storage_dir: str
2720
  @param new_file_storage_dir: the name we should rename to
2721
  @rtype: tuple (success,)
2722
  @return: tuple of one element, C{success}, denoting
2723
      whether the operation was successful
2724

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

    
2743

    
2744
def _EnsureJobQueueFile(file_name):
2745
  """Checks whether the given filename is in the queue directory.
2746

2747
  @type file_name: str
2748
  @param file_name: the file name we should check
2749
  @rtype: None
2750
  @raises RPCFail: if the file is not valid
2751

2752
  """
2753
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2754
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2755

    
2756
  if not result:
2757
    _Fail("Passed job queue file '%s' does not belong to"
2758
          " the queue directory '%s'", file_name, queue_dir)
2759

    
2760

    
2761
def JobQueueUpdate(file_name, content):
2762
  """Updates a file in the queue directory.
2763

2764
  This is just a wrapper over L{utils.io.WriteFile}, with proper
2765
  checking.
2766

2767
  @type file_name: str
2768
  @param file_name: the job file name
2769
  @type content: str
2770
  @param content: the new job contents
2771
  @rtype: boolean
2772
  @return: the success of the operation
2773

2774
  """
2775
  _EnsureJobQueueFile(file_name)
2776
  getents = runtime.GetEnts()
2777

    
2778
  # Write and replace the file atomically
2779
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
2780
                  gid=getents.masterd_gid)
2781

    
2782

    
2783
def JobQueueRename(old, new):
2784
  """Renames a job queue file.
2785

2786
  This is just a wrapper over os.rename with proper checking.
2787

2788
  @type old: str
2789
  @param old: the old (actual) file name
2790
  @type new: str
2791
  @param new: the desired file name
2792
  @rtype: tuple
2793
  @return: the success of the operation and payload
2794

2795
  """
2796
  _EnsureJobQueueFile(old)
2797
  _EnsureJobQueueFile(new)
2798

    
2799
  getents = runtime.GetEnts()
2800

    
2801
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0700,
2802
                   dir_uid=getents.masterd_uid, dir_gid=getents.masterd_gid)
2803

    
2804

    
2805
def BlockdevClose(instance_name, disks):
2806
  """Closes the given block devices.
2807

2808
  This means they will be switched to secondary mode (in case of
2809
  DRBD).
2810

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

2821
  """
2822
  bdevs = []
2823
  for cf in disks:
2824
    rd = _RecursiveFindBD(cf)
2825
    if rd is None:
2826
      _Fail("Can't find device %s", cf)
2827
    bdevs.append(rd)
2828

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

    
2841

    
2842
def ValidateHVParams(hvname, hvparams):
2843
  """Validates the given hypervisor parameters.
2844

2845
  @type hvname: string
2846
  @param hvname: the hypervisor name
2847
  @type hvparams: dict
2848
  @param hvparams: the hypervisor parameters to be validated
2849
  @rtype: None
2850

2851
  """
2852
  try:
2853
    hv_type = hypervisor.GetHypervisor(hvname)
2854
    hv_type.ValidateParameters(hvparams)
2855
  except errors.HypervisorError, err:
2856
    _Fail(str(err), log=False)
2857

    
2858

    
2859
def _CheckOSPList(os_obj, parameters):
2860
  """Check whether a list of parameters is supported by the OS.
2861

2862
  @type os_obj: L{objects.OS}
2863
  @param os_obj: OS object to check
2864
  @type parameters: list
2865
  @param parameters: the list of parameters to check
2866

2867
  """
2868
  supported = [v[0] for v in os_obj.supported_parameters]
2869
  delta = frozenset(parameters).difference(supported)
2870
  if delta:
2871
    _Fail("The following parameters are not supported"
2872
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
2873

    
2874

    
2875
def ValidateOS(required, osname, checks, osparams):
2876
  """Validate the given OS' parameters.
2877

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

2891
  """
2892
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
2893
    _Fail("Unknown checks required for OS %s: %s", osname,
2894
          set(checks).difference(constants.OS_VALIDATE_CALLS))
2895

    
2896
  name_only = objects.OS.GetName(osname)
2897
  status, tbv = _TryOSFromDisk(name_only, None)
2898

    
2899
  if not status:
2900
    if required:
2901
      _Fail(tbv)
2902
    else:
2903
      return False
2904

    
2905
  if max(tbv.api_versions) < constants.OS_API_V20:
2906
    return True
2907

    
2908
  if constants.OS_VALIDATE_PARAMETERS in checks:
2909
    _CheckOSPList(tbv, osparams.keys())
2910

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

    
2920
  return True
2921

    
2922

    
2923
def DemoteFromMC():
2924
  """Demotes the current node from master candidate role.
2925

2926
  """
2927
  # try to ensure we're not the master by mistake
2928
  master, myself = ssconf.GetMasterAndMyself()
2929
  if master == myself:
2930
    _Fail("ssconf status shows I'm the master node, will not demote")
2931

    
2932
  result = utils.RunCmd([constants.DAEMON_UTIL, "check", constants.MASTERD])
2933
  if not result.failed:
2934
    _Fail("The master daemon is running, will not demote")
2935

    
2936
  try:
2937
    if os.path.isfile(constants.CLUSTER_CONF_FILE):
2938
      utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2939
  except EnvironmentError, err:
2940
    if err.errno != errno.ENOENT:
2941
      _Fail("Error while backing up cluster file: %s", err, exc=True)
2942

    
2943
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2944

    
2945

    
2946
def _GetX509Filenames(cryptodir, name):
2947
  """Returns the full paths for the private key and certificate.
2948

2949
  """
2950
  return (utils.PathJoin(cryptodir, name),
2951
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
2952
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
2953

    
2954

    
2955
def CreateX509Certificate(validity, cryptodir=constants.CRYPTO_KEYS_DIR):
2956
  """Creates a new X509 certificate for SSL/TLS.
2957

2958
  @type validity: int
2959
  @param validity: Validity in seconds
2960
  @rtype: tuple; (string, string)
2961
  @return: Certificate name and public part
2962

2963
  """
2964
  (key_pem, cert_pem) = \
2965
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
2966
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
2967

    
2968
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
2969
                              prefix="x509-%s-" % utils.TimestampForFilename())
2970
  try:
2971
    name = os.path.basename(cert_dir)
2972
    assert len(name) > 5
2973

    
2974
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2975

    
2976
    utils.WriteFile(key_file, mode=0400, data=key_pem)
2977
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
2978

    
2979
    # Never return private key as it shouldn't leave the node
2980
    return (name, cert_pem)
2981
  except Exception:
2982
    shutil.rmtree(cert_dir, ignore_errors=True)
2983
    raise
2984

    
2985

    
2986
def RemoveX509Certificate(name, cryptodir=constants.CRYPTO_KEYS_DIR):
2987
  """Removes a X509 certificate.
2988

2989
  @type name: string
2990
  @param name: Certificate name
2991

2992
  """
2993
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2994

    
2995
  utils.RemoveFile(key_file)
2996
  utils.RemoveFile(cert_file)
2997

    
2998
  try:
2999
    os.rmdir(cert_dir)
3000
  except EnvironmentError, err:
3001
    _Fail("Cannot remove certificate directory '%s': %s",
3002
          cert_dir, err)
3003

    
3004

    
3005
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3006
  """Returns the command for the requested input/output.
3007

3008
  @type instance: L{objects.Instance}
3009
  @param instance: The instance object
3010
  @param mode: Import/export mode
3011
  @param ieio: Input/output type
3012
  @param ieargs: Input/output arguments
3013

3014
  """
3015
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3016

    
3017
  env = None
3018
  prefix = None
3019
  suffix = None
3020
  exp_size = None
3021

    
3022
  if ieio == constants.IEIO_FILE:
3023
    (filename, ) = ieargs
3024

    
3025
    if not utils.IsNormAbsPath(filename):
3026
      _Fail("Path '%s' is not normalized or absolute", filename)
3027

    
3028
    real_filename = os.path.realpath(filename)
3029
    directory = os.path.dirname(real_filename)
3030

    
3031
    if not utils.IsBelowDir(constants.EXPORT_DIR, real_filename):
3032
      _Fail("File '%s' is not under exports directory '%s': %s",
3033
            filename, constants.EXPORT_DIR, real_filename)
3034

    
3035
    # Create directory
3036
    utils.Makedirs(directory, mode=0750)
3037

    
3038
    quoted_filename = utils.ShellQuote(filename)
3039

    
3040
    if mode == constants.IEM_IMPORT:
3041
      suffix = "> %s" % quoted_filename
3042
    elif mode == constants.IEM_EXPORT:
3043
      suffix = "< %s" % quoted_filename
3044

    
3045
      # Retrieve file size
3046
      try:
3047
        st = os.stat(filename)
3048
      except EnvironmentError, err:
3049
        logging.error("Can't stat(2) %s: %s", filename, err)
3050
      else:
3051
        exp_size = utils.BytesToMebibyte(st.st_size)
3052

    
3053
  elif ieio == constants.IEIO_RAW_DISK:
3054
    (disk, ) = ieargs
3055

    
3056
    real_disk = _OpenRealBD(disk)
3057

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

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

    
3078
  elif ieio == constants.IEIO_SCRIPT:
3079
    (disk, disk_index, ) = ieargs
3080

    
3081
    assert isinstance(disk_index, (int, long))
3082

    
3083
    real_disk = _OpenRealBD(disk)
3084

    
3085
    inst_os = OSFromDisk(instance.os)
3086
    env = OSEnvironment(instance, inst_os)
3087

    
3088
    if mode == constants.IEM_IMPORT:
3089
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3090
      env["IMPORT_INDEX"] = str(disk_index)
3091
      script = inst_os.import_script
3092

    
3093
    elif mode == constants.IEM_EXPORT:
3094
      env["EXPORT_DEVICE"] = real_disk.dev_path
3095
      env["EXPORT_INDEX"] = str(disk_index)
3096
      script = inst_os.export_script
3097

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

    
3101
    if mode == constants.IEM_IMPORT:
3102
      suffix = "| %s" % script_cmd
3103

    
3104
    elif mode == constants.IEM_EXPORT:
3105
      prefix = "%s |" % script_cmd
3106

    
3107
    # Let script predict size
3108
    exp_size = constants.IE_CUSTOM_SIZE
3109

    
3110
  else:
3111
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3112

    
3113
  return (env, prefix, suffix, exp_size)
3114

    
3115

    
3116
def _CreateImportExportStatusDir(prefix):
3117
  """Creates status directory for import/export.
3118

3119
  """
3120
  return tempfile.mkdtemp(dir=constants.IMPORT_EXPORT_DIR,
3121
                          prefix=("%s-%s-" %
3122
                                  (prefix, utils.TimestampForFilename())))
3123

    
3124

    
3125
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3126
                            ieio, ieioargs):
3127
  """Starts an import or export daemon.
3128

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

3144
  """
3145
  if mode == constants.IEM_IMPORT:
3146
    prefix = "import"
3147

    
3148
    if not (host is None and port is None):
3149
      _Fail("Can not specify host or port on import")
3150

    
3151
  elif mode == constants.IEM_EXPORT:
3152
    prefix = "export"
3153

    
3154
    if host is None or port is None:
3155
      _Fail("Host and port must be specified for an export")
3156

    
3157
  else:
3158
    _Fail("Invalid mode %r", mode)
3159

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

    
3163
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3164
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3165

    
3166
  if opts.key_name is None:
3167
    # Use server.pem
3168
    key_path = constants.NODED_CERT_FILE
3169
    cert_path = constants.NODED_CERT_FILE
3170
    assert opts.ca_pem is None
3171
  else:
3172
    (_, key_path, cert_path) = _GetX509Filenames(constants.CRYPTO_KEYS_DIR,
3173
                                                 opts.key_name)
3174
    assert opts.ca_pem is not None
3175

    
3176
  for i in [key_path, cert_path]:
3177
    if not os.path.exists(i):
3178
      _Fail("File '%s' does not exist" % i)
3179

    
3180
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3181
  try:
3182
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3183
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3184
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3185

    
3186
    if opts.ca_pem is None:
3187
      # Use server.pem
3188
      ca = utils.ReadFile(constants.NODED_CERT_FILE)
3189
    else:
3190
      ca = opts.ca_pem
3191

    
3192
    # Write CA file
3193
    utils.WriteFile(ca_file, data=ca, mode=0400)
3194

    
3195
    cmd = [
3196
      constants.IMPORT_EXPORT_DAEMON,
3197
      status_file, mode,
3198
      "--key=%s" % key_path,
3199
      "--cert=%s" % cert_path,
3200
      "--ca=%s" % ca_file,
3201
      ]
3202

    
3203
    if host:
3204
      cmd.append("--host=%s" % host)
3205

    
3206
    if port:
3207
      cmd.append("--port=%s" % port)
3208

    
3209
    if opts.ipv6:
3210
      cmd.append("--ipv6")
3211
    else:
3212
      cmd.append("--ipv4")
3213

    
3214
    if opts.compress:
3215
      cmd.append("--compress=%s" % opts.compress)
3216

    
3217
    if opts.magic:
3218
      cmd.append("--magic=%s" % opts.magic)
3219

    
3220
    if exp_size is not None:
3221
      cmd.append("--expected-size=%s" % exp_size)
3222

    
3223
    if cmd_prefix:
3224
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3225

    
3226
    if cmd_suffix:
3227
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3228

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

    
3238
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3239

    
3240
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3241
    # support for receiving a file descriptor for output
3242
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3243
                      output=logfile)
3244

    
3245
    # The import/export name is simply the status directory name
3246
    return os.path.basename(status_dir)
3247

    
3248
  except Exception:
3249
    shutil.rmtree(status_dir, ignore_errors=True)
3250
    raise
3251

    
3252

    
3253
def GetImportExportStatus(names):
3254
  """Returns import/export daemon status.
3255

3256
  @type names: sequence
3257
  @param names: List of names
3258
  @rtype: List of dicts
3259
  @return: Returns a list of the state of each named import/export or None if a
3260
           status couldn't be read
3261

3262
  """
3263
  result = []
3264

    
3265
  for name in names:
3266
    status_file = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name,
3267
                                 _IES_STATUS_FILE)
3268

    
3269
    try:
3270
      data = utils.ReadFile(status_file)
3271
    except EnvironmentError, err:
3272
      if err.errno != errno.ENOENT:
3273
        raise
3274
      data = None
3275

    
3276
    if not data:
3277
      result.append(None)
3278
      continue
3279

    
3280
    result.append(serializer.LoadJson(data))
3281

    
3282
  return result
3283

    
3284

    
3285
def AbortImportExport(name):
3286
  """Sends SIGTERM to a running import/export daemon.
3287

3288
  """
3289
  logging.info("Abort import/export %s", name)
3290

    
3291
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3292
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3293

    
3294
  if pid:
3295
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3296
                 name, pid)
3297
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3298

    
3299

    
3300
def CleanupImportExport(name):
3301
  """Cleanup after an import or export.
3302

3303
  If the import/export daemon is still running it's killed. Afterwards the
3304
  whole status directory is removed.
3305

3306
  """
3307
  logging.info("Finalizing import/export %s", name)
3308

    
3309
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3310

    
3311
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3312

    
3313
  if pid:
3314
    logging.info("Import/export %s is still running with PID %s",
3315
                 name, pid)
3316
    utils.KillProcess(pid, waitpid=False)
3317

    
3318
  shutil.rmtree(status_dir, ignore_errors=True)
3319

    
3320

    
3321
def _FindDisks(nodes_ip, disks):
3322
  """Sets the physical ID on disks and returns the block devices.
3323

3324
  """
3325
  # set the correct physical ID
3326
  my_name = netutils.Hostname.GetSysName()
3327
  for cf in disks:
3328
    cf.SetPhysicalID(my_name, nodes_ip)
3329

    
3330
  bdevs = []
3331

    
3332
  for cf in disks:
3333
    rd = _RecursiveFindBD(cf)
3334
    if rd is None:
3335
      _Fail("Can't find device %s", cf)
3336
    bdevs.append(rd)
3337
  return bdevs
3338

    
3339

    
3340
def DrbdDisconnectNet(nodes_ip, disks):
3341
  """Disconnects the network on a list of drbd devices.
3342

3343
  """
3344
  bdevs = _FindDisks(nodes_ip, disks)
3345

    
3346
  # disconnect disks
3347
  for rd in bdevs:
3348
    try:
3349
      rd.DisconnectNet()
3350
    except errors.BlockDeviceError, err:
3351
      _Fail("Can't change network configuration to standalone mode: %s",
3352
            err, exc=True)
3353

    
3354

    
3355
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3356
  """Attaches the network on a list of drbd devices.
3357

3358
  """
3359
  bdevs = _FindDisks(nodes_ip, disks)
3360

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

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

    
3381
  def _Attach():
3382
    all_connected = True
3383

    
3384
    for rd in bdevs:
3385
      stats = rd.GetProcStatus()
3386

    
3387
      all_connected = (all_connected and
3388
                       (stats.is_connected or stats.is_in_resync))
3389

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

    
3399
    if not all_connected:
3400
      raise utils.RetryAgain()
3401

    
3402
  try:
3403
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3404
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3405
  except utils.RetryTimeout:
3406
    _Fail("Timeout in disk reconnecting")
3407

    
3408
  if multimaster:
3409
    # change to primary mode
3410
    for rd in bdevs:
3411
      try:
3412
        rd.Open()
3413
      except errors.BlockDeviceError, err:
3414
        _Fail("Can't change to primary mode: %s", err)
3415

    
3416

    
3417
def DrbdWaitSync(nodes_ip, disks):
3418
  """Wait until DRBDs have synchronized.
3419

3420
  """
3421
  def _helper(rd):
3422
    stats = rd.GetProcStatus()
3423
    if not (stats.is_connected or stats.is_in_resync):
3424
      raise utils.RetryAgain()
3425
    return stats
3426

    
3427
  bdevs = _FindDisks(nodes_ip, disks)
3428

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

    
3444
  return (alldone, min_resync)
3445

    
3446

    
3447
def GetDrbdUsermodeHelper():
3448
  """Returns DRBD usermode helper currently configured.
3449

3450
  """
3451
  try:
3452
    return bdev.BaseDRBD.GetUsermodeHelper()
3453
  except errors.BlockDeviceError, err:
3454
    _Fail(str(err))
3455

    
3456

    
3457
def PowercycleNode(hypervisor_type):
3458
  """Hard-powercycle the node.
3459

3460
  Because we need to return first, and schedule the powercycle in the
3461
  background, we won't be able to report failures nicely.
3462

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

    
3480

    
3481
class HooksRunner(object):
3482
  """Hook runner.
3483

3484
  This class is instantiated on the node side (ganeti-noded) and not
3485
  on the master side.
3486

3487
  """
3488
  def __init__(self, hooks_base_dir=None):
3489
    """Constructor for hooks runner.
3490

3491
    @type hooks_base_dir: str or None
3492
    @param hooks_base_dir: if not None, this overrides the
3493
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
3494

3495
    """
3496
    if hooks_base_dir is None:
3497
      hooks_base_dir = constants.HOOKS_BASE_DIR
3498
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3499
    # constant
3500
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
3501

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

3505
    """
3506
    assert len(node_list) == 1
3507
    node = node_list[0]
3508
    _, myself = ssconf.GetMasterAndMyself()
3509
    assert node == myself
3510

    
3511
    results = self.RunHooks(hpath, phase, env)
3512

    
3513
    # Return values in the form expected by HooksMaster
3514
    return {node: (None, False, results)}
3515

    
3516
  def RunHooks(self, hpath, phase, env):
3517
    """Run the scripts in the hooks directory.
3518

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

3534
    @raise errors.ProgrammerError: for invalid input
3535
        parameters
3536

3537
    """
3538
    if phase == constants.HOOKS_PHASE_PRE:
3539
      suffix = "pre"
3540
    elif phase == constants.HOOKS_PHASE_POST:
3541
      suffix = "post"
3542
    else:
3543
      _Fail("Unknown hooks phase '%s'", phase)
3544

    
3545
    subdir = "%s-%s.d" % (hpath, suffix)
3546
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3547

    
3548
    results = []
3549

    
3550
    if not os.path.isdir(dir_name):
3551
      # for non-existing/non-dirs, we simply exit instead of logging a
3552
      # warning at every operation
3553
      return results
3554

    
3555
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3556

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

    
3572
    return results
3573

    
3574

    
3575
class IAllocatorRunner(object):
3576
  """IAllocator runner.
3577

3578
  This class is instantiated on the node side (ganeti-noded) and not on
3579
  the master side.
3580

3581
  """
3582
  @staticmethod
3583
  def Run(name, idata):
3584
    """Run an iallocator script.
3585

3586
    @type name: str
3587
    @param name: the iallocator script name
3588
    @type idata: str
3589
    @param idata: the allocator input data
3590

3591
    @rtype: tuple
3592
    @return: two element tuple of:
3593
       - status
3594
       - either error message or stdout of allocator (for success)
3595

3596
    """
3597
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
3598
                                  os.path.isfile)
3599
    if alloc_script is None:
3600
      _Fail("iallocator module '%s' not found in the search path", name)
3601

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

    
3613
    return result.stdout
3614

    
3615

    
3616
class DevCacheManager(object):
3617
  """Simple class for managing a cache of block device information.
3618

3619
  """
3620
  _DEV_PREFIX = "/dev/"
3621
  _ROOT_DIR = constants.BDEV_CACHE_DIR
3622

    
3623
  @classmethod
3624
  def _ConvertPath(cls, dev_path):
3625
    """Converts a /dev/name path to the cache file name.
3626

3627
    This replaces slashes with underscores and strips the /dev
3628
    prefix. It then returns the full path to the cache file.
3629

3630
    @type dev_path: str
3631
    @param dev_path: the C{/dev/} path name
3632
    @rtype: str
3633
    @return: the converted path name
3634

3635
    """
3636
    if dev_path.startswith(cls._DEV_PREFIX):
3637
      dev_path = dev_path[len(cls._DEV_PREFIX):]
3638
    dev_path = dev_path.replace("/", "_")
3639
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
3640
    return fpath
3641

    
3642
  @classmethod
3643
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
3644
    """Updates the cache information for a given device.
3645

3646
    @type dev_path: str
3647
    @param dev_path: the pathname of the device
3648
    @type owner: str
3649
    @param owner: the owner (instance name) of the device
3650
    @type on_primary: bool
3651
    @param on_primary: whether this is the primary
3652
        node nor not
3653
    @type iv_name: str
3654
    @param iv_name: the instance-visible name of the
3655
        device, as in objects.Disk.iv_name
3656

3657
    @rtype: None
3658

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

    
3676
  @classmethod
3677
  def RemoveCache(cls, dev_path):
3678
    """Remove data for a dev_path.
3679

3680
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
3681
    path name and logging.
3682

3683
    @type dev_path: str
3684
    @param dev_path: the pathname of the device
3685

3686
    @rtype: None
3687

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