Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 41e079ce

History | View | Annotate | Download (111 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 _BuildMasterIpHookEnv():
287
  """Builds environment variables for master IP hooks.
288

289
  """
290
  cfg = _GetConfig()
291
  env = {
292
    "MASTER_NETDEV": cfg.GetMasterNetdev(),
293
    "MASTER_IP": cfg.GetMasterIP(),
294
  }
295

    
296
  return env
297

    
298

    
299
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNUP, "master-ip-turnup",
300
               _BuildMasterIpHookEnv)
301
def ActivateMasterIp(master_ip, master_netmask, master_netdev, family):
302
  """Activate the IP address of the master daemon.
303

304
  @param master_ip: the master IP
305
  @param master_netmask: the master IP netmask
306
  @param master_netdev: the master network device
307
  @param family: the IP family
308

309
  """
310
  # GetMasterInfo will raise an exception if not able to return data
311
  master_netdev, master_ip, _, family, master_netmask = GetMasterInfo()
312

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

    
324
    result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
325
                           "%s/%s" % (master_ip, master_netmask),
326
                           "dev", master_netdev, "label",
327
                           "%s:0" % master_netdev])
328
    if result.failed:
329
      err_msg = "Can't activate master IP: %s" % result.output
330
      logging.error(err_msg)
331

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

    
344
  if err_msg:
345
    _Fail(err_msg)
346

    
347

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

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

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

358
  """
359

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

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

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

    
375

    
376
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNDOWN, "master-ip-turndown",
377
               _BuildMasterIpHookEnv)
378
def DeactivateMasterIp(master_ip, master_netmask, master_netdev):
379
  """Deactivate the master IP on this node.
380

381
  @param master_ip: the master IP
382
  @param master_netmask: the master IP netmask
383
  @param master_netdev: the master network device
384

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

    
389
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
390
                         "%s/%s" % (master_ip, master_netmask),
391
                         "dev", master_netdev])
392
  if result.failed:
393
    logging.error("Can't remove the master IP, error: %s", result.output)
394
    # but otherwise ignore the failure
395

    
396

    
397
def StopMasterDaemons():
398
  """Stop the master daemons on this node.
399

400
  Stop the master daemons (ganeti-masterd and ganeti-rapi) on this node.
401

402
  @rtype: None
403

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

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

    
414

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

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

423
  """
424
  if old_netmask == netmask:
425
    return
426

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

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

    
441

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

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

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

    
463

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

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

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

474
  @param modify_ssh_setup: boolean
475

476
  """
477
  _CleanDirectory(constants.DATA_DIR)
478
  _CleanDirectory(constants.CRYPTO_KEYS_DIR)
479
  JobQueuePurge()
480

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

    
485
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
486

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

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

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

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

    
509

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

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

527
  """
528
  outputarray = {}
529

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

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

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

    
547
  return outputarray
548

    
549

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

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

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

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

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

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

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

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

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

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

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

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

    
615
    # Use a random order
616
    random.shuffle(nodes)
617

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

    
625
    result[constants.NV_NODELIST] = val
626

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
750

    
751
def GetBlockDevSizes(devices):
752
  """Return the size of the given block devices
753

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

761
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
762

763
  """
764
  DEV_PREFIX = "/dev/"
765
  blockdevs = {}
766

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

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

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

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

    
788

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

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

800
        {'xenvg/test1': ('20.06', True, True)}
801

802
      in case of errors, a string is returned with the error
803
      details.
804

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

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

    
832
  return lvs
833

    
834

    
835
def ListVolumeGroups():
836
  """List the volume groups and their size.
837

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

842
  """
843
  return utils.ListVolumeGroups()
844

    
845

    
846
def NodeVolumes():
847
  """List all volumes on this node.
848

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

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

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

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

    
872
  def parse_dev(dev):
873
    return dev.split("(")[0]
874

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

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

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

    
891

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

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

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

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

    
907

    
908
def GetInstanceList(hypervisor_list):
909
  """Provides a list of instances.
910

911
  @type hypervisor_list: list
912
  @param hypervisor_list: the list of hypervisors to query information
913

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

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

    
929
  return results
930

    
931

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

935
  @type instance: string
936
  @param instance: the instance name
937
  @type hname: string
938
  @param hname: the hypervisor type of the instance
939

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

946
  """
947
  output = {}
948

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

    
955
  return output
956

    
957

    
958
def GetInstanceMigratable(instance):
959
  """Gives whether an instance can be migrated.
960

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

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

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

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

    
981

    
982
def GetAllInstancesInfo(hypervisor_list):
983
  """Gather data about all instances.
984

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

989
  @type hypervisor_list: list
990
  @param hypervisor_list: list of hypervisors to query for instance data
991

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

999
  """
1000
  output = {}
1001

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

    
1022
  return output
1023

    
1024

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

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

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

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

    
1052

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

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

1064
  """
1065
  inst_os = OSFromDisk(instance.os)
1066

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

    
1071
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1072

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

    
1084

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

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

1097
  """
1098
  inst_os = OSFromDisk(instance.os)
1099

    
1100
  rename_env = OSEnvironment(instance, inst_os, debug)
1101
  rename_env["OLD_INSTANCE_NAME"] = old_name
1102

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

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

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

    
1117

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

    
1122

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

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

1129

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

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

    
1148
  return link_name
1149

    
1150

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

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

    
1163

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

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

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

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

    
1189
    block_devices.append((disk, link_name))
1190

    
1191
  return block_devices
1192

    
1193

    
1194
def StartInstance(instance, startup_paused):
1195
  """Start an instance.
1196

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

1203
  """
1204
  running_instances = GetInstanceList([instance.hypervisor])
1205

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

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

    
1220

    
1221
def InstanceShutdown(instance, timeout):
1222
  """Shut an instance down.
1223

1224
  @note: this functions uses polling with a hardcoded timeout.
1225

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

1232
  """
1233
  hv_name = instance.hypervisor
1234
  hyper = hypervisor.GetHypervisor(hv_name)
1235
  iname = instance.name
1236

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

    
1241
  class _TryShutdown:
1242
    def __init__(self):
1243
      self.tried_once = False
1244

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

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

    
1257
        _Fail("Failed to stop instance %s: %s", iname, err)
1258

    
1259
      self.tried_once = True
1260

    
1261
      raise utils.RetryAgain()
1262

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

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

    
1277
    time.sleep(1)
1278

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

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

    
1287
  _RemoveBlockDevLinks(iname, instance.disks)
1288

    
1289

    
1290
def InstanceReboot(instance, reboot_type, shutdown_timeout):
1291
  """Reboot an instance.
1292

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

1310
  """
1311
  running_instances = GetInstanceList([instance.hypervisor])
1312

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

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

    
1331

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

1335
  @type instance: L{objects.Instance}
1336
  @param instance: the instance definition
1337

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

    
1346

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

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

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

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

    
1375

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

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

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

    
1393

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

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

1406
  """
1407
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1408

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

    
1414

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

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

1426
  """
1427
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1428

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

    
1435

    
1436
def GetMigrationStatus(instance):
1437
  """Get the migration status
1438

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

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

    
1454

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

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

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

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

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

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

    
1514
  device.SetInfo(info)
1515

    
1516
  return device.unique_id
1517

    
1518

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

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

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

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

    
1536

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

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

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

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

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

    
1562
  _WipeDevice(rdev.dev_path, offset, size)
1563

    
1564

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

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

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

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

    
1586
    result = rdev.PauseResumeSync(pause)
1587

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

    
1597
  return success
1598

    
1599

    
1600
def BlockdevRemove(disk):
1601
  """Remove a block device.
1602

1603
  @note: This is intended to be called recursively.
1604

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

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

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

    
1634
  if msgs:
1635
    _Fail("; ".join(msgs))
1636

    
1637

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

1641
  This is run on the primary and secondary nodes for an instance.
1642

1643
  @note: this function is called recursively.
1644

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

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

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

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

    
1687
  else:
1688
    result = True
1689
  return result
1690

    
1691

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

1695
  This is a wrapper over _RecursiveAssembleBD.
1696

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

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

    
1714
  return result
1715

    
1716

    
1717
def BlockdevShutdown(disk):
1718
  """Shut down a block device.
1719

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

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

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

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

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

    
1751
  if msgs:
1752
    _Fail("; ".join(msgs))
1753

    
1754

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

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

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

    
1773

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

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

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

    
1802

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

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

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

    
1820
    stats.append(rbd.CombinedSyncStatus())
1821

    
1822
  return stats
1823

    
1824

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

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

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

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

    
1851
  assert len(disks) == len(result)
1852

    
1853
  return result
1854

    
1855

    
1856
def _RecursiveFindBD(disk):
1857
  """Check if a device is activated.
1858

1859
  If so, return information about the real device.
1860

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

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

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

    
1873
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1874

    
1875

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

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

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

    
1887
  real_disk.Open()
1888

    
1889
  return real_disk
1890

    
1891

    
1892
def BlockdevFind(disk):
1893
  """Check if a device is activated.
1894

1895
  If it is, return information about the real device.
1896

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

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

    
1909
  if rbd is None:
1910
    return None
1911

    
1912
  return rbd.GetSyncStatus()
1913

    
1914

    
1915
def BlockdevGetsize(disks):
1916
  """Computes the size of the given disks.
1917

1918
  If a disk is not found, returns None instead.
1919

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

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

    
1940

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

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

1954
  """
1955
  real_disk = _OpenRealBD(disk)
1956

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

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

    
1971
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1972
                                                   constants.GANETI_RUNAS,
1973
                                                   destcmd)
1974

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

    
1978
  result = utils.RunCmd(["bash", "-c", command])
1979

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

    
1984

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

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

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

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

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

    
2015
  raw_data = _Decompress(data)
2016

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

    
2020
  getents = runtime.GetEnts()
2021
  uid = getents.LookupUser(uid)
2022
  gid = getents.LookupGroup(gid)
2023

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

    
2028

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

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

2037
  @return: stdout
2038
  @raise RPCFail: If execution fails for some reason
2039

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

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

    
2047
  return result.stdout
2048

    
2049

    
2050
def WriteSsconfFiles(values):
2051
  """Update all ssconf files.
2052

2053
  Wrapper around the SimpleStore.WriteFiles.
2054

2055
  """
2056
  ssconf.SimpleStore().WriteFiles(values)
2057

    
2058

    
2059
def _ErrnoOrStr(err):
2060
  """Format an EnvironmentError exception.
2061

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

2066
  @type err: L{EnvironmentError}
2067
  @param err: the exception to format
2068

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

    
2076

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

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

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

2089
  """
2090
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2091

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

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

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

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

    
2114
  return True, api_versions
2115

    
2116

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

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

2136
  """
2137
  if top_dirs is None:
2138
    top_dirs = constants.OS_SEARCH_PATH
2139

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

    
2162
  return result
2163

    
2164

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2263

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

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

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

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

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

    
2285
  if not status:
2286
    _Fail(payload)
2287

    
2288
  return payload
2289

    
2290

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

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

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

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

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

    
2328
  return result
2329

    
2330

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

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

2345
  """
2346
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2347

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

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

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

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

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

    
2390
  return result
2391

    
2392

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

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

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

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

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

    
2420

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

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

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

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

    
2450

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

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

2461
  @rtype: None
2462

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

    
2467
  config = objects.SerializableConfigParser()
2468

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

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

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

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

    
2509
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2510

    
2511
  # New-style hypervisor/backend parameters
2512

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

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

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

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

    
2531

    
2532
def ExportInfo(dest):
2533
  """Get export configuration information.
2534

2535
  @type dest: str
2536
  @param dest: directory containing the export
2537

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

2542
  """
2543
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2544

    
2545
  config = objects.SerializableConfigParser()
2546
  config.read(cff)
2547

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

    
2552
  return config.Dumps()
2553

    
2554

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

2558
  @rtype: list
2559
  @return: list of the exports
2560

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

    
2567

    
2568
def RemoveExport(export):
2569
  """Remove an existing export from the node.
2570

2571
  @type export: str
2572
  @param export: the name of the export to remove
2573
  @rtype: None
2574

2575
  """
2576
  target = utils.PathJoin(constants.EXPORT_DIR, export)
2577

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

    
2583

    
2584
def BlockdevRename(devlist):
2585
  """Rename a list of block devices.
2586

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

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

    
2624

    
2625
def _TransformFileStorageDir(fs_dir):
2626
  """Checks whether given file_storage_dir is valid.
2627

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

2632
  @type fs_dir: str
2633
  @param fs_dir: the path to check
2634

2635
  @return: the normalized path if valid, None otherwise
2636

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

    
2651

    
2652
def CreateFileStorageDir(file_storage_dir):
2653
  """Create file storage directory.
2654

2655
  @type file_storage_dir: str
2656
  @param file_storage_dir: directory to create
2657

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

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

    
2675

    
2676
def RemoveFileStorageDir(file_storage_dir):
2677
  """Remove file storage directory.
2678

2679
  Remove it only if it's empty. If not log an error and return.
2680

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

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

    
2700

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

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

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

    
2730

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

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

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

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

    
2747

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

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

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

2761
  """
2762
  _EnsureJobQueueFile(file_name)
2763
  getents = runtime.GetEnts()
2764

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

    
2769

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

2773
  This is just a wrapper over os.rename with proper checking.
2774

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

2782
  """
2783
  _EnsureJobQueueFile(old)
2784
  _EnsureJobQueueFile(new)
2785

    
2786
  getents = runtime.GetEnts()
2787

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

    
2791

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

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

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

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

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

    
2828

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

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

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

    
2845

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

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

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

    
2861

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

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

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

    
2883
  name_only = objects.OS.GetName(osname)
2884
  status, tbv = _TryOSFromDisk(name_only, None)
2885

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

    
2892
  if max(tbv.api_versions) < constants.OS_API_V20:
2893
    return True
2894

    
2895
  if constants.OS_VALIDATE_PARAMETERS in checks:
2896
    _CheckOSPList(tbv, osparams.keys())
2897

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

    
2907
  return True
2908

    
2909

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

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

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

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

    
2930
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2931

    
2932

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

2936
  """
2937
  return (utils.PathJoin(cryptodir, name),
2938
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
2939
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
2940

    
2941

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

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

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

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

    
2961
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2962

    
2963
    utils.WriteFile(key_file, mode=0400, data=key_pem)
2964
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
2965

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

    
2972

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

2976
  @type name: string
2977
  @param name: Certificate name
2978

2979
  """
2980
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2981

    
2982
  utils.RemoveFile(key_file)
2983
  utils.RemoveFile(cert_file)
2984

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

    
2991

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

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

3001
  """
3002
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3003

    
3004
  env = None
3005
  prefix = None
3006
  suffix = None
3007
  exp_size = None
3008

    
3009
  if ieio == constants.IEIO_FILE:
3010
    (filename, ) = ieargs
3011

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

    
3015
    real_filename = os.path.realpath(filename)
3016
    directory = os.path.dirname(real_filename)
3017

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

    
3022
    # Create directory
3023
    utils.Makedirs(directory, mode=0750)
3024

    
3025
    quoted_filename = utils.ShellQuote(filename)
3026

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

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

    
3040
  elif ieio == constants.IEIO_RAW_DISK:
3041
    (disk, ) = ieargs
3042

    
3043
    real_disk = _OpenRealBD(disk)
3044

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

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

    
3065
  elif ieio == constants.IEIO_SCRIPT:
3066
    (disk, disk_index, ) = ieargs
3067

    
3068
    assert isinstance(disk_index, (int, long))
3069

    
3070
    real_disk = _OpenRealBD(disk)
3071

    
3072
    inst_os = OSFromDisk(instance.os)
3073
    env = OSEnvironment(instance, inst_os)
3074

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

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

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

    
3088
    if mode == constants.IEM_IMPORT:
3089
      suffix = "| %s" % script_cmd
3090

    
3091
    elif mode == constants.IEM_EXPORT:
3092
      prefix = "%s |" % script_cmd
3093

    
3094
    # Let script predict size
3095
    exp_size = constants.IE_CUSTOM_SIZE
3096

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

    
3100
  return (env, prefix, suffix, exp_size)
3101

    
3102

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

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

    
3111

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

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

3131
  """
3132
  if mode == constants.IEM_IMPORT:
3133
    prefix = "import"
3134

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

    
3138
  elif mode == constants.IEM_EXPORT:
3139
    prefix = "export"
3140

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

    
3144
  else:
3145
    _Fail("Invalid mode %r", mode)
3146

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

    
3150
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3151
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3152

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

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

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

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

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

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

    
3190
    if host:
3191
      cmd.append("--host=%s" % host)
3192

    
3193
    if port:
3194
      cmd.append("--port=%s" % port)
3195

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

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

    
3204
    if opts.magic:
3205
      cmd.append("--magic=%s" % opts.magic)
3206

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

    
3210
    if cmd_prefix:
3211
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3212

    
3213
    if cmd_suffix:
3214
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3215

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

    
3225
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3226

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

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

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

    
3239

    
3240
def GetImportExportStatus(names):
3241
  """Returns import/export daemon status.
3242

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

3249
  """
3250
  result = []
3251

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

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

    
3263
    if not data:
3264
      result.append(None)
3265
      continue
3266

    
3267
    result.append(serializer.LoadJson(data))
3268

    
3269
  return result
3270

    
3271

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

3275
  """
3276
  logging.info("Abort import/export %s", name)
3277

    
3278
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3279
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3280

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

    
3286

    
3287
def CleanupImportExport(name):
3288
  """Cleanup after an import or export.
3289

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

3293
  """
3294
  logging.info("Finalizing import/export %s", name)
3295

    
3296
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3297

    
3298
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3299

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

    
3305
  shutil.rmtree(status_dir, ignore_errors=True)
3306

    
3307

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

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

    
3317
  bdevs = []
3318

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

    
3326

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

3330
  """
3331
  bdevs = _FindDisks(nodes_ip, disks)
3332

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

    
3341

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

3345
  """
3346
  bdevs = _FindDisks(nodes_ip, disks)
3347

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

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

    
3368
  def _Attach():
3369
    all_connected = True
3370

    
3371
    for rd in bdevs:
3372
      stats = rd.GetProcStatus()
3373

    
3374
      all_connected = (all_connected and
3375
                       (stats.is_connected or stats.is_in_resync))
3376

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

    
3386
    if not all_connected:
3387
      raise utils.RetryAgain()
3388

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

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

    
3403

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

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

    
3414
  bdevs = _FindDisks(nodes_ip, disks)
3415

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

    
3431
  return (alldone, min_resync)
3432

    
3433

    
3434
def GetDrbdUsermodeHelper():
3435
  """Returns DRBD usermode helper currently configured.
3436

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

    
3443

    
3444
def PowercycleNode(hypervisor_type):
3445
  """Hard-powercycle the node.
3446

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

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

    
3467

    
3468
class HooksRunner(object):
3469
  """Hook runner.
3470

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

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

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

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

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

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

    
3498
    results = self.RunHooks(hpath, phase, env)
3499

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

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

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

3521
    @raise errors.ProgrammerError: for invalid input
3522
        parameters
3523

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

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

    
3535
    results = []
3536

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

    
3542
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3543

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

    
3559
    return results
3560

    
3561

    
3562
class IAllocatorRunner(object):
3563
  """IAllocator runner.
3564

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

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

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

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

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

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

    
3600
    return result.stdout
3601

    
3602

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

3606
  """
3607
  _DEV_PREFIX = "/dev/"
3608
  _ROOT_DIR = constants.BDEV_CACHE_DIR
3609

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

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

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

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

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

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

3644
    @rtype: None
3645

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

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

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

3670
    @type dev_path: str
3671
    @param dev_path: the pathname of the device
3672

3673
    @rtype: None
3674

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