Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ c79198a0

History | View | Annotate | Download (111.1 kB)

1
#
2
#
3

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

    
21

    
22
"""Functions used by the node daemon
23

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

29
"""
30

    
31
# pylint: disable=E1103
32

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

    
37

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

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

    
65

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

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

    
83

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

87
  Its argument is the error message.
88

89
  """
90

    
91

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

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

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

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

    
114

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

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

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

    
124

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

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

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

    
137

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

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

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

    
157

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

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

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

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

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

    
187

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

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

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

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

    
211
  return frozenset(allowed_files)
212

    
213

    
214
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
215

    
216

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

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

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

    
227

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

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

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

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

    
252

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

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

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

    
271
      cfg = _GetConfig()
272
      hr = HooksRunner()
273
      hm = mcpu.HooksMaster(hook_opcode, hooks_path, nodes, hr.RunLocalHooks,
274
                            None, env_builder_fn, logging.warning,
275
                            cfg.GetClusterName(), cfg.GetMasterNode())
276

    
277
      hm.RunPhase(constants.HOOKS_PHASE_PRE)
278
      result = fn(*args, **kwargs)
279
      hm.RunPhase(constants.HOOKS_PHASE_POST)
280

    
281
      return result
282
    return wrapper
283
  return decorator
284

    
285

    
286
def _BuildMasterIpEnv():
287
  """Builds environment variables for master IP hooks.
288

289
  """
290
  master_netdev, master_ip, _, family, master_netmask = GetMasterInfo()
291
  version = str(netutils.IPAddress.GetVersionFromAddressFamily(family))
292
  env = {
293
    "MASTER_NETDEV": master_netdev,
294
    "MASTER_IP": master_ip,
295
    "MASTER_NETMASK": master_netmask,
296
    "CLUSTER_IP_VERSION": version,
297
  }
298

    
299
  return env
300

    
301

    
302
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNUP, "master-ip-turnup",
303
               _BuildMasterIpEnv)
304
def ActivateMasterIp(master_params):
305
  """Activate the IP address of the master daemon.
306

307
  @type master_params: L{objects.MasterNetworkParameters}
308
  @param master_params: network parameters of the master
309

310
  """
311
  err_msg = None
312
  if netutils.TcpPing(master_params.ip, constants.DEFAULT_NODED_PORT):
313
    if netutils.IPAddress.Own(master_params.ip):
314
      # we already have the ip:
315
      logging.debug("Master IP already configured, doing nothing")
316
    else:
317
      err_msg = "Someone else has the master ip, not activating"
318
      logging.error(err_msg)
319
  else:
320
    ipcls = netutils.IPAddress.GetClassFromIpFamily(master_params.ip_family)
321

    
322
    result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
323
                           "%s/%s" % (master_params.ip, master_params.netmask),
324
                           "dev", master_params.netdev, "label",
325
                           "%s:0" % master_params.netdev])
326
    if result.failed:
327
      err_msg = "Can't activate master IP: %s" % result.output
328
      logging.error(err_msg)
329

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

    
343
  if err_msg:
344
    _Fail(err_msg)
345

    
346

    
347
def StartMasterDaemons(no_voting):
348
  """Activate local node as master node.
349

350
  The function will start the master daemons (ganeti-masterd and ganeti-rapi).
351

352
  @type no_voting: boolean
353
  @param no_voting: whether to start ganeti-masterd without a node vote
354
      but still non-interactively
355
  @rtype: None
356

357
  """
358

    
359
  if no_voting:
360
    masterd_args = "--no-voting --yes-do-it"
361
  else:
362
    masterd_args = ""
363

    
364
  env = {
365
    "EXTRA_MASTERD_ARGS": masterd_args,
366
    }
367

    
368
  result = utils.RunCmd([constants.DAEMON_UTIL, "start-master"], env=env)
369
  if result.failed:
370
    msg = "Can't start Ganeti master: %s" % result.output
371
    logging.error(msg)
372
    _Fail(msg)
373

    
374

    
375
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNDOWN, "master-ip-turndown",
376
               _BuildMasterIpEnv)
377
def DeactivateMasterIp(master_params):
378
  """Deactivate the master IP on this node.
379

380
  @type master_params: L{objects.MasterNetworkParameters}
381
  @param master_params: network parameters of the master
382

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

    
387
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
388
                         "%s/%s" % (master_params.ip, master_params.netmask),
389
                         "dev", master_params.netdev])
390
  if result.failed:
391
    logging.error("Can't remove the master IP, error: %s", result.output)
392
    # but otherwise ignore the failure
393

    
394

    
395
def StopMasterDaemons():
396
  """Stop the master daemons on this node.
397

398
  Stop the master daemons (ganeti-masterd and ganeti-rapi) on this node.
399

400
  @rtype: None
401

402
  """
403
  # TODO: log and report back to the caller the error failures; we
404
  # need to decide in which case we fail the RPC for this
405

    
406
  result = utils.RunCmd([constants.DAEMON_UTIL, "stop-master"])
407
  if result.failed:
408
    logging.error("Could not stop Ganeti master, command %s had exitcode %s"
409
                  " and error %s",
410
                  result.cmd, result.exit_code, result.output)
411

    
412

    
413
def ChangeMasterNetmask(old_netmask, netmask, master_ip, master_netdev):
414
  """Change the netmask of the master IP.
415

416
  @param old_netmask: the old value of the netmask
417
  @param netmask: the new value of the netmask
418
  @param master_ip: the master IP
419
  @param master_netdev: the master network device
420

421
  """
422
  if old_netmask == netmask:
423
    return
424

    
425
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
426
                         "%s/%s" % (master_ip, netmask),
427
                         "dev", master_netdev, "label",
428
                         "%s:0" % master_netdev])
429
  if result.failed:
430
    _Fail("Could not change the master IP netmask")
431

    
432
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
433
                         "%s/%s" % (master_ip, old_netmask),
434
                         "dev", master_netdev, "label",
435
                         "%s:0" % master_netdev])
436
  if result.failed:
437
    _Fail("Could not change the master IP netmask")
438

    
439

    
440
def EtcHostsModify(mode, host, ip):
441
  """Modify a host entry in /etc/hosts.
442

443
  @param mode: The mode to operate. Either add or remove entry
444
  @param host: The host to operate on
445
  @param ip: The ip associated with the entry
446

447
  """
448
  if mode == constants.ETC_HOSTS_ADD:
449
    if not ip:
450
      RPCFail("Mode 'add' needs 'ip' parameter, but parameter not"
451
              " present")
452
    utils.AddHostToEtcHosts(host, ip)
453
  elif mode == constants.ETC_HOSTS_REMOVE:
454
    if ip:
455
      RPCFail("Mode 'remove' does not allow 'ip' parameter, but"
456
              " parameter is present")
457
    utils.RemoveHostFromEtcHosts(host)
458
  else:
459
    RPCFail("Mode not supported")
460

    
461

    
462
def LeaveCluster(modify_ssh_setup):
463
  """Cleans up and remove the current node.
464

465
  This function cleans up and prepares the current node to be removed
466
  from the cluster.
467

468
  If processing is successful, then it raises an
469
  L{errors.QuitGanetiException} which is used as a special case to
470
  shutdown the node daemon.
471

472
  @param modify_ssh_setup: boolean
473

474
  """
475
  _CleanDirectory(constants.DATA_DIR)
476
  _CleanDirectory(constants.CRYPTO_KEYS_DIR)
477
  JobQueuePurge()
478

    
479
  if modify_ssh_setup:
480
    try:
481
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
482

    
483
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
484

    
485
      utils.RemoveFile(priv_key)
486
      utils.RemoveFile(pub_key)
487
    except errors.OpExecError:
488
      logging.exception("Error while processing ssh files")
489

    
490
  try:
491
    utils.RemoveFile(constants.CONFD_HMAC_KEY)
492
    utils.RemoveFile(constants.RAPI_CERT_FILE)
493
    utils.RemoveFile(constants.SPICE_CERT_FILE)
494
    utils.RemoveFile(constants.SPICE_CACERT_FILE)
495
    utils.RemoveFile(constants.NODED_CERT_FILE)
496
  except: # pylint: disable=W0702
497
    logging.exception("Error while removing cluster secrets")
498

    
499
  result = utils.RunCmd([constants.DAEMON_UTIL, "stop", constants.CONFD])
500
  if result.failed:
501
    logging.error("Command %s failed with exitcode %s and error %s",
502
                  result.cmd, result.exit_code, result.output)
503

    
504
  # Raise a custom exception (handled in ganeti-noded)
505
  raise errors.QuitGanetiException(True, "Shutdown scheduled")
506

    
507

    
508
def GetNodeInfo(vgname, hypervisor_type):
509
  """Gives back a hash with different information about the node.
510

511
  @type vgname: C{string}
512
  @param vgname: the name of the volume group to ask for disk space information
513
  @type hypervisor_type: C{str}
514
  @param hypervisor_type: the name of the hypervisor to ask for
515
      memory information
516
  @rtype: C{dict}
517
  @return: dictionary with the following keys:
518
      - vg_size is the size of the configured volume group in MiB
519
      - vg_free is the free size of the volume group in MiB
520
      - memory_dom0 is the memory allocated for domain0 in MiB
521
      - memory_free is the currently available (free) ram in MiB
522
      - memory_total is the total number of ram in MiB
523
      - hv_version: the hypervisor version, if available
524

525
  """
526
  outputarray = {}
527

    
528
  if vgname is not None:
529
    vginfo = bdev.LogicalVolume.GetVGInfo([vgname])
530
    vg_free = vg_size = None
531
    if vginfo:
532
      vg_free = int(round(vginfo[0][0], 0))
533
      vg_size = int(round(vginfo[0][1], 0))
534
    outputarray["vg_size"] = vg_size
535
    outputarray["vg_free"] = vg_free
536

    
537
  if hypervisor_type is not None:
538
    hyper = hypervisor.GetHypervisor(hypervisor_type)
539
    hyp_info = hyper.GetNodeInfo()
540
    if hyp_info is not None:
541
      outputarray.update(hyp_info)
542

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

    
545
  return outputarray
546

    
547

    
548
def VerifyNode(what, cluster_name):
549
  """Verify the status of the local node.
550

551
  Based on the input L{what} parameter, various checks are done on the
552
  local node.
553

554
  If the I{filelist} key is present, this list of
555
  files is checksummed and the file/checksum pairs are returned.
556

557
  If the I{nodelist} key is present, we check that we have
558
  connectivity via ssh with the target nodes (and check the hostname
559
  report).
560

561
  If the I{node-net-test} key is present, we check that we have
562
  connectivity to the given nodes via both primary IP and, if
563
  applicable, secondary IPs.
564

565
  @type what: C{dict}
566
  @param what: a dictionary of things to check:
567
      - filelist: list of files for which to compute checksums
568
      - nodelist: list of nodes we should check ssh communication with
569
      - node-net-test: list of nodes we should check node daemon port
570
        connectivity with
571
      - hypervisor: list with hypervisors to run the verify for
572
  @rtype: dict
573
  @return: a dictionary with the same keys as the input dict, and
574
      values representing the result of the checks
575

576
  """
577
  result = {}
578
  my_name = netutils.Hostname.GetSysName()
579
  port = netutils.GetDaemonPort(constants.NODED)
580
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
581

    
582
  if constants.NV_HYPERVISOR in what and vm_capable:
583
    result[constants.NV_HYPERVISOR] = tmp = {}
584
    for hv_name in what[constants.NV_HYPERVISOR]:
585
      try:
586
        val = hypervisor.GetHypervisor(hv_name).Verify()
587
      except errors.HypervisorError, err:
588
        val = "Error while checking hypervisor: %s" % str(err)
589
      tmp[hv_name] = val
590

    
591
  if constants.NV_HVPARAMS in what and vm_capable:
592
    result[constants.NV_HVPARAMS] = tmp = []
593
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
594
      try:
595
        logging.info("Validating hv %s, %s", hv_name, hvparms)
596
        hypervisor.GetHypervisor(hv_name).ValidateParameters(hvparms)
597
      except errors.HypervisorError, err:
598
        tmp.append((source, hv_name, str(err)))
599

    
600
  if constants.NV_FILELIST in what:
601
    result[constants.NV_FILELIST] = utils.FingerprintFiles(
602
      what[constants.NV_FILELIST])
603

    
604
  if constants.NV_NODELIST in what:
605
    (nodes, bynode) = what[constants.NV_NODELIST]
606

    
607
    # Add nodes from other groups (different for each node)
608
    try:
609
      nodes.extend(bynode[my_name])
610
    except KeyError:
611
      pass
612

    
613
    # Use a random order
614
    random.shuffle(nodes)
615

    
616
    # Try to contact all nodes
617
    val = {}
618
    for node in nodes:
619
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
620
      if not success:
621
        val[node] = message
622

    
623
    result[constants.NV_NODELIST] = val
624

    
625
  if constants.NV_NODENETTEST in what:
626
    result[constants.NV_NODENETTEST] = tmp = {}
627
    my_pip = my_sip = None
628
    for name, pip, sip in what[constants.NV_NODENETTEST]:
629
      if name == my_name:
630
        my_pip = pip
631
        my_sip = sip
632
        break
633
    if not my_pip:
634
      tmp[my_name] = ("Can't find my own primary/secondary IP"
635
                      " in the node list")
636
    else:
637
      for name, pip, sip in what[constants.NV_NODENETTEST]:
638
        fail = []
639
        if not netutils.TcpPing(pip, port, source=my_pip):
640
          fail.append("primary")
641
        if sip != pip:
642
          if not netutils.TcpPing(sip, port, source=my_sip):
643
            fail.append("secondary")
644
        if fail:
645
          tmp[name] = ("failure using the %s interface(s)" %
646
                       " and ".join(fail))
647

    
648
  if constants.NV_MASTERIP in what:
649
    # FIXME: add checks on incoming data structures (here and in the
650
    # rest of the function)
651
    master_name, master_ip = what[constants.NV_MASTERIP]
652
    if master_name == my_name:
653
      source = constants.IP4_ADDRESS_LOCALHOST
654
    else:
655
      source = None
656
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
657
                                                  source=source)
658

    
659
  if constants.NV_OOB_PATHS in what:
660
    result[constants.NV_OOB_PATHS] = tmp = []
661
    for path in what[constants.NV_OOB_PATHS]:
662
      try:
663
        st = os.stat(path)
664
      except OSError, err:
665
        tmp.append("error stating out of band helper: %s" % err)
666
      else:
667
        if stat.S_ISREG(st.st_mode):
668
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
669
            tmp.append(None)
670
          else:
671
            tmp.append("out of band helper %s is not executable" % path)
672
        else:
673
          tmp.append("out of band helper %s is not a file" % path)
674

    
675
  if constants.NV_LVLIST in what and vm_capable:
676
    try:
677
      val = GetVolumeList(utils.ListVolumeGroups().keys())
678
    except RPCFail, err:
679
      val = str(err)
680
    result[constants.NV_LVLIST] = val
681

    
682
  if constants.NV_INSTANCELIST in what and vm_capable:
683
    # GetInstanceList can fail
684
    try:
685
      val = GetInstanceList(what[constants.NV_INSTANCELIST])
686
    except RPCFail, err:
687
      val = str(err)
688
    result[constants.NV_INSTANCELIST] = val
689

    
690
  if constants.NV_VGLIST in what and vm_capable:
691
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
692

    
693
  if constants.NV_PVLIST in what and vm_capable:
694
    result[constants.NV_PVLIST] = \
695
      bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
696
                                   filter_allocatable=False)
697

    
698
  if constants.NV_VERSION in what:
699
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
700
                                    constants.RELEASE_VERSION)
701

    
702
  if constants.NV_HVINFO in what and vm_capable:
703
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
704
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
705

    
706
  if constants.NV_DRBDLIST in what and vm_capable:
707
    try:
708
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
709
    except errors.BlockDeviceError, err:
710
      logging.warning("Can't get used minors list", exc_info=True)
711
      used_minors = str(err)
712
    result[constants.NV_DRBDLIST] = used_minors
713

    
714
  if constants.NV_DRBDHELPER in what and vm_capable:
715
    status = True
716
    try:
717
      payload = bdev.BaseDRBD.GetUsermodeHelper()
718
    except errors.BlockDeviceError, err:
719
      logging.error("Can't get DRBD usermode helper: %s", str(err))
720
      status = False
721
      payload = str(err)
722
    result[constants.NV_DRBDHELPER] = (status, payload)
723

    
724
  if constants.NV_NODESETUP in what:
725
    result[constants.NV_NODESETUP] = tmpr = []
726
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
727
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
728
                  " under /sys, missing required directories /sys/block"
729
                  " and /sys/class/net")
730
    if (not os.path.isdir("/proc/sys") or
731
        not os.path.isfile("/proc/sysrq-trigger")):
732
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
733
                  " under /proc, missing required directory /proc/sys and"
734
                  " the file /proc/sysrq-trigger")
735

    
736
  if constants.NV_TIME in what:
737
    result[constants.NV_TIME] = utils.SplitTime(time.time())
738

    
739
  if constants.NV_OSLIST in what and vm_capable:
740
    result[constants.NV_OSLIST] = DiagnoseOS()
741

    
742
  if constants.NV_BRIDGES in what and vm_capable:
743
    result[constants.NV_BRIDGES] = [bridge
744
                                    for bridge in what[constants.NV_BRIDGES]
745
                                    if not utils.BridgeExists(bridge)]
746
  return result
747

    
748

    
749
def GetBlockDevSizes(devices):
750
  """Return the size of the given block devices
751

752
  @type devices: list
753
  @param devices: list of block device nodes to query
754
  @rtype: dict
755
  @return:
756
    dictionary of all block devices under /dev (key). The value is their
757
    size in MiB.
758

759
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
760

761
  """
762
  DEV_PREFIX = "/dev/"
763
  blockdevs = {}
764

    
765
  for devpath in devices:
766
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
767
      continue
768

    
769
    try:
770
      st = os.stat(devpath)
771
    except EnvironmentError, err:
772
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
773
      continue
774

    
775
    if stat.S_ISBLK(st.st_mode):
776
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
777
      if result.failed:
778
        # We don't want to fail, just do not list this device as available
779
        logging.warning("Cannot get size for block device %s", devpath)
780
        continue
781

    
782
      size = int(result.stdout) / (1024 * 1024)
783
      blockdevs[devpath] = size
784
  return blockdevs
785

    
786

    
787
def GetVolumeList(vg_names):
788
  """Compute list of logical volumes and their size.
789

790
  @type vg_names: list
791
  @param vg_names: the volume groups whose LVs we should list, or
792
      empty for all volume groups
793
  @rtype: dict
794
  @return:
795
      dictionary of all partions (key) with value being a tuple of
796
      their size (in MiB), inactive and online status::
797

798
        {'xenvg/test1': ('20.06', True, True)}
799

800
      in case of errors, a string is returned with the error
801
      details.
802

803
  """
804
  lvs = {}
805
  sep = "|"
806
  if not vg_names:
807
    vg_names = []
808
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
809
                         "--separator=%s" % sep,
810
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
811
  if result.failed:
812
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
813

    
814
  for line in result.stdout.splitlines():
815
    line = line.strip()
816
    match = _LVSLINE_REGEX.match(line)
817
    if not match:
818
      logging.error("Invalid line returned from lvs output: '%s'", line)
819
      continue
820
    vg_name, name, size, attr = match.groups()
821
    inactive = attr[4] == "-"
822
    online = attr[5] == "o"
823
    virtual = attr[0] == "v"
824
    if virtual:
825
      # we don't want to report such volumes as existing, since they
826
      # don't really hold data
827
      continue
828
    lvs[vg_name + "/" + name] = (size, inactive, online)
829

    
830
  return lvs
831

    
832

    
833
def ListVolumeGroups():
834
  """List the volume groups and their size.
835

836
  @rtype: dict
837
  @return: dictionary with keys volume name and values the
838
      size of the volume
839

840
  """
841
  return utils.ListVolumeGroups()
842

    
843

    
844
def NodeVolumes():
845
  """List all volumes on this node.
846

847
  @rtype: list
848
  @return:
849
    A list of dictionaries, each having four keys:
850
      - name: the logical volume name,
851
      - size: the size of the logical volume
852
      - dev: the physical device on which the LV lives
853
      - vg: the volume group to which it belongs
854

855
    In case of errors, we return an empty list and log the
856
    error.
857

858
    Note that since a logical volume can live on multiple physical
859
    volumes, the resulting list might include a logical volume
860
    multiple times.
861

862
  """
863
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
864
                         "--separator=|",
865
                         "--options=lv_name,lv_size,devices,vg_name"])
866
  if result.failed:
867
    _Fail("Failed to list logical volumes, lvs output: %s",
868
          result.output)
869

    
870
  def parse_dev(dev):
871
    return dev.split("(")[0]
872

    
873
  def handle_dev(dev):
874
    return [parse_dev(x) for x in dev.split(",")]
875

    
876
  def map_line(line):
877
    line = [v.strip() for v in line]
878
    return [{"name": line[0], "size": line[1],
879
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
880

    
881
  all_devs = []
882
  for line in result.stdout.splitlines():
883
    if line.count("|") >= 3:
884
      all_devs.extend(map_line(line.split("|")))
885
    else:
886
      logging.warning("Strange line in the output from lvs: '%s'", line)
887
  return all_devs
888

    
889

    
890
def BridgesExist(bridges_list):
891
  """Check if a list of bridges exist on the current node.
892

893
  @rtype: boolean
894
  @return: C{True} if all of them exist, C{False} otherwise
895

896
  """
897
  missing = []
898
  for bridge in bridges_list:
899
    if not utils.BridgeExists(bridge):
900
      missing.append(bridge)
901

    
902
  if missing:
903
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
904

    
905

    
906
def GetInstanceList(hypervisor_list):
907
  """Provides a list of instances.
908

909
  @type hypervisor_list: list
910
  @param hypervisor_list: the list of hypervisors to query information
911

912
  @rtype: list
913
  @return: a list of all running instances on the current node
914
    - instance1.example.com
915
    - instance2.example.com
916

917
  """
918
  results = []
919
  for hname in hypervisor_list:
920
    try:
921
      names = hypervisor.GetHypervisor(hname).ListInstances()
922
      results.extend(names)
923
    except errors.HypervisorError, err:
924
      _Fail("Error enumerating instances (hypervisor %s): %s",
925
            hname, err, exc=True)
926

    
927
  return results
928

    
929

    
930
def GetInstanceInfo(instance, hname):
931
  """Gives back the information about an instance as a dictionary.
932

933
  @type instance: string
934
  @param instance: the instance name
935
  @type hname: string
936
  @param hname: the hypervisor type of the instance
937

938
  @rtype: dict
939
  @return: dictionary with the following keys:
940
      - memory: memory size of instance (int)
941
      - state: xen state of instance (string)
942
      - time: cpu time of instance (float)
943

944
  """
945
  output = {}
946

    
947
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
948
  if iinfo is not None:
949
    output["memory"] = iinfo[2]
950
    output["state"] = iinfo[4]
951
    output["time"] = iinfo[5]
952

    
953
  return output
954

    
955

    
956
def GetInstanceMigratable(instance):
957
  """Gives whether an instance can be migrated.
958

959
  @type instance: L{objects.Instance}
960
  @param instance: object representing the instance to be checked.
961

962
  @rtype: tuple
963
  @return: tuple of (result, description) where:
964
      - result: whether the instance can be migrated or not
965
      - description: a description of the issue, if relevant
966

967
  """
968
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
969
  iname = instance.name
970
  if iname not in hyper.ListInstances():
971
    _Fail("Instance %s is not running", iname)
972

    
973
  for idx in range(len(instance.disks)):
974
    link_name = _GetBlockDevSymlinkPath(iname, idx)
975
    if not os.path.islink(link_name):
976
      logging.warning("Instance %s is missing symlink %s for disk %d",
977
                      iname, link_name, idx)
978

    
979

    
980
def GetAllInstancesInfo(hypervisor_list):
981
  """Gather data about all instances.
982

983
  This is the equivalent of L{GetInstanceInfo}, except that it
984
  computes data for all instances at once, thus being faster if one
985
  needs data about more than one instance.
986

987
  @type hypervisor_list: list
988
  @param hypervisor_list: list of hypervisors to query for instance data
989

990
  @rtype: dict
991
  @return: dictionary of instance: data, with data having the following keys:
992
      - memory: memory size of instance (int)
993
      - state: xen state of instance (string)
994
      - time: cpu time of instance (float)
995
      - vcpus: the number of vcpus
996

997
  """
998
  output = {}
999

    
1000
  for hname in hypervisor_list:
1001
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
1002
    if iinfo:
1003
      for name, _, memory, vcpus, state, times in iinfo:
1004
        value = {
1005
          "memory": memory,
1006
          "vcpus": vcpus,
1007
          "state": state,
1008
          "time": times,
1009
          }
1010
        if name in output:
1011
          # we only check static parameters, like memory and vcpus,
1012
          # and not state and time which can change between the
1013
          # invocations of the different hypervisors
1014
          for key in "memory", "vcpus":
1015
            if value[key] != output[name][key]:
1016
              _Fail("Instance %s is running twice"
1017
                    " with different parameters", name)
1018
        output[name] = value
1019

    
1020
  return output
1021

    
1022

    
1023
def _InstanceLogName(kind, os_name, instance, component):
1024
  """Compute the OS log filename for a given instance and operation.
1025

1026
  The instance name and os name are passed in as strings since not all
1027
  operations have these as part of an instance object.
1028

1029
  @type kind: string
1030
  @param kind: the operation type (e.g. add, import, etc.)
1031
  @type os_name: string
1032
  @param os_name: the os name
1033
  @type instance: string
1034
  @param instance: the name of the instance being imported/added/etc.
1035
  @type component: string or None
1036
  @param component: the name of the component of the instance being
1037
      transferred
1038

1039
  """
1040
  # TODO: Use tempfile.mkstemp to create unique filename
1041
  if component:
1042
    assert "/" not in component
1043
    c_msg = "-%s" % component
1044
  else:
1045
    c_msg = ""
1046
  base = ("%s-%s-%s%s-%s.log" %
1047
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1048
  return utils.PathJoin(constants.LOG_OS_DIR, base)
1049

    
1050

    
1051
def InstanceOsAdd(instance, reinstall, debug):
1052
  """Add an OS to an instance.
1053

1054
  @type instance: L{objects.Instance}
1055
  @param instance: Instance whose OS is to be installed
1056
  @type reinstall: boolean
1057
  @param reinstall: whether this is an instance reinstall
1058
  @type debug: integer
1059
  @param debug: debug level, passed to the OS scripts
1060
  @rtype: None
1061

1062
  """
1063
  inst_os = OSFromDisk(instance.os)
1064

    
1065
  create_env = OSEnvironment(instance, inst_os, debug)
1066
  if reinstall:
1067
    create_env["INSTANCE_REINSTALL"] = "1"
1068

    
1069
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1070

    
1071
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1072
                        cwd=inst_os.path, output=logfile, reset_env=True)
1073
  if result.failed:
1074
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1075
                  " output: %s", result.cmd, result.fail_reason, logfile,
1076
                  result.output)
1077
    lines = [utils.SafeEncode(val)
1078
             for val in utils.TailFile(logfile, lines=20)]
1079
    _Fail("OS create script failed (%s), last lines in the"
1080
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1081

    
1082

    
1083
def RunRenameInstance(instance, old_name, debug):
1084
  """Run the OS rename script for an instance.
1085

1086
  @type instance: L{objects.Instance}
1087
  @param instance: Instance whose OS is to be installed
1088
  @type old_name: string
1089
  @param old_name: previous instance name
1090
  @type debug: integer
1091
  @param debug: debug level, passed to the OS scripts
1092
  @rtype: boolean
1093
  @return: the success of the operation
1094

1095
  """
1096
  inst_os = OSFromDisk(instance.os)
1097

    
1098
  rename_env = OSEnvironment(instance, inst_os, debug)
1099
  rename_env["OLD_INSTANCE_NAME"] = old_name
1100

    
1101
  logfile = _InstanceLogName("rename", instance.os,
1102
                             "%s-%s" % (old_name, instance.name), None)
1103

    
1104
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1105
                        cwd=inst_os.path, output=logfile, reset_env=True)
1106

    
1107
  if result.failed:
1108
    logging.error("os create command '%s' returned error: %s output: %s",
1109
                  result.cmd, result.fail_reason, result.output)
1110
    lines = [utils.SafeEncode(val)
1111
             for val in utils.TailFile(logfile, lines=20)]
1112
    _Fail("OS rename script failed (%s), last lines in the"
1113
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1114

    
1115

    
1116
def _GetBlockDevSymlinkPath(instance_name, idx):
1117
  return utils.PathJoin(constants.DISK_LINKS_DIR, "%s%s%d" %
1118
                        (instance_name, constants.DISK_SEPARATOR, idx))
1119

    
1120

    
1121
def _SymlinkBlockDev(instance_name, device_path, idx):
1122
  """Set up symlinks to a instance's block device.
1123

1124
  This is an auxiliary function run when an instance is start (on the primary
1125
  node) or when an instance is migrated (on the target node).
1126

1127

1128
  @param instance_name: the name of the target instance
1129
  @param device_path: path of the physical block device, on the node
1130
  @param idx: the disk index
1131
  @return: absolute path to the disk's symlink
1132

1133
  """
1134
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1135
  try:
1136
    os.symlink(device_path, link_name)
1137
  except OSError, err:
1138
    if err.errno == errno.EEXIST:
1139
      if (not os.path.islink(link_name) or
1140
          os.readlink(link_name) != device_path):
1141
        os.remove(link_name)
1142
        os.symlink(device_path, link_name)
1143
    else:
1144
      raise
1145

    
1146
  return link_name
1147

    
1148

    
1149
def _RemoveBlockDevLinks(instance_name, disks):
1150
  """Remove the block device symlinks belonging to the given instance.
1151

1152
  """
1153
  for idx, _ in enumerate(disks):
1154
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1155
    if os.path.islink(link_name):
1156
      try:
1157
        os.remove(link_name)
1158
      except OSError:
1159
        logging.exception("Can't remove symlink '%s'", link_name)
1160

    
1161

    
1162
def _GatherAndLinkBlockDevs(instance):
1163
  """Set up an instance's block device(s).
1164

1165
  This is run on the primary node at instance startup. The block
1166
  devices must be already assembled.
1167

1168
  @type instance: L{objects.Instance}
1169
  @param instance: the instance whose disks we shoul assemble
1170
  @rtype: list
1171
  @return: list of (disk_object, device_path)
1172

1173
  """
1174
  block_devices = []
1175
  for idx, disk in enumerate(instance.disks):
1176
    device = _RecursiveFindBD(disk)
1177
    if device is None:
1178
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1179
                                    str(disk))
1180
    device.Open()
1181
    try:
1182
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1183
    except OSError, e:
1184
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1185
                                    e.strerror)
1186

    
1187
    block_devices.append((disk, link_name))
1188

    
1189
  return block_devices
1190

    
1191

    
1192
def StartInstance(instance, startup_paused):
1193
  """Start an instance.
1194

1195
  @type instance: L{objects.Instance}
1196
  @param instance: the instance object
1197
  @type startup_paused: bool
1198
  @param instance: pause instance at startup?
1199
  @rtype: None
1200

1201
  """
1202
  running_instances = GetInstanceList([instance.hypervisor])
1203

    
1204
  if instance.name in running_instances:
1205
    logging.info("Instance %s already running, not starting", instance.name)
1206
    return
1207

    
1208
  try:
1209
    block_devices = _GatherAndLinkBlockDevs(instance)
1210
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1211
    hyper.StartInstance(instance, block_devices, startup_paused)
1212
  except errors.BlockDeviceError, err:
1213
    _Fail("Block device error: %s", err, exc=True)
1214
  except errors.HypervisorError, err:
1215
    _RemoveBlockDevLinks(instance.name, instance.disks)
1216
    _Fail("Hypervisor error: %s", err, exc=True)
1217

    
1218

    
1219
def InstanceShutdown(instance, timeout):
1220
  """Shut an instance down.
1221

1222
  @note: this functions uses polling with a hardcoded timeout.
1223

1224
  @type instance: L{objects.Instance}
1225
  @param instance: the instance object
1226
  @type timeout: integer
1227
  @param timeout: maximum timeout for soft shutdown
1228
  @rtype: None
1229

1230
  """
1231
  hv_name = instance.hypervisor
1232
  hyper = hypervisor.GetHypervisor(hv_name)
1233
  iname = instance.name
1234

    
1235
  if instance.name not in hyper.ListInstances():
1236
    logging.info("Instance %s not running, doing nothing", iname)
1237
    return
1238

    
1239
  class _TryShutdown:
1240
    def __init__(self):
1241
      self.tried_once = False
1242

    
1243
    def __call__(self):
1244
      if iname not in hyper.ListInstances():
1245
        return
1246

    
1247
      try:
1248
        hyper.StopInstance(instance, retry=self.tried_once)
1249
      except errors.HypervisorError, err:
1250
        if iname not in hyper.ListInstances():
1251
          # if the instance is no longer existing, consider this a
1252
          # success and go to cleanup
1253
          return
1254

    
1255
        _Fail("Failed to stop instance %s: %s", iname, err)
1256

    
1257
      self.tried_once = True
1258

    
1259
      raise utils.RetryAgain()
1260

    
1261
  try:
1262
    utils.Retry(_TryShutdown(), 5, timeout)
1263
  except utils.RetryTimeout:
1264
    # the shutdown did not succeed
1265
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1266

    
1267
    try:
1268
      hyper.StopInstance(instance, force=True)
1269
    except errors.HypervisorError, err:
1270
      if iname in hyper.ListInstances():
1271
        # only raise an error if the instance still exists, otherwise
1272
        # the error could simply be "instance ... unknown"!
1273
        _Fail("Failed to force stop instance %s: %s", iname, err)
1274

    
1275
    time.sleep(1)
1276

    
1277
    if iname in hyper.ListInstances():
1278
      _Fail("Could not shutdown instance %s even by destroy", iname)
1279

    
1280
  try:
1281
    hyper.CleanupInstance(instance.name)
1282
  except errors.HypervisorError, err:
1283
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1284

    
1285
  _RemoveBlockDevLinks(iname, instance.disks)
1286

    
1287

    
1288
def InstanceReboot(instance, reboot_type, shutdown_timeout):
1289
  """Reboot an instance.
1290

1291
  @type instance: L{objects.Instance}
1292
  @param instance: the instance object to reboot
1293
  @type reboot_type: str
1294
  @param reboot_type: the type of reboot, one the following
1295
    constants:
1296
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1297
        instance OS, do not recreate the VM
1298
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1299
        restart the VM (at the hypervisor level)
1300
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1301
        not accepted here, since that mode is handled differently, in
1302
        cmdlib, and translates into full stop and start of the
1303
        instance (instead of a call_instance_reboot RPC)
1304
  @type shutdown_timeout: integer
1305
  @param shutdown_timeout: maximum timeout for soft shutdown
1306
  @rtype: None
1307

1308
  """
1309
  running_instances = GetInstanceList([instance.hypervisor])
1310

    
1311
  if instance.name not in running_instances:
1312
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1313

    
1314
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1315
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1316
    try:
1317
      hyper.RebootInstance(instance)
1318
    except errors.HypervisorError, err:
1319
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1320
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1321
    try:
1322
      InstanceShutdown(instance, shutdown_timeout)
1323
      return StartInstance(instance, False)
1324
    except errors.HypervisorError, err:
1325
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1326
  else:
1327
    _Fail("Invalid reboot_type received: %s", reboot_type)
1328

    
1329

    
1330
def MigrationInfo(instance):
1331
  """Gather information about an instance to be migrated.
1332

1333
  @type instance: L{objects.Instance}
1334
  @param instance: the instance definition
1335

1336
  """
1337
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1338
  try:
1339
    info = hyper.MigrationInfo(instance)
1340
  except errors.HypervisorError, err:
1341
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1342
  return info
1343

    
1344

    
1345
def AcceptInstance(instance, info, target):
1346
  """Prepare the node to accept an instance.
1347

1348
  @type instance: L{objects.Instance}
1349
  @param instance: the instance definition
1350
  @type info: string/data (opaque)
1351
  @param info: migration information, from the source node
1352
  @type target: string
1353
  @param target: target host (usually ip), on this node
1354

1355
  """
1356
  # TODO: why is this required only for DTS_EXT_MIRROR?
1357
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1358
    # Create the symlinks, as the disks are not active
1359
    # in any way
1360
    try:
1361
      _GatherAndLinkBlockDevs(instance)
1362
    except errors.BlockDeviceError, err:
1363
      _Fail("Block device error: %s", err, exc=True)
1364

    
1365
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1366
  try:
1367
    hyper.AcceptInstance(instance, info, target)
1368
  except errors.HypervisorError, err:
1369
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1370
      _RemoveBlockDevLinks(instance.name, instance.disks)
1371
    _Fail("Failed to accept instance: %s", err, exc=True)
1372

    
1373

    
1374
def FinalizeMigrationDst(instance, info, success):
1375
  """Finalize any preparation to accept an instance.
1376

1377
  @type instance: L{objects.Instance}
1378
  @param instance: the instance definition
1379
  @type info: string/data (opaque)
1380
  @param info: migration information, from the source node
1381
  @type success: boolean
1382
  @param success: whether the migration was a success or a failure
1383

1384
  """
1385
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1386
  try:
1387
    hyper.FinalizeMigrationDst(instance, info, success)
1388
  except errors.HypervisorError, err:
1389
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1390

    
1391

    
1392
def MigrateInstance(instance, target, live):
1393
  """Migrates an instance to another node.
1394

1395
  @type instance: L{objects.Instance}
1396
  @param instance: the instance definition
1397
  @type target: string
1398
  @param target: the target node name
1399
  @type live: boolean
1400
  @param live: whether the migration should be done live or not (the
1401
      interpretation of this parameter is left to the hypervisor)
1402
  @raise RPCFail: if migration fails for some reason
1403

1404
  """
1405
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1406

    
1407
  try:
1408
    hyper.MigrateInstance(instance, target, live)
1409
  except errors.HypervisorError, err:
1410
    _Fail("Failed to migrate instance: %s", err, exc=True)
1411

    
1412

    
1413
def FinalizeMigrationSource(instance, success, live):
1414
  """Finalize the instance migration on the source node.
1415

1416
  @type instance: L{objects.Instance}
1417
  @param instance: the instance definition of the migrated instance
1418
  @type success: bool
1419
  @param success: whether the migration succeeded or not
1420
  @type live: bool
1421
  @param live: whether the user requested a live migration or not
1422
  @raise RPCFail: If the execution fails for some reason
1423

1424
  """
1425
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1426

    
1427
  try:
1428
    hyper.FinalizeMigrationSource(instance, success, live)
1429
  except Exception, err:  # pylint: disable=W0703
1430
    _Fail("Failed to finalize the migration on the source node: %s", err,
1431
          exc=True)
1432

    
1433

    
1434
def GetMigrationStatus(instance):
1435
  """Get the migration status
1436

1437
  @type instance: L{objects.Instance}
1438
  @param instance: the instance that is being migrated
1439
  @rtype: L{objects.MigrationStatus}
1440
  @return: the status of the current migration (one of
1441
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1442
           progress info that can be retrieved from the hypervisor
1443
  @raise RPCFail: If the migration status cannot be retrieved
1444

1445
  """
1446
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1447
  try:
1448
    return hyper.GetMigrationStatus(instance)
1449
  except Exception, err:  # pylint: disable=W0703
1450
    _Fail("Failed to get migration status: %s", err, exc=True)
1451

    
1452

    
1453
def BlockdevCreate(disk, size, owner, on_primary, info):
1454
  """Creates a block device for an instance.
1455

1456
  @type disk: L{objects.Disk}
1457
  @param disk: the object describing the disk we should create
1458
  @type size: int
1459
  @param size: the size of the physical underlying device, in MiB
1460
  @type owner: str
1461
  @param owner: the name of the instance for which disk is created,
1462
      used for device cache data
1463
  @type on_primary: boolean
1464
  @param on_primary:  indicates if it is the primary node or not
1465
  @type info: string
1466
  @param info: string that will be sent to the physical device
1467
      creation, used for example to set (LVM) tags on LVs
1468

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

1473
  """
1474
  # TODO: remove the obsolete "size" argument
1475
  # pylint: disable=W0613
1476
  clist = []
1477
  if disk.children:
1478
    for child in disk.children:
1479
      try:
1480
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1481
      except errors.BlockDeviceError, err:
1482
        _Fail("Can't assemble device %s: %s", child, err)
1483
      if on_primary or disk.AssembleOnSecondary():
1484
        # we need the children open in case the device itself has to
1485
        # be assembled
1486
        try:
1487
          # pylint: disable=E1103
1488
          crdev.Open()
1489
        except errors.BlockDeviceError, err:
1490
          _Fail("Can't make child '%s' read-write: %s", child, err)
1491
      clist.append(crdev)
1492

    
1493
  try:
1494
    device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
1495
  except errors.BlockDeviceError, err:
1496
    _Fail("Can't create block device: %s", err)
1497

    
1498
  if on_primary or disk.AssembleOnSecondary():
1499
    try:
1500
      device.Assemble()
1501
    except errors.BlockDeviceError, err:
1502
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1503
    device.SetSyncSpeed(constants.SYNC_SPEED)
1504
    if on_primary or disk.OpenOnSecondary():
1505
      try:
1506
        device.Open(force=True)
1507
      except errors.BlockDeviceError, err:
1508
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1509
    DevCacheManager.UpdateCache(device.dev_path, owner,
1510
                                on_primary, disk.iv_name)
1511

    
1512
  device.SetInfo(info)
1513

    
1514
  return device.unique_id
1515

    
1516

    
1517
def _WipeDevice(path, offset, size):
1518
  """This function actually wipes the device.
1519

1520
  @param path: The path to the device to wipe
1521
  @param offset: The offset in MiB in the file
1522
  @param size: The size in MiB to write
1523

1524
  """
1525
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1526
         "bs=%d" % constants.WIPE_BLOCK_SIZE, "oflag=direct", "of=%s" % path,
1527
         "count=%d" % size]
1528
  result = utils.RunCmd(cmd)
1529

    
1530
  if result.failed:
1531
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1532
          result.fail_reason, result.output)
1533

    
1534

    
1535
def BlockdevWipe(disk, offset, size):
1536
  """Wipes a block device.
1537

1538
  @type disk: L{objects.Disk}
1539
  @param disk: the disk object we want to wipe
1540
  @type offset: int
1541
  @param offset: The offset in MiB in the file
1542
  @type size: int
1543
  @param size: The size in MiB to write
1544

1545
  """
1546
  try:
1547
    rdev = _RecursiveFindBD(disk)
1548
  except errors.BlockDeviceError:
1549
    rdev = None
1550

    
1551
  if not rdev:
1552
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1553

    
1554
  # Do cross verify some of the parameters
1555
  if offset > rdev.size:
1556
    _Fail("Offset is bigger than device size")
1557
  if (offset + size) > rdev.size:
1558
    _Fail("The provided offset and size to wipe is bigger than device size")
1559

    
1560
  _WipeDevice(rdev.dev_path, offset, size)
1561

    
1562

    
1563
def BlockdevPauseResumeSync(disks, pause):
1564
  """Pause or resume the sync of the block device.
1565

1566
  @type disks: list of L{objects.Disk}
1567
  @param disks: the disks object we want to pause/resume
1568
  @type pause: bool
1569
  @param pause: Wheater to pause or resume
1570

1571
  """
1572
  success = []
1573
  for disk in disks:
1574
    try:
1575
      rdev = _RecursiveFindBD(disk)
1576
    except errors.BlockDeviceError:
1577
      rdev = None
1578

    
1579
    if not rdev:
1580
      success.append((False, ("Cannot change sync for device %s:"
1581
                              " device not found" % disk.iv_name)))
1582
      continue
1583

    
1584
    result = rdev.PauseResumeSync(pause)
1585

    
1586
    if result:
1587
      success.append((result, None))
1588
    else:
1589
      if pause:
1590
        msg = "Pause"
1591
      else:
1592
        msg = "Resume"
1593
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1594

    
1595
  return success
1596

    
1597

    
1598
def BlockdevRemove(disk):
1599
  """Remove a block device.
1600

1601
  @note: This is intended to be called recursively.
1602

1603
  @type disk: L{objects.Disk}
1604
  @param disk: the disk object we should remove
1605
  @rtype: boolean
1606
  @return: the success of the operation
1607

1608
  """
1609
  msgs = []
1610
  try:
1611
    rdev = _RecursiveFindBD(disk)
1612
  except errors.BlockDeviceError, err:
1613
    # probably can't attach
1614
    logging.info("Can't attach to device %s in remove", disk)
1615
    rdev = None
1616
  if rdev is not None:
1617
    r_path = rdev.dev_path
1618
    try:
1619
      rdev.Remove()
1620
    except errors.BlockDeviceError, err:
1621
      msgs.append(str(err))
1622
    if not msgs:
1623
      DevCacheManager.RemoveCache(r_path)
1624

    
1625
  if disk.children:
1626
    for child in disk.children:
1627
      try:
1628
        BlockdevRemove(child)
1629
      except RPCFail, err:
1630
        msgs.append(str(err))
1631

    
1632
  if msgs:
1633
    _Fail("; ".join(msgs))
1634

    
1635

    
1636
def _RecursiveAssembleBD(disk, owner, as_primary):
1637
  """Activate a block device for an instance.
1638

1639
  This is run on the primary and secondary nodes for an instance.
1640

1641
  @note: this function is called recursively.
1642

1643
  @type disk: L{objects.Disk}
1644
  @param disk: the disk we try to assemble
1645
  @type owner: str
1646
  @param owner: the name of the instance which owns the disk
1647
  @type as_primary: boolean
1648
  @param as_primary: if we should make the block device
1649
      read/write
1650

1651
  @return: the assembled device or None (in case no device
1652
      was assembled)
1653
  @raise errors.BlockDeviceError: in case there is an error
1654
      during the activation of the children or the device
1655
      itself
1656

1657
  """
1658
  children = []
1659
  if disk.children:
1660
    mcn = disk.ChildrenNeeded()
1661
    if mcn == -1:
1662
      mcn = 0 # max number of Nones allowed
1663
    else:
1664
      mcn = len(disk.children) - mcn # max number of Nones
1665
    for chld_disk in disk.children:
1666
      try:
1667
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1668
      except errors.BlockDeviceError, err:
1669
        if children.count(None) >= mcn:
1670
          raise
1671
        cdev = None
1672
        logging.error("Error in child activation (but continuing): %s",
1673
                      str(err))
1674
      children.append(cdev)
1675

    
1676
  if as_primary or disk.AssembleOnSecondary():
1677
    r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
1678
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1679
    result = r_dev
1680
    if as_primary or disk.OpenOnSecondary():
1681
      r_dev.Open()
1682
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1683
                                as_primary, disk.iv_name)
1684

    
1685
  else:
1686
    result = True
1687
  return result
1688

    
1689

    
1690
def BlockdevAssemble(disk, owner, as_primary, idx):
1691
  """Activate a block device for an instance.
1692

1693
  This is a wrapper over _RecursiveAssembleBD.
1694

1695
  @rtype: str or boolean
1696
  @return: a C{/dev/...} path for primary nodes, and
1697
      C{True} for secondary nodes
1698

1699
  """
1700
  try:
1701
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1702
    if isinstance(result, bdev.BlockDev):
1703
      # pylint: disable=E1103
1704
      result = result.dev_path
1705
      if as_primary:
1706
        _SymlinkBlockDev(owner, result, idx)
1707
  except errors.BlockDeviceError, err:
1708
    _Fail("Error while assembling disk: %s", err, exc=True)
1709
  except OSError, err:
1710
    _Fail("Error while symlinking disk: %s", err, exc=True)
1711

    
1712
  return result
1713

    
1714

    
1715
def BlockdevShutdown(disk):
1716
  """Shut down a block device.
1717

1718
  First, if the device is assembled (Attach() is successful), then
1719
  the device is shutdown. Then the children of the device are
1720
  shutdown.
1721

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

1726
  @type disk: L{objects.Disk}
1727
  @param disk: the description of the disk we should
1728
      shutdown
1729
  @rtype: None
1730

1731
  """
1732
  msgs = []
1733
  r_dev = _RecursiveFindBD(disk)
1734
  if r_dev is not None:
1735
    r_path = r_dev.dev_path
1736
    try:
1737
      r_dev.Shutdown()
1738
      DevCacheManager.RemoveCache(r_path)
1739
    except errors.BlockDeviceError, err:
1740
      msgs.append(str(err))
1741

    
1742
  if disk.children:
1743
    for child in disk.children:
1744
      try:
1745
        BlockdevShutdown(child)
1746
      except RPCFail, err:
1747
        msgs.append(str(err))
1748

    
1749
  if msgs:
1750
    _Fail("; ".join(msgs))
1751

    
1752

    
1753
def BlockdevAddchildren(parent_cdev, new_cdevs):
1754
  """Extend a mirrored block device.
1755

1756
  @type parent_cdev: L{objects.Disk}
1757
  @param parent_cdev: the disk to which we should add children
1758
  @type new_cdevs: list of L{objects.Disk}
1759
  @param new_cdevs: the list of children which we should add
1760
  @rtype: None
1761

1762
  """
1763
  parent_bdev = _RecursiveFindBD(parent_cdev)
1764
  if parent_bdev is None:
1765
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1766
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1767
  if new_bdevs.count(None) > 0:
1768
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1769
  parent_bdev.AddChildren(new_bdevs)
1770

    
1771

    
1772
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1773
  """Shrink a mirrored block device.
1774

1775
  @type parent_cdev: L{objects.Disk}
1776
  @param parent_cdev: the disk from which we should remove children
1777
  @type new_cdevs: list of L{objects.Disk}
1778
  @param new_cdevs: the list of children which we should remove
1779
  @rtype: None
1780

1781
  """
1782
  parent_bdev = _RecursiveFindBD(parent_cdev)
1783
  if parent_bdev is None:
1784
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1785
  devs = []
1786
  for disk in new_cdevs:
1787
    rpath = disk.StaticDevPath()
1788
    if rpath is None:
1789
      bd = _RecursiveFindBD(disk)
1790
      if bd is None:
1791
        _Fail("Can't find device %s while removing children", disk)
1792
      else:
1793
        devs.append(bd.dev_path)
1794
    else:
1795
      if not utils.IsNormAbsPath(rpath):
1796
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
1797
      devs.append(rpath)
1798
  parent_bdev.RemoveChildren(devs)
1799

    
1800

    
1801
def BlockdevGetmirrorstatus(disks):
1802
  """Get the mirroring status of a list of devices.
1803

1804
  @type disks: list of L{objects.Disk}
1805
  @param disks: the list of disks which we should query
1806
  @rtype: disk
1807
  @return: List of L{objects.BlockDevStatus}, one for each disk
1808
  @raise errors.BlockDeviceError: if any of the disks cannot be
1809
      found
1810

1811
  """
1812
  stats = []
1813
  for dsk in disks:
1814
    rbd = _RecursiveFindBD(dsk)
1815
    if rbd is None:
1816
      _Fail("Can't find device %s", dsk)
1817

    
1818
    stats.append(rbd.CombinedSyncStatus())
1819

    
1820
  return stats
1821

    
1822

    
1823
def BlockdevGetmirrorstatusMulti(disks):
1824
  """Get the mirroring status of a list of devices.
1825

1826
  @type disks: list of L{objects.Disk}
1827
  @param disks: the list of disks which we should query
1828
  @rtype: disk
1829
  @return: List of tuples, (bool, status), one for each disk; bool denotes
1830
    success/failure, status is L{objects.BlockDevStatus} on success, string
1831
    otherwise
1832

1833
  """
1834
  result = []
1835
  for disk in disks:
1836
    try:
1837
      rbd = _RecursiveFindBD(disk)
1838
      if rbd is None:
1839
        result.append((False, "Can't find device %s" % disk))
1840
        continue
1841

    
1842
      status = rbd.CombinedSyncStatus()
1843
    except errors.BlockDeviceError, err:
1844
      logging.exception("Error while getting disk status")
1845
      result.append((False, str(err)))
1846
    else:
1847
      result.append((True, status))
1848

    
1849
  assert len(disks) == len(result)
1850

    
1851
  return result
1852

    
1853

    
1854
def _RecursiveFindBD(disk):
1855
  """Check if a device is activated.
1856

1857
  If so, return information about the real device.
1858

1859
  @type disk: L{objects.Disk}
1860
  @param disk: the disk object we need to find
1861

1862
  @return: None if the device can't be found,
1863
      otherwise the device instance
1864

1865
  """
1866
  children = []
1867
  if disk.children:
1868
    for chdisk in disk.children:
1869
      children.append(_RecursiveFindBD(chdisk))
1870

    
1871
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1872

    
1873

    
1874
def _OpenRealBD(disk):
1875
  """Opens the underlying block device of a disk.
1876

1877
  @type disk: L{objects.Disk}
1878
  @param disk: the disk object we want to open
1879

1880
  """
1881
  real_disk = _RecursiveFindBD(disk)
1882
  if real_disk is None:
1883
    _Fail("Block device '%s' is not set up", disk)
1884

    
1885
  real_disk.Open()
1886

    
1887
  return real_disk
1888

    
1889

    
1890
def BlockdevFind(disk):
1891
  """Check if a device is activated.
1892

1893
  If it is, return information about the real device.
1894

1895
  @type disk: L{objects.Disk}
1896
  @param disk: the disk to find
1897
  @rtype: None or objects.BlockDevStatus
1898
  @return: None if the disk cannot be found, otherwise a the current
1899
           information
1900

1901
  """
1902
  try:
1903
    rbd = _RecursiveFindBD(disk)
1904
  except errors.BlockDeviceError, err:
1905
    _Fail("Failed to find device: %s", err, exc=True)
1906

    
1907
  if rbd is None:
1908
    return None
1909

    
1910
  return rbd.GetSyncStatus()
1911

    
1912

    
1913
def BlockdevGetsize(disks):
1914
  """Computes the size of the given disks.
1915

1916
  If a disk is not found, returns None instead.
1917

1918
  @type disks: list of L{objects.Disk}
1919
  @param disks: the list of disk to compute the size for
1920
  @rtype: list
1921
  @return: list with elements None if the disk cannot be found,
1922
      otherwise the size
1923

1924
  """
1925
  result = []
1926
  for cf in disks:
1927
    try:
1928
      rbd = _RecursiveFindBD(cf)
1929
    except errors.BlockDeviceError:
1930
      result.append(None)
1931
      continue
1932
    if rbd is None:
1933
      result.append(None)
1934
    else:
1935
      result.append(rbd.GetActualSize())
1936
  return result
1937

    
1938

    
1939
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
1940
  """Export a block device to a remote node.
1941

1942
  @type disk: L{objects.Disk}
1943
  @param disk: the description of the disk to export
1944
  @type dest_node: str
1945
  @param dest_node: the destination node to export to
1946
  @type dest_path: str
1947
  @param dest_path: the destination path on the target node
1948
  @type cluster_name: str
1949
  @param cluster_name: the cluster name, needed for SSH hostalias
1950
  @rtype: None
1951

1952
  """
1953
  real_disk = _OpenRealBD(disk)
1954

    
1955
  # the block size on the read dd is 1MiB to match our units
1956
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
1957
                               "dd if=%s bs=1048576 count=%s",
1958
                               real_disk.dev_path, str(disk.size))
1959

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

    
1969
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1970
                                                   constants.GANETI_RUNAS,
1971
                                                   destcmd)
1972

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

    
1976
  result = utils.RunCmd(["bash", "-c", command])
1977

    
1978
  if result.failed:
1979
    _Fail("Disk copy command '%s' returned error: %s"
1980
          " output: %s", command, result.fail_reason, result.output)
1981

    
1982

    
1983
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1984
  """Write a file to the filesystem.
1985

1986
  This allows the master to overwrite(!) a file. It will only perform
1987
  the operation if the file belongs to a list of configuration files.
1988

1989
  @type file_name: str
1990
  @param file_name: the target file name
1991
  @type data: str
1992
  @param data: the new contents of the file
1993
  @type mode: int
1994
  @param mode: the mode to give the file (can be None)
1995
  @type uid: string
1996
  @param uid: the owner of the file
1997
  @type gid: string
1998
  @param gid: the group of the file
1999
  @type atime: float
2000
  @param atime: the atime to set on the file (can be None)
2001
  @type mtime: float
2002
  @param mtime: the mtime to set on the file (can be None)
2003
  @rtype: None
2004

2005
  """
2006
  if not os.path.isabs(file_name):
2007
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2008

    
2009
  if file_name not in _ALLOWED_UPLOAD_FILES:
2010
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2011
          file_name)
2012

    
2013
  raw_data = _Decompress(data)
2014

    
2015
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2016
    _Fail("Invalid username/groupname type")
2017

    
2018
  getents = runtime.GetEnts()
2019
  uid = getents.LookupUser(uid)
2020
  gid = getents.LookupGroup(gid)
2021

    
2022
  utils.SafeWriteFile(file_name, None,
2023
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2024
                      atime=atime, mtime=mtime)
2025

    
2026

    
2027
def RunOob(oob_program, command, node, timeout):
2028
  """Executes oob_program with given command on given node.
2029

2030
  @param oob_program: The path to the executable oob_program
2031
  @param command: The command to invoke on oob_program
2032
  @param node: The node given as an argument to the program
2033
  @param timeout: Timeout after which we kill the oob program
2034

2035
  @return: stdout
2036
  @raise RPCFail: If execution fails for some reason
2037

2038
  """
2039
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2040

    
2041
  if result.failed:
2042
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2043
          result.fail_reason, result.output)
2044

    
2045
  return result.stdout
2046

    
2047

    
2048
def WriteSsconfFiles(values):
2049
  """Update all ssconf files.
2050

2051
  Wrapper around the SimpleStore.WriteFiles.
2052

2053
  """
2054
  ssconf.SimpleStore().WriteFiles(values)
2055

    
2056

    
2057
def _ErrnoOrStr(err):
2058
  """Format an EnvironmentError exception.
2059

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

2064
  @type err: L{EnvironmentError}
2065
  @param err: the exception to format
2066

2067
  """
2068
  if hasattr(err, "errno"):
2069
    detail = errno.errorcode[err.errno]
2070
  else:
2071
    detail = str(err)
2072
  return detail
2073

    
2074

    
2075
def _OSOndiskAPIVersion(os_dir):
2076
  """Compute and return the API version of a given OS.
2077

2078
  This function will try to read the API version of the OS residing in
2079
  the 'os_dir' directory.
2080

2081
  @type os_dir: str
2082
  @param os_dir: the directory in which we should look for the OS
2083
  @rtype: tuple
2084
  @return: tuple (status, data) with status denoting the validity and
2085
      data holding either the vaid versions or an error message
2086

2087
  """
2088
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2089

    
2090
  try:
2091
    st = os.stat(api_file)
2092
  except EnvironmentError, err:
2093
    return False, ("Required file '%s' not found under path %s: %s" %
2094
                   (constants.OS_API_FILE, os_dir, _ErrnoOrStr(err)))
2095

    
2096
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2097
    return False, ("File '%s' in %s is not a regular file" %
2098
                   (constants.OS_API_FILE, os_dir))
2099

    
2100
  try:
2101
    api_versions = utils.ReadFile(api_file).splitlines()
2102
  except EnvironmentError, err:
2103
    return False, ("Error while reading the API version file at %s: %s" %
2104
                   (api_file, _ErrnoOrStr(err)))
2105

    
2106
  try:
2107
    api_versions = [int(version.strip()) for version in api_versions]
2108
  except (TypeError, ValueError), err:
2109
    return False, ("API version(s) can't be converted to integer: %s" %
2110
                   str(err))
2111

    
2112
  return True, api_versions
2113

    
2114

    
2115
def DiagnoseOS(top_dirs=None):
2116
  """Compute the validity for all OSes.
2117

2118
  @type top_dirs: list
2119
  @param top_dirs: the list of directories in which to
2120
      search (if not given defaults to
2121
      L{constants.OS_SEARCH_PATH})
2122
  @rtype: list of L{objects.OS}
2123
  @return: a list of tuples (name, path, status, diagnose, variants,
2124
      parameters, api_version) for all (potential) OSes under all
2125
      search paths, where:
2126
          - name is the (potential) OS name
2127
          - path is the full path to the OS
2128
          - status True/False is the validity of the OS
2129
          - diagnose is the error message for an invalid OS, otherwise empty
2130
          - variants is a list of supported OS variants, if any
2131
          - parameters is a list of (name, help) parameters, if any
2132
          - api_version is a list of support OS API versions
2133

2134
  """
2135
  if top_dirs is None:
2136
    top_dirs = constants.OS_SEARCH_PATH
2137

    
2138
  result = []
2139
  for dir_name in top_dirs:
2140
    if os.path.isdir(dir_name):
2141
      try:
2142
        f_names = utils.ListVisibleFiles(dir_name)
2143
      except EnvironmentError, err:
2144
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2145
        break
2146
      for name in f_names:
2147
        os_path = utils.PathJoin(dir_name, name)
2148
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2149
        if status:
2150
          diagnose = ""
2151
          variants = os_inst.supported_variants
2152
          parameters = os_inst.supported_parameters
2153
          api_versions = os_inst.api_versions
2154
        else:
2155
          diagnose = os_inst
2156
          variants = parameters = api_versions = []
2157
        result.append((name, os_path, status, diagnose, variants,
2158
                       parameters, api_versions))
2159

    
2160
  return result
2161

    
2162

    
2163
def _TryOSFromDisk(name, base_dir=None):
2164
  """Create an OS instance from disk.
2165

2166
  This function will return an OS instance if the given name is a
2167
  valid OS name.
2168

2169
  @type base_dir: string
2170
  @keyword base_dir: Base directory containing OS installations.
2171
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2172
  @rtype: tuple
2173
  @return: success and either the OS instance if we find a valid one,
2174
      or error message
2175

2176
  """
2177
  if base_dir is None:
2178
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
2179
  else:
2180
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2181

    
2182
  if os_dir is None:
2183
    return False, "Directory for OS %s not found in search path" % name
2184

    
2185
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2186
  if not status:
2187
    # push the error up
2188
    return status, api_versions
2189

    
2190
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2191
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2192
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2193

    
2194
  # OS Files dictionary, we will populate it with the absolute path
2195
  # names; if the value is True, then it is a required file, otherwise
2196
  # an optional one
2197
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2198

    
2199
  if max(api_versions) >= constants.OS_API_V15:
2200
    os_files[constants.OS_VARIANTS_FILE] = False
2201

    
2202
  if max(api_versions) >= constants.OS_API_V20:
2203
    os_files[constants.OS_PARAMETERS_FILE] = True
2204
  else:
2205
    del os_files[constants.OS_SCRIPT_VERIFY]
2206

    
2207
  for (filename, required) in os_files.items():
2208
    os_files[filename] = utils.PathJoin(os_dir, filename)
2209

    
2210
    try:
2211
      st = os.stat(os_files[filename])
2212
    except EnvironmentError, err:
2213
      if err.errno == errno.ENOENT and not required:
2214
        del os_files[filename]
2215
        continue
2216
      return False, ("File '%s' under path '%s' is missing (%s)" %
2217
                     (filename, os_dir, _ErrnoOrStr(err)))
2218

    
2219
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2220
      return False, ("File '%s' under path '%s' is not a regular file" %
2221
                     (filename, os_dir))
2222

    
2223
    if filename in constants.OS_SCRIPTS:
2224
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2225
        return False, ("File '%s' under path '%s' is not executable" %
2226
                       (filename, os_dir))
2227

    
2228
  variants = []
2229
  if constants.OS_VARIANTS_FILE in os_files:
2230
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2231
    try:
2232
      variants = utils.ReadFile(variants_file).splitlines()
2233
    except EnvironmentError, err:
2234
      # we accept missing files, but not other errors
2235
      if err.errno != errno.ENOENT:
2236
        return False, ("Error while reading the OS variants file at %s: %s" %
2237
                       (variants_file, _ErrnoOrStr(err)))
2238

    
2239
  parameters = []
2240
  if constants.OS_PARAMETERS_FILE in os_files:
2241
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2242
    try:
2243
      parameters = utils.ReadFile(parameters_file).splitlines()
2244
    except EnvironmentError, err:
2245
      return False, ("Error while reading the OS parameters file at %s: %s" %
2246
                     (parameters_file, _ErrnoOrStr(err)))
2247
    parameters = [v.split(None, 1) for v in parameters]
2248

    
2249
  os_obj = objects.OS(name=name, path=os_dir,
2250
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2251
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2252
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2253
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2254
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2255
                                                 None),
2256
                      supported_variants=variants,
2257
                      supported_parameters=parameters,
2258
                      api_versions=api_versions)
2259
  return True, os_obj
2260

    
2261

    
2262
def OSFromDisk(name, base_dir=None):
2263
  """Create an OS instance from disk.
2264

2265
  This function will return an OS instance if the given name is a
2266
  valid OS name. Otherwise, it will raise an appropriate
2267
  L{RPCFail} exception, detailing why this is not a valid OS.
2268

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

2272
  @type base_dir: string
2273
  @keyword base_dir: Base directory containing OS installations.
2274
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2275
  @rtype: L{objects.OS}
2276
  @return: the OS instance if we find a valid one
2277
  @raise RPCFail: if we don't find a valid OS
2278

2279
  """
2280
  name_only = objects.OS.GetName(name)
2281
  status, payload = _TryOSFromDisk(name_only, base_dir)
2282

    
2283
  if not status:
2284
    _Fail(payload)
2285

    
2286
  return payload
2287

    
2288

    
2289
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2290
  """Calculate the basic environment for an os script.
2291

2292
  @type os_name: str
2293
  @param os_name: full operating system name (including variant)
2294
  @type inst_os: L{objects.OS}
2295
  @param inst_os: operating system for which the environment is being built
2296
  @type os_params: dict
2297
  @param os_params: the OS parameters
2298
  @type debug: integer
2299
  @param debug: debug level (0 or 1, for OS Api 10)
2300
  @rtype: dict
2301
  @return: dict of environment variables
2302
  @raise errors.BlockDeviceError: if the block device
2303
      cannot be found
2304

2305
  """
2306
  result = {}
2307
  api_version = \
2308
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2309
  result["OS_API_VERSION"] = "%d" % api_version
2310
  result["OS_NAME"] = inst_os.name
2311
  result["DEBUG_LEVEL"] = "%d" % debug
2312

    
2313
  # OS variants
2314
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2315
    variant = objects.OS.GetVariant(os_name)
2316
    if not variant:
2317
      variant = inst_os.supported_variants[0]
2318
  else:
2319
    variant = ""
2320
  result["OS_VARIANT"] = variant
2321

    
2322
  # OS params
2323
  for pname, pvalue in os_params.items():
2324
    result["OSP_%s" % pname.upper()] = pvalue
2325

    
2326
  return result
2327

    
2328

    
2329
def OSEnvironment(instance, inst_os, debug=0):
2330
  """Calculate the environment for an os script.
2331

2332
  @type instance: L{objects.Instance}
2333
  @param instance: target instance for the os script run
2334
  @type inst_os: L{objects.OS}
2335
  @param inst_os: operating system for which the environment is being built
2336
  @type debug: integer
2337
  @param debug: debug level (0 or 1, for OS Api 10)
2338
  @rtype: dict
2339
  @return: dict of environment variables
2340
  @raise errors.BlockDeviceError: if the block device
2341
      cannot be found
2342

2343
  """
2344
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2345

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

    
2349
  result["HYPERVISOR"] = instance.hypervisor
2350
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2351
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2352
  result["INSTANCE_SECONDARY_NODES"] = \
2353
      ("%s" % " ".join(instance.secondary_nodes))
2354

    
2355
  # Disks
2356
  for idx, disk in enumerate(instance.disks):
2357
    real_disk = _OpenRealBD(disk)
2358
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2359
    result["DISK_%d_ACCESS" % idx] = disk.mode
2360
    if constants.HV_DISK_TYPE in instance.hvparams:
2361
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2362
        instance.hvparams[constants.HV_DISK_TYPE]
2363
    if disk.dev_type in constants.LDS_BLOCK:
2364
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2365
    elif disk.dev_type == constants.LD_FILE:
2366
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2367
        "file:%s" % disk.physical_id[0]
2368

    
2369
  # NICs
2370
  for idx, nic in enumerate(instance.nics):
2371
    result["NIC_%d_MAC" % idx] = nic.mac
2372
    if nic.ip:
2373
      result["NIC_%d_IP" % idx] = nic.ip
2374
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2375
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2376
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2377
    if nic.nicparams[constants.NIC_LINK]:
2378
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2379
    if constants.HV_NIC_TYPE in instance.hvparams:
2380
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2381
        instance.hvparams[constants.HV_NIC_TYPE]
2382

    
2383
  # HV/BE params
2384
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2385
    for key, value in source.items():
2386
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2387

    
2388
  return result
2389

    
2390

    
2391
def BlockdevGrow(disk, amount, dryrun):
2392
  """Grow a stack of block devices.
2393

2394
  This function is called recursively, with the childrens being the
2395
  first ones to resize.
2396

2397
  @type disk: L{objects.Disk}
2398
  @param disk: the disk to be grown
2399
  @type amount: integer
2400
  @param amount: the amount (in mebibytes) to grow with
2401
  @type dryrun: boolean
2402
  @param dryrun: whether to execute the operation in simulation mode
2403
      only, without actually increasing the size
2404
  @rtype: (status, result)
2405
  @return: a tuple with the status of the operation (True/False), and
2406
      the errors message if status is False
2407

2408
  """
2409
  r_dev = _RecursiveFindBD(disk)
2410
  if r_dev is None:
2411
    _Fail("Cannot find block device %s", disk)
2412

    
2413
  try:
2414
    r_dev.Grow(amount, dryrun)
2415
  except errors.BlockDeviceError, err:
2416
    _Fail("Failed to grow block device: %s", err, exc=True)
2417

    
2418

    
2419
def BlockdevSnapshot(disk):
2420
  """Create a snapshot copy of a block device.
2421

2422
  This function is called recursively, and the snapshot is actually created
2423
  just for the leaf lvm backend device.
2424

2425
  @type disk: L{objects.Disk}
2426
  @param disk: the disk to be snapshotted
2427
  @rtype: string
2428
  @return: snapshot disk ID as (vg, lv)
2429

2430
  """
2431
  if disk.dev_type == constants.LD_DRBD8:
2432
    if not disk.children:
2433
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2434
            disk.unique_id)
2435
    return BlockdevSnapshot(disk.children[0])
2436
  elif disk.dev_type == constants.LD_LV:
2437
    r_dev = _RecursiveFindBD(disk)
2438
    if r_dev is not None:
2439
      # FIXME: choose a saner value for the snapshot size
2440
      # let's stay on the safe side and ask for the full size, for now
2441
      return r_dev.Snapshot(disk.size)
2442
    else:
2443
      _Fail("Cannot find block device %s", disk)
2444
  else:
2445
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2446
          disk.unique_id, disk.dev_type)
2447

    
2448

    
2449
def FinalizeExport(instance, snap_disks):
2450
  """Write out the export configuration information.
2451

2452
  @type instance: L{objects.Instance}
2453
  @param instance: the instance which we export, used for
2454
      saving configuration
2455
  @type snap_disks: list of L{objects.Disk}
2456
  @param snap_disks: list of snapshot block devices, which
2457
      will be used to get the actual name of the dump file
2458

2459
  @rtype: None
2460

2461
  """
2462
  destdir = utils.PathJoin(constants.EXPORT_DIR, instance.name + ".new")
2463
  finaldestdir = utils.PathJoin(constants.EXPORT_DIR, instance.name)
2464

    
2465
  config = objects.SerializableConfigParser()
2466

    
2467
  config.add_section(constants.INISECT_EXP)
2468
  config.set(constants.INISECT_EXP, "version", "0")
2469
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2470
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2471
  config.set(constants.INISECT_EXP, "os", instance.os)
2472
  config.set(constants.INISECT_EXP, "compression", "none")
2473

    
2474
  config.add_section(constants.INISECT_INS)
2475
  config.set(constants.INISECT_INS, "name", instance.name)
2476
  config.set(constants.INISECT_INS, "memory", "%d" %
2477
             instance.beparams[constants.BE_MEMORY])
2478
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2479
             instance.beparams[constants.BE_VCPUS])
2480
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2481
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2482
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2483

    
2484
  nic_total = 0
2485
  for nic_count, nic in enumerate(instance.nics):
2486
    nic_total += 1
2487
    config.set(constants.INISECT_INS, "nic%d_mac" %
2488
               nic_count, "%s" % nic.mac)
2489
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2490
    for param in constants.NICS_PARAMETER_TYPES:
2491
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2492
                 "%s" % nic.nicparams.get(param, None))
2493
  # TODO: redundant: on load can read nics until it doesn't exist
2494
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2495

    
2496
  disk_total = 0
2497
  for disk_count, disk in enumerate(snap_disks):
2498
    if disk:
2499
      disk_total += 1
2500
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2501
                 ("%s" % disk.iv_name))
2502
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2503
                 ("%s" % disk.physical_id[1]))
2504
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2505
                 ("%d" % disk.size))
2506

    
2507
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2508

    
2509
  # New-style hypervisor/backend parameters
2510

    
2511
  config.add_section(constants.INISECT_HYP)
2512
  for name, value in instance.hvparams.items():
2513
    if name not in constants.HVC_GLOBALS:
2514
      config.set(constants.INISECT_HYP, name, str(value))
2515

    
2516
  config.add_section(constants.INISECT_BEP)
2517
  for name, value in instance.beparams.items():
2518
    config.set(constants.INISECT_BEP, name, str(value))
2519

    
2520
  config.add_section(constants.INISECT_OSP)
2521
  for name, value in instance.osparams.items():
2522
    config.set(constants.INISECT_OSP, name, str(value))
2523

    
2524
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2525
                  data=config.Dumps())
2526
  shutil.rmtree(finaldestdir, ignore_errors=True)
2527
  shutil.move(destdir, finaldestdir)
2528

    
2529

    
2530
def ExportInfo(dest):
2531
  """Get export configuration information.
2532

2533
  @type dest: str
2534
  @param dest: directory containing the export
2535

2536
  @rtype: L{objects.SerializableConfigParser}
2537
  @return: a serializable config file containing the
2538
      export info
2539

2540
  """
2541
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2542

    
2543
  config = objects.SerializableConfigParser()
2544
  config.read(cff)
2545

    
2546
  if (not config.has_section(constants.INISECT_EXP) or
2547
      not config.has_section(constants.INISECT_INS)):
2548
    _Fail("Export info file doesn't have the required fields")
2549

    
2550
  return config.Dumps()
2551

    
2552

    
2553
def ListExports():
2554
  """Return a list of exports currently available on this machine.
2555

2556
  @rtype: list
2557
  @return: list of the exports
2558

2559
  """
2560
  if os.path.isdir(constants.EXPORT_DIR):
2561
    return sorted(utils.ListVisibleFiles(constants.EXPORT_DIR))
2562
  else:
2563
    _Fail("No exports directory")
2564

    
2565

    
2566
def RemoveExport(export):
2567
  """Remove an existing export from the node.
2568

2569
  @type export: str
2570
  @param export: the name of the export to remove
2571
  @rtype: None
2572

2573
  """
2574
  target = utils.PathJoin(constants.EXPORT_DIR, export)
2575

    
2576
  try:
2577
    shutil.rmtree(target)
2578
  except EnvironmentError, err:
2579
    _Fail("Error while removing the export: %s", err, exc=True)
2580

    
2581

    
2582
def BlockdevRename(devlist):
2583
  """Rename a list of block devices.
2584

2585
  @type devlist: list of tuples
2586
  @param devlist: list of tuples of the form  (disk,
2587
      new_logical_id, new_physical_id); disk is an
2588
      L{objects.Disk} object describing the current disk,
2589
      and new logical_id/physical_id is the name we
2590
      rename it to
2591
  @rtype: boolean
2592
  @return: True if all renames succeeded, False otherwise
2593

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

    
2622

    
2623
def _TransformFileStorageDir(fs_dir):
2624
  """Checks whether given file_storage_dir is valid.
2625

2626
  Checks wheter the given fs_dir is within the cluster-wide default
2627
  file_storage_dir or the shared_file_storage_dir, which are stored in
2628
  SimpleStore. Only paths under those directories are allowed.
2629

2630
  @type fs_dir: str
2631
  @param fs_dir: the path to check
2632

2633
  @return: the normalized path if valid, None otherwise
2634

2635
  """
2636
  if not constants.ENABLE_FILE_STORAGE:
2637
    _Fail("File storage disabled at configure time")
2638
  cfg = _GetConfig()
2639
  fs_dir = os.path.normpath(fs_dir)
2640
  base_fstore = cfg.GetFileStorageDir()
2641
  base_shared = cfg.GetSharedFileStorageDir()
2642
  if not (utils.IsBelowDir(base_fstore, fs_dir) or
2643
          utils.IsBelowDir(base_shared, fs_dir)):
2644
    _Fail("File storage directory '%s' is not under base file"
2645
          " storage directory '%s' or shared storage directory '%s'",
2646
          fs_dir, base_fstore, base_shared)
2647
  return fs_dir
2648

    
2649

    
2650
def CreateFileStorageDir(file_storage_dir):
2651
  """Create file storage directory.
2652

2653
  @type file_storage_dir: str
2654
  @param file_storage_dir: directory to create
2655

2656
  @rtype: tuple
2657
  @return: tuple with first element a boolean indicating wheter dir
2658
      creation was successful or not
2659

2660
  """
2661
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2662
  if os.path.exists(file_storage_dir):
2663
    if not os.path.isdir(file_storage_dir):
2664
      _Fail("Specified storage dir '%s' is not a directory",
2665
            file_storage_dir)
2666
  else:
2667
    try:
2668
      os.makedirs(file_storage_dir, 0750)
2669
    except OSError, err:
2670
      _Fail("Cannot create file storage directory '%s': %s",
2671
            file_storage_dir, err, exc=True)
2672

    
2673

    
2674
def RemoveFileStorageDir(file_storage_dir):
2675
  """Remove file storage directory.
2676

2677
  Remove it only if it's empty. If not log an error and return.
2678

2679
  @type file_storage_dir: str
2680
  @param file_storage_dir: the directory we should cleanup
2681
  @rtype: tuple (success,)
2682
  @return: tuple of one element, C{success}, denoting
2683
      whether the operation was successful
2684

2685
  """
2686
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2687
  if os.path.exists(file_storage_dir):
2688
    if not os.path.isdir(file_storage_dir):
2689
      _Fail("Specified Storage directory '%s' is not a directory",
2690
            file_storage_dir)
2691
    # deletes dir only if empty, otherwise we want to fail the rpc call
2692
    try:
2693
      os.rmdir(file_storage_dir)
2694
    except OSError, err:
2695
      _Fail("Cannot remove file storage directory '%s': %s",
2696
            file_storage_dir, err)
2697

    
2698

    
2699
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2700
  """Rename the file storage directory.
2701

2702
  @type old_file_storage_dir: str
2703
  @param old_file_storage_dir: the current path
2704
  @type new_file_storage_dir: str
2705
  @param new_file_storage_dir: the name we should rename to
2706
  @rtype: tuple (success,)
2707
  @return: tuple of one element, C{success}, denoting
2708
      whether the operation was successful
2709

2710
  """
2711
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2712
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2713
  if not os.path.exists(new_file_storage_dir):
2714
    if os.path.isdir(old_file_storage_dir):
2715
      try:
2716
        os.rename(old_file_storage_dir, new_file_storage_dir)
2717
      except OSError, err:
2718
        _Fail("Cannot rename '%s' to '%s': %s",
2719
              old_file_storage_dir, new_file_storage_dir, err)
2720
    else:
2721
      _Fail("Specified storage dir '%s' is not a directory",
2722
            old_file_storage_dir)
2723
  else:
2724
    if os.path.exists(old_file_storage_dir):
2725
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2726
            old_file_storage_dir, new_file_storage_dir)
2727

    
2728

    
2729
def _EnsureJobQueueFile(file_name):
2730
  """Checks whether the given filename is in the queue directory.
2731

2732
  @type file_name: str
2733
  @param file_name: the file name we should check
2734
  @rtype: None
2735
  @raises RPCFail: if the file is not valid
2736

2737
  """
2738
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2739
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2740

    
2741
  if not result:
2742
    _Fail("Passed job queue file '%s' does not belong to"
2743
          " the queue directory '%s'", file_name, queue_dir)
2744

    
2745

    
2746
def JobQueueUpdate(file_name, content):
2747
  """Updates a file in the queue directory.
2748

2749
  This is just a wrapper over L{utils.io.WriteFile}, with proper
2750
  checking.
2751

2752
  @type file_name: str
2753
  @param file_name: the job file name
2754
  @type content: str
2755
  @param content: the new job contents
2756
  @rtype: boolean
2757
  @return: the success of the operation
2758

2759
  """
2760
  _EnsureJobQueueFile(file_name)
2761
  getents = runtime.GetEnts()
2762

    
2763
  # Write and replace the file atomically
2764
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
2765
                  gid=getents.masterd_gid)
2766

    
2767

    
2768
def JobQueueRename(old, new):
2769
  """Renames a job queue file.
2770

2771
  This is just a wrapper over os.rename with proper checking.
2772

2773
  @type old: str
2774
  @param old: the old (actual) file name
2775
  @type new: str
2776
  @param new: the desired file name
2777
  @rtype: tuple
2778
  @return: the success of the operation and payload
2779

2780
  """
2781
  _EnsureJobQueueFile(old)
2782
  _EnsureJobQueueFile(new)
2783

    
2784
  getents = runtime.GetEnts()
2785

    
2786
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0700,
2787
                   dir_uid=getents.masterd_uid, dir_gid=getents.masterd_gid)
2788

    
2789

    
2790
def BlockdevClose(instance_name, disks):
2791
  """Closes the given block devices.
2792

2793
  This means they will be switched to secondary mode (in case of
2794
  DRBD).
2795

2796
  @param instance_name: if the argument is not empty, the symlinks
2797
      of this instance will be removed
2798
  @type disks: list of L{objects.Disk}
2799
  @param disks: the list of disks to be closed
2800
  @rtype: tuple (success, message)
2801
  @return: a tuple of success and message, where success
2802
      indicates the succes of the operation, and message
2803
      which will contain the error details in case we
2804
      failed
2805

2806
  """
2807
  bdevs = []
2808
  for cf in disks:
2809
    rd = _RecursiveFindBD(cf)
2810
    if rd is None:
2811
      _Fail("Can't find device %s", cf)
2812
    bdevs.append(rd)
2813

    
2814
  msg = []
2815
  for rd in bdevs:
2816
    try:
2817
      rd.Close()
2818
    except errors.BlockDeviceError, err:
2819
      msg.append(str(err))
2820
  if msg:
2821
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2822
  else:
2823
    if instance_name:
2824
      _RemoveBlockDevLinks(instance_name, disks)
2825

    
2826

    
2827
def ValidateHVParams(hvname, hvparams):
2828
  """Validates the given hypervisor parameters.
2829

2830
  @type hvname: string
2831
  @param hvname: the hypervisor name
2832
  @type hvparams: dict
2833
  @param hvparams: the hypervisor parameters to be validated
2834
  @rtype: None
2835

2836
  """
2837
  try:
2838
    hv_type = hypervisor.GetHypervisor(hvname)
2839
    hv_type.ValidateParameters(hvparams)
2840
  except errors.HypervisorError, err:
2841
    _Fail(str(err), log=False)
2842

    
2843

    
2844
def _CheckOSPList(os_obj, parameters):
2845
  """Check whether a list of parameters is supported by the OS.
2846

2847
  @type os_obj: L{objects.OS}
2848
  @param os_obj: OS object to check
2849
  @type parameters: list
2850
  @param parameters: the list of parameters to check
2851

2852
  """
2853
  supported = [v[0] for v in os_obj.supported_parameters]
2854
  delta = frozenset(parameters).difference(supported)
2855
  if delta:
2856
    _Fail("The following parameters are not supported"
2857
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
2858

    
2859

    
2860
def ValidateOS(required, osname, checks, osparams):
2861
  """Validate the given OS' parameters.
2862

2863
  @type required: boolean
2864
  @param required: whether absence of the OS should translate into
2865
      failure or not
2866
  @type osname: string
2867
  @param osname: the OS to be validated
2868
  @type checks: list
2869
  @param checks: list of the checks to run (currently only 'parameters')
2870
  @type osparams: dict
2871
  @param osparams: dictionary with OS parameters
2872
  @rtype: boolean
2873
  @return: True if the validation passed, or False if the OS was not
2874
      found and L{required} was false
2875

2876
  """
2877
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
2878
    _Fail("Unknown checks required for OS %s: %s", osname,
2879
          set(checks).difference(constants.OS_VALIDATE_CALLS))
2880

    
2881
  name_only = objects.OS.GetName(osname)
2882
  status, tbv = _TryOSFromDisk(name_only, None)
2883

    
2884
  if not status:
2885
    if required:
2886
      _Fail(tbv)
2887
    else:
2888
      return False
2889

    
2890
  if max(tbv.api_versions) < constants.OS_API_V20:
2891
    return True
2892

    
2893
  if constants.OS_VALIDATE_PARAMETERS in checks:
2894
    _CheckOSPList(tbv, osparams.keys())
2895

    
2896
  validate_env = OSCoreEnv(osname, tbv, osparams)
2897
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
2898
                        cwd=tbv.path, reset_env=True)
2899
  if result.failed:
2900
    logging.error("os validate command '%s' returned error: %s output: %s",
2901
                  result.cmd, result.fail_reason, result.output)
2902
    _Fail("OS validation script failed (%s), output: %s",
2903
          result.fail_reason, result.output, log=False)
2904

    
2905
  return True
2906

    
2907

    
2908
def DemoteFromMC():
2909
  """Demotes the current node from master candidate role.
2910

2911
  """
2912
  # try to ensure we're not the master by mistake
2913
  master, myself = ssconf.GetMasterAndMyself()
2914
  if master == myself:
2915
    _Fail("ssconf status shows I'm the master node, will not demote")
2916

    
2917
  result = utils.RunCmd([constants.DAEMON_UTIL, "check", constants.MASTERD])
2918
  if not result.failed:
2919
    _Fail("The master daemon is running, will not demote")
2920

    
2921
  try:
2922
    if os.path.isfile(constants.CLUSTER_CONF_FILE):
2923
      utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2924
  except EnvironmentError, err:
2925
    if err.errno != errno.ENOENT:
2926
      _Fail("Error while backing up cluster file: %s", err, exc=True)
2927

    
2928
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2929

    
2930

    
2931
def _GetX509Filenames(cryptodir, name):
2932
  """Returns the full paths for the private key and certificate.
2933

2934
  """
2935
  return (utils.PathJoin(cryptodir, name),
2936
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
2937
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
2938

    
2939

    
2940
def CreateX509Certificate(validity, cryptodir=constants.CRYPTO_KEYS_DIR):
2941
  """Creates a new X509 certificate for SSL/TLS.
2942

2943
  @type validity: int
2944
  @param validity: Validity in seconds
2945
  @rtype: tuple; (string, string)
2946
  @return: Certificate name and public part
2947

2948
  """
2949
  (key_pem, cert_pem) = \
2950
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
2951
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
2952

    
2953
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
2954
                              prefix="x509-%s-" % utils.TimestampForFilename())
2955
  try:
2956
    name = os.path.basename(cert_dir)
2957
    assert len(name) > 5
2958

    
2959
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2960

    
2961
    utils.WriteFile(key_file, mode=0400, data=key_pem)
2962
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
2963

    
2964
    # Never return private key as it shouldn't leave the node
2965
    return (name, cert_pem)
2966
  except Exception:
2967
    shutil.rmtree(cert_dir, ignore_errors=True)
2968
    raise
2969

    
2970

    
2971
def RemoveX509Certificate(name, cryptodir=constants.CRYPTO_KEYS_DIR):
2972
  """Removes a X509 certificate.
2973

2974
  @type name: string
2975
  @param name: Certificate name
2976

2977
  """
2978
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2979

    
2980
  utils.RemoveFile(key_file)
2981
  utils.RemoveFile(cert_file)
2982

    
2983
  try:
2984
    os.rmdir(cert_dir)
2985
  except EnvironmentError, err:
2986
    _Fail("Cannot remove certificate directory '%s': %s",
2987
          cert_dir, err)
2988

    
2989

    
2990
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
2991
  """Returns the command for the requested input/output.
2992

2993
  @type instance: L{objects.Instance}
2994
  @param instance: The instance object
2995
  @param mode: Import/export mode
2996
  @param ieio: Input/output type
2997
  @param ieargs: Input/output arguments
2998

2999
  """
3000
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3001

    
3002
  env = None
3003
  prefix = None
3004
  suffix = None
3005
  exp_size = None
3006

    
3007
  if ieio == constants.IEIO_FILE:
3008
    (filename, ) = ieargs
3009

    
3010
    if not utils.IsNormAbsPath(filename):
3011
      _Fail("Path '%s' is not normalized or absolute", filename)
3012

    
3013
    real_filename = os.path.realpath(filename)
3014
    directory = os.path.dirname(real_filename)
3015

    
3016
    if not utils.IsBelowDir(constants.EXPORT_DIR, real_filename):
3017
      _Fail("File '%s' is not under exports directory '%s': %s",
3018
            filename, constants.EXPORT_DIR, real_filename)
3019

    
3020
    # Create directory
3021
    utils.Makedirs(directory, mode=0750)
3022

    
3023
    quoted_filename = utils.ShellQuote(filename)
3024

    
3025
    if mode == constants.IEM_IMPORT:
3026
      suffix = "> %s" % quoted_filename
3027
    elif mode == constants.IEM_EXPORT:
3028
      suffix = "< %s" % quoted_filename
3029

    
3030
      # Retrieve file size
3031
      try:
3032
        st = os.stat(filename)
3033
      except EnvironmentError, err:
3034
        logging.error("Can't stat(2) %s: %s", filename, err)
3035
      else:
3036
        exp_size = utils.BytesToMebibyte(st.st_size)
3037

    
3038
  elif ieio == constants.IEIO_RAW_DISK:
3039
    (disk, ) = ieargs
3040

    
3041
    real_disk = _OpenRealBD(disk)
3042

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

    
3055
    elif mode == constants.IEM_EXPORT:
3056
      # the block size on the read dd is 1MiB to match our units
3057
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3058
                                   real_disk.dev_path,
3059
                                   str(1024 * 1024), # 1 MB
3060
                                   str(disk.size))
3061
      exp_size = disk.size
3062

    
3063
  elif ieio == constants.IEIO_SCRIPT:
3064
    (disk, disk_index, ) = ieargs
3065

    
3066
    assert isinstance(disk_index, (int, long))
3067

    
3068
    real_disk = _OpenRealBD(disk)
3069

    
3070
    inst_os = OSFromDisk(instance.os)
3071
    env = OSEnvironment(instance, inst_os)
3072

    
3073
    if mode == constants.IEM_IMPORT:
3074
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3075
      env["IMPORT_INDEX"] = str(disk_index)
3076
      script = inst_os.import_script
3077

    
3078
    elif mode == constants.IEM_EXPORT:
3079
      env["EXPORT_DEVICE"] = real_disk.dev_path
3080
      env["EXPORT_INDEX"] = str(disk_index)
3081
      script = inst_os.export_script
3082

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

    
3086
    if mode == constants.IEM_IMPORT:
3087
      suffix = "| %s" % script_cmd
3088

    
3089
    elif mode == constants.IEM_EXPORT:
3090
      prefix = "%s |" % script_cmd
3091

    
3092
    # Let script predict size
3093
    exp_size = constants.IE_CUSTOM_SIZE
3094

    
3095
  else:
3096
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3097

    
3098
  return (env, prefix, suffix, exp_size)
3099

    
3100

    
3101
def _CreateImportExportStatusDir(prefix):
3102
  """Creates status directory for import/export.
3103

3104
  """
3105
  return tempfile.mkdtemp(dir=constants.IMPORT_EXPORT_DIR,
3106
                          prefix=("%s-%s-" %
3107
                                  (prefix, utils.TimestampForFilename())))
3108

    
3109

    
3110
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3111
                            ieio, ieioargs):
3112
  """Starts an import or export daemon.
3113

3114
  @param mode: Import/output mode
3115
  @type opts: L{objects.ImportExportOptions}
3116
  @param opts: Daemon options
3117
  @type host: string
3118
  @param host: Remote host for export (None for import)
3119
  @type port: int
3120
  @param port: Remote port for export (None for import)
3121
  @type instance: L{objects.Instance}
3122
  @param instance: Instance object
3123
  @type component: string
3124
  @param component: which part of the instance is transferred now,
3125
      e.g. 'disk/0'
3126
  @param ieio: Input/output type
3127
  @param ieioargs: Input/output arguments
3128

3129
  """
3130
  if mode == constants.IEM_IMPORT:
3131
    prefix = "import"
3132

    
3133
    if not (host is None and port is None):
3134
      _Fail("Can not specify host or port on import")
3135

    
3136
  elif mode == constants.IEM_EXPORT:
3137
    prefix = "export"
3138

    
3139
    if host is None or port is None:
3140
      _Fail("Host and port must be specified for an export")
3141

    
3142
  else:
3143
    _Fail("Invalid mode %r", mode)
3144

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

    
3148
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3149
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3150

    
3151
  if opts.key_name is None:
3152
    # Use server.pem
3153
    key_path = constants.NODED_CERT_FILE
3154
    cert_path = constants.NODED_CERT_FILE
3155
    assert opts.ca_pem is None
3156
  else:
3157
    (_, key_path, cert_path) = _GetX509Filenames(constants.CRYPTO_KEYS_DIR,
3158
                                                 opts.key_name)
3159
    assert opts.ca_pem is not None
3160

    
3161
  for i in [key_path, cert_path]:
3162
    if not os.path.exists(i):
3163
      _Fail("File '%s' does not exist" % i)
3164

    
3165
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3166
  try:
3167
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3168
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3169
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3170

    
3171
    if opts.ca_pem is None:
3172
      # Use server.pem
3173
      ca = utils.ReadFile(constants.NODED_CERT_FILE)
3174
    else:
3175
      ca = opts.ca_pem
3176

    
3177
    # Write CA file
3178
    utils.WriteFile(ca_file, data=ca, mode=0400)
3179

    
3180
    cmd = [
3181
      constants.IMPORT_EXPORT_DAEMON,
3182
      status_file, mode,
3183
      "--key=%s" % key_path,
3184
      "--cert=%s" % cert_path,
3185
      "--ca=%s" % ca_file,
3186
      ]
3187

    
3188
    if host:
3189
      cmd.append("--host=%s" % host)
3190

    
3191
    if port:
3192
      cmd.append("--port=%s" % port)
3193

    
3194
    if opts.ipv6:
3195
      cmd.append("--ipv6")
3196
    else:
3197
      cmd.append("--ipv4")
3198

    
3199
    if opts.compress:
3200
      cmd.append("--compress=%s" % opts.compress)
3201

    
3202
    if opts.magic:
3203
      cmd.append("--magic=%s" % opts.magic)
3204

    
3205
    if exp_size is not None:
3206
      cmd.append("--expected-size=%s" % exp_size)
3207

    
3208
    if cmd_prefix:
3209
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3210

    
3211
    if cmd_suffix:
3212
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3213

    
3214
    if mode == constants.IEM_EXPORT:
3215
      # Retry connection a few times when connecting to remote peer
3216
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3217
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3218
    elif opts.connect_timeout is not None:
3219
      assert mode == constants.IEM_IMPORT
3220
      # Overall timeout for establishing connection while listening
3221
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3222

    
3223
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3224

    
3225
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3226
    # support for receiving a file descriptor for output
3227
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3228
                      output=logfile)
3229

    
3230
    # The import/export name is simply the status directory name
3231
    return os.path.basename(status_dir)
3232

    
3233
  except Exception:
3234
    shutil.rmtree(status_dir, ignore_errors=True)
3235
    raise
3236

    
3237

    
3238
def GetImportExportStatus(names):
3239
  """Returns import/export daemon status.
3240

3241
  @type names: sequence
3242
  @param names: List of names
3243
  @rtype: List of dicts
3244
  @return: Returns a list of the state of each named import/export or None if a
3245
           status couldn't be read
3246

3247
  """
3248
  result = []
3249

    
3250
  for name in names:
3251
    status_file = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name,
3252
                                 _IES_STATUS_FILE)
3253

    
3254
    try:
3255
      data = utils.ReadFile(status_file)
3256
    except EnvironmentError, err:
3257
      if err.errno != errno.ENOENT:
3258
        raise
3259
      data = None
3260

    
3261
    if not data:
3262
      result.append(None)
3263
      continue
3264

    
3265
    result.append(serializer.LoadJson(data))
3266

    
3267
  return result
3268

    
3269

    
3270
def AbortImportExport(name):
3271
  """Sends SIGTERM to a running import/export daemon.
3272

3273
  """
3274
  logging.info("Abort import/export %s", name)
3275

    
3276
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3277
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3278

    
3279
  if pid:
3280
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3281
                 name, pid)
3282
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3283

    
3284

    
3285
def CleanupImportExport(name):
3286
  """Cleanup after an import or export.
3287

3288
  If the import/export daemon is still running it's killed. Afterwards the
3289
  whole status directory is removed.
3290

3291
  """
3292
  logging.info("Finalizing import/export %s", name)
3293

    
3294
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3295

    
3296
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3297

    
3298
  if pid:
3299
    logging.info("Import/export %s is still running with PID %s",
3300
                 name, pid)
3301
    utils.KillProcess(pid, waitpid=False)
3302

    
3303
  shutil.rmtree(status_dir, ignore_errors=True)
3304

    
3305

    
3306
def _FindDisks(nodes_ip, disks):
3307
  """Sets the physical ID on disks and returns the block devices.
3308

3309
  """
3310
  # set the correct physical ID
3311
  my_name = netutils.Hostname.GetSysName()
3312
  for cf in disks:
3313
    cf.SetPhysicalID(my_name, nodes_ip)
3314

    
3315
  bdevs = []
3316

    
3317
  for cf in disks:
3318
    rd = _RecursiveFindBD(cf)
3319
    if rd is None:
3320
      _Fail("Can't find device %s", cf)
3321
    bdevs.append(rd)
3322
  return bdevs
3323

    
3324

    
3325
def DrbdDisconnectNet(nodes_ip, disks):
3326
  """Disconnects the network on a list of drbd devices.
3327

3328
  """
3329
  bdevs = _FindDisks(nodes_ip, disks)
3330

    
3331
  # disconnect disks
3332
  for rd in bdevs:
3333
    try:
3334
      rd.DisconnectNet()
3335
    except errors.BlockDeviceError, err:
3336
      _Fail("Can't change network configuration to standalone mode: %s",
3337
            err, exc=True)
3338

    
3339

    
3340
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3341
  """Attaches the network on a list of drbd devices.
3342

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

    
3346
  if multimaster:
3347
    for idx, rd in enumerate(bdevs):
3348
      try:
3349
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3350
      except EnvironmentError, err:
3351
        _Fail("Can't create symlink: %s", err)
3352
  # reconnect disks, switch to new master configuration and if
3353
  # needed primary mode
3354
  for rd in bdevs:
3355
    try:
3356
      rd.AttachNet(multimaster)
3357
    except errors.BlockDeviceError, err:
3358
      _Fail("Can't change network configuration: %s", err)
3359

    
3360
  # wait until the disks are connected; we need to retry the re-attach
3361
  # if the device becomes standalone, as this might happen if the one
3362
  # node disconnects and reconnects in a different mode before the
3363
  # other node reconnects; in this case, one or both of the nodes will
3364
  # decide it has wrong configuration and switch to standalone
3365

    
3366
  def _Attach():
3367
    all_connected = True
3368

    
3369
    for rd in bdevs:
3370
      stats = rd.GetProcStatus()
3371

    
3372
      all_connected = (all_connected and
3373
                       (stats.is_connected or stats.is_in_resync))
3374

    
3375
      if stats.is_standalone:
3376
        # peer had different config info and this node became
3377
        # standalone, even though this should not happen with the
3378
        # new staged way of changing disk configs
3379
        try:
3380
          rd.AttachNet(multimaster)
3381
        except errors.BlockDeviceError, err:
3382
          _Fail("Can't change network configuration: %s", err)
3383

    
3384
    if not all_connected:
3385
      raise utils.RetryAgain()
3386

    
3387
  try:
3388
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3389
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3390
  except utils.RetryTimeout:
3391
    _Fail("Timeout in disk reconnecting")
3392

    
3393
  if multimaster:
3394
    # change to primary mode
3395
    for rd in bdevs:
3396
      try:
3397
        rd.Open()
3398
      except errors.BlockDeviceError, err:
3399
        _Fail("Can't change to primary mode: %s", err)
3400

    
3401

    
3402
def DrbdWaitSync(nodes_ip, disks):
3403
  """Wait until DRBDs have synchronized.
3404

3405
  """
3406
  def _helper(rd):
3407
    stats = rd.GetProcStatus()
3408
    if not (stats.is_connected or stats.is_in_resync):
3409
      raise utils.RetryAgain()
3410
    return stats
3411

    
3412
  bdevs = _FindDisks(nodes_ip, disks)
3413

    
3414
  min_resync = 100
3415
  alldone = True
3416
  for rd in bdevs:
3417
    try:
3418
      # poll each second for 15 seconds
3419
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3420
    except utils.RetryTimeout:
3421
      stats = rd.GetProcStatus()
3422
      # last check
3423
      if not (stats.is_connected or stats.is_in_resync):
3424
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3425
    alldone = alldone and (not stats.is_in_resync)
3426
    if stats.sync_percent is not None:
3427
      min_resync = min(min_resync, stats.sync_percent)
3428

    
3429
  return (alldone, min_resync)
3430

    
3431

    
3432
def GetDrbdUsermodeHelper():
3433
  """Returns DRBD usermode helper currently configured.
3434

3435
  """
3436
  try:
3437
    return bdev.BaseDRBD.GetUsermodeHelper()
3438
  except errors.BlockDeviceError, err:
3439
    _Fail(str(err))
3440

    
3441

    
3442
def PowercycleNode(hypervisor_type):
3443
  """Hard-powercycle the node.
3444

3445
  Because we need to return first, and schedule the powercycle in the
3446
  background, we won't be able to report failures nicely.
3447

3448
  """
3449
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3450
  try:
3451
    pid = os.fork()
3452
  except OSError:
3453
    # if we can't fork, we'll pretend that we're in the child process
3454
    pid = 0
3455
  if pid > 0:
3456
    return "Reboot scheduled in 5 seconds"
3457
  # ensure the child is running on ram
3458
  try:
3459
    utils.Mlockall()
3460
  except Exception: # pylint: disable=W0703
3461
    pass
3462
  time.sleep(5)
3463
  hyper.PowercycleNode()
3464

    
3465

    
3466
class HooksRunner(object):
3467
  """Hook runner.
3468

3469
  This class is instantiated on the node side (ganeti-noded) and not
3470
  on the master side.
3471

3472
  """
3473
  def __init__(self, hooks_base_dir=None):
3474
    """Constructor for hooks runner.
3475

3476
    @type hooks_base_dir: str or None
3477
    @param hooks_base_dir: if not None, this overrides the
3478
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
3479

3480
    """
3481
    if hooks_base_dir is None:
3482
      hooks_base_dir = constants.HOOKS_BASE_DIR
3483
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3484
    # constant
3485
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
3486

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

3490
    """
3491
    assert len(node_list) == 1
3492
    node = node_list[0]
3493
    _, myself = ssconf.GetMasterAndMyself()
3494
    assert node == myself
3495

    
3496
    results = self.RunHooks(hpath, phase, env)
3497

    
3498
    # Return values in the form expected by HooksMaster
3499
    return {node: (None, False, results)}
3500

    
3501
  def RunHooks(self, hpath, phase, env):
3502
    """Run the scripts in the hooks directory.
3503

3504
    @type hpath: str
3505
    @param hpath: the path to the hooks directory which
3506
        holds the scripts
3507
    @type phase: str
3508
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
3509
        L{constants.HOOKS_PHASE_POST}
3510
    @type env: dict
3511
    @param env: dictionary with the environment for the hook
3512
    @rtype: list
3513
    @return: list of 3-element tuples:
3514
      - script path
3515
      - script result, either L{constants.HKR_SUCCESS} or
3516
        L{constants.HKR_FAIL}
3517
      - output of the script
3518

3519
    @raise errors.ProgrammerError: for invalid input
3520
        parameters
3521

3522
    """
3523
    if phase == constants.HOOKS_PHASE_PRE:
3524
      suffix = "pre"
3525
    elif phase == constants.HOOKS_PHASE_POST:
3526
      suffix = "post"
3527
    else:
3528
      _Fail("Unknown hooks phase '%s'", phase)
3529

    
3530
    subdir = "%s-%s.d" % (hpath, suffix)
3531
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3532

    
3533
    results = []
3534

    
3535
    if not os.path.isdir(dir_name):
3536
      # for non-existing/non-dirs, we simply exit instead of logging a
3537
      # warning at every operation
3538
      return results
3539

    
3540
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3541

    
3542
    for (relname, relstatus, runresult)  in runparts_results:
3543
      if relstatus == constants.RUNPARTS_SKIP:
3544
        rrval = constants.HKR_SKIP
3545
        output = ""
3546
      elif relstatus == constants.RUNPARTS_ERR:
3547
        rrval = constants.HKR_FAIL
3548
        output = "Hook script execution error: %s" % runresult
3549
      elif relstatus == constants.RUNPARTS_RUN:
3550
        if runresult.failed:
3551
          rrval = constants.HKR_FAIL
3552
        else:
3553
          rrval = constants.HKR_SUCCESS
3554
        output = utils.SafeEncode(runresult.output.strip())
3555
      results.append(("%s/%s" % (subdir, relname), rrval, output))
3556

    
3557
    return results
3558

    
3559

    
3560
class IAllocatorRunner(object):
3561
  """IAllocator runner.
3562

3563
  This class is instantiated on the node side (ganeti-noded) and not on
3564
  the master side.
3565

3566
  """
3567
  @staticmethod
3568
  def Run(name, idata):
3569
    """Run an iallocator script.
3570

3571
    @type name: str
3572
    @param name: the iallocator script name
3573
    @type idata: str
3574
    @param idata: the allocator input data
3575

3576
    @rtype: tuple
3577
    @return: two element tuple of:
3578
       - status
3579
       - either error message or stdout of allocator (for success)
3580

3581
    """
3582
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
3583
                                  os.path.isfile)
3584
    if alloc_script is None:
3585
      _Fail("iallocator module '%s' not found in the search path", name)
3586

    
3587
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
3588
    try:
3589
      os.write(fd, idata)
3590
      os.close(fd)
3591
      result = utils.RunCmd([alloc_script, fin_name])
3592
      if result.failed:
3593
        _Fail("iallocator module '%s' failed: %s, output '%s'",
3594
              name, result.fail_reason, result.output)
3595
    finally:
3596
      os.unlink(fin_name)
3597

    
3598
    return result.stdout
3599

    
3600

    
3601
class DevCacheManager(object):
3602
  """Simple class for managing a cache of block device information.
3603

3604
  """
3605
  _DEV_PREFIX = "/dev/"
3606
  _ROOT_DIR = constants.BDEV_CACHE_DIR
3607

    
3608
  @classmethod
3609
  def _ConvertPath(cls, dev_path):
3610
    """Converts a /dev/name path to the cache file name.
3611

3612
    This replaces slashes with underscores and strips the /dev
3613
    prefix. It then returns the full path to the cache file.
3614

3615
    @type dev_path: str
3616
    @param dev_path: the C{/dev/} path name
3617
    @rtype: str
3618
    @return: the converted path name
3619

3620
    """
3621
    if dev_path.startswith(cls._DEV_PREFIX):
3622
      dev_path = dev_path[len(cls._DEV_PREFIX):]
3623
    dev_path = dev_path.replace("/", "_")
3624
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
3625
    return fpath
3626

    
3627
  @classmethod
3628
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
3629
    """Updates the cache information for a given device.
3630

3631
    @type dev_path: str
3632
    @param dev_path: the pathname of the device
3633
    @type owner: str
3634
    @param owner: the owner (instance name) of the device
3635
    @type on_primary: bool
3636
    @param on_primary: whether this is the primary
3637
        node nor not
3638
    @type iv_name: str
3639
    @param iv_name: the instance-visible name of the
3640
        device, as in objects.Disk.iv_name
3641

3642
    @rtype: None
3643

3644
    """
3645
    if dev_path is None:
3646
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
3647
      return
3648
    fpath = cls._ConvertPath(dev_path)
3649
    if on_primary:
3650
      state = "primary"
3651
    else:
3652
      state = "secondary"
3653
    if iv_name is None:
3654
      iv_name = "not_visible"
3655
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
3656
    try:
3657
      utils.WriteFile(fpath, data=fdata)
3658
    except EnvironmentError, err:
3659
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
3660

    
3661
  @classmethod
3662
  def RemoveCache(cls, dev_path):
3663
    """Remove data for a dev_path.
3664

3665
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
3666
    path name and logging.
3667

3668
    @type dev_path: str
3669
    @param dev_path: the pathname of the device
3670

3671
    @rtype: None
3672

3673
    """
3674
    if dev_path is None:
3675
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
3676
      return
3677
    fpath = cls._ConvertPath(dev_path)
3678
    try:
3679
      utils.RemoveFile(fpath)
3680
    except EnvironmentError, err:
3681
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)