Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 8da2bd43

History | View | Annotate | Download (110.8 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():
379
  """Deactivate the master IP on this node.
380

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

    
385
  # GetMasterInfo will raise an exception if not able to return data
386
  master_netdev, master_ip, _, _, master_netmask = GetMasterInfo()
387

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

    
395

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

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

401
  @rtype: None
402

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

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

    
413

    
414
def ChangeMasterNetmask(netmask):
415
  """Change the netmask of the master IP.
416

417
  """
418
  master_netdev, master_ip, _, _, old_netmask = GetMasterInfo()
419
  if old_netmask == netmask:
420
    return
421

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

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

    
436

    
437
def EtcHostsModify(mode, host, ip):
438
  """Modify a host entry in /etc/hosts.
439

440
  @param mode: The mode to operate. Either add or remove entry
441
  @param host: The host to operate on
442
  @param ip: The ip associated with the entry
443

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

    
458

    
459
def LeaveCluster(modify_ssh_setup):
460
  """Cleans up and remove the current node.
461

462
  This function cleans up and prepares the current node to be removed
463
  from the cluster.
464

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

469
  @param modify_ssh_setup: boolean
470

471
  """
472
  _CleanDirectory(constants.DATA_DIR)
473
  _CleanDirectory(constants.CRYPTO_KEYS_DIR)
474
  JobQueuePurge()
475

    
476
  if modify_ssh_setup:
477
    try:
478
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
479

    
480
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
481

    
482
      utils.RemoveFile(priv_key)
483
      utils.RemoveFile(pub_key)
484
    except errors.OpExecError:
485
      logging.exception("Error while processing ssh files")
486

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

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

    
501
  # Raise a custom exception (handled in ganeti-noded)
502
  raise errors.QuitGanetiException(True, "Shutdown scheduled")
503

    
504

    
505
def GetNodeInfo(vgname, hypervisor_type):
506
  """Gives back a hash with different information about the node.
507

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

522
  """
523
  outputarray = {}
524

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

    
534
  if hypervisor_type is not None:
535
    hyper = hypervisor.GetHypervisor(hypervisor_type)
536
    hyp_info = hyper.GetNodeInfo()
537
    if hyp_info is not None:
538
      outputarray.update(hyp_info)
539

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

    
542
  return outputarray
543

    
544

    
545
def VerifyNode(what, cluster_name):
546
  """Verify the status of the local node.
547

548
  Based on the input L{what} parameter, various checks are done on the
549
  local node.
550

551
  If the I{filelist} key is present, this list of
552
  files is checksummed and the file/checksum pairs are returned.
553

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

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

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

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

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

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

    
597
  if constants.NV_FILELIST in what:
598
    result[constants.NV_FILELIST] = utils.FingerprintFiles(
599
      what[constants.NV_FILELIST])
600

    
601
  if constants.NV_NODELIST in what:
602
    (nodes, bynode) = what[constants.NV_NODELIST]
603

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

    
610
    # Use a random order
611
    random.shuffle(nodes)
612

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

    
620
    result[constants.NV_NODELIST] = val
621

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

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

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

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

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

    
687
  if constants.NV_VGLIST in what and vm_capable:
688
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
689

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

    
695
  if constants.NV_VERSION in what:
696
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
697
                                    constants.RELEASE_VERSION)
698

    
699
  if constants.NV_HVINFO in what and vm_capable:
700
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
701
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
702

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

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

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

    
733
  if constants.NV_TIME in what:
734
    result[constants.NV_TIME] = utils.SplitTime(time.time())
735

    
736
  if constants.NV_OSLIST in what and vm_capable:
737
    result[constants.NV_OSLIST] = DiagnoseOS()
738

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

    
745

    
746
def GetBlockDevSizes(devices):
747
  """Return the size of the given block devices
748

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

756
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
757

758
  """
759
  DEV_PREFIX = "/dev/"
760
  blockdevs = {}
761

    
762
  for devpath in devices:
763
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
764
      continue
765

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

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

    
779
      size = int(result.stdout) / (1024 * 1024)
780
      blockdevs[devpath] = size
781
  return blockdevs
782

    
783

    
784
def GetVolumeList(vg_names):
785
  """Compute list of logical volumes and their size.
786

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

795
        {'xenvg/test1': ('20.06', True, True)}
796

797
      in case of errors, a string is returned with the error
798
      details.
799

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

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

    
827
  return lvs
828

    
829

    
830
def ListVolumeGroups():
831
  """List the volume groups and their size.
832

833
  @rtype: dict
834
  @return: dictionary with keys volume name and values the
835
      size of the volume
836

837
  """
838
  return utils.ListVolumeGroups()
839

    
840

    
841
def NodeVolumes():
842
  """List all volumes on this node.
843

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

852
    In case of errors, we return an empty list and log the
853
    error.
854

855
    Note that since a logical volume can live on multiple physical
856
    volumes, the resulting list might include a logical volume
857
    multiple times.
858

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

    
867
  def parse_dev(dev):
868
    return dev.split("(")[0]
869

    
870
  def handle_dev(dev):
871
    return [parse_dev(x) for x in dev.split(",")]
872

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

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

    
886

    
887
def BridgesExist(bridges_list):
888
  """Check if a list of bridges exist on the current node.
889

890
  @rtype: boolean
891
  @return: C{True} if all of them exist, C{False} otherwise
892

893
  """
894
  missing = []
895
  for bridge in bridges_list:
896
    if not utils.BridgeExists(bridge):
897
      missing.append(bridge)
898

    
899
  if missing:
900
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
901

    
902

    
903
def GetInstanceList(hypervisor_list):
904
  """Provides a list of instances.
905

906
  @type hypervisor_list: list
907
  @param hypervisor_list: the list of hypervisors to query information
908

909
  @rtype: list
910
  @return: a list of all running instances on the current node
911
    - instance1.example.com
912
    - instance2.example.com
913

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

    
924
  return results
925

    
926

    
927
def GetInstanceInfo(instance, hname):
928
  """Gives back the information about an instance as a dictionary.
929

930
  @type instance: string
931
  @param instance: the instance name
932
  @type hname: string
933
  @param hname: the hypervisor type of the instance
934

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

941
  """
942
  output = {}
943

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

    
950
  return output
951

    
952

    
953
def GetInstanceMigratable(instance):
954
  """Gives whether an instance can be migrated.
955

956
  @type instance: L{objects.Instance}
957
  @param instance: object representing the instance to be checked.
958

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

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

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

    
976

    
977
def GetAllInstancesInfo(hypervisor_list):
978
  """Gather data about all instances.
979

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

984
  @type hypervisor_list: list
985
  @param hypervisor_list: list of hypervisors to query for instance data
986

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

994
  """
995
  output = {}
996

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

    
1017
  return output
1018

    
1019

    
1020
def _InstanceLogName(kind, os_name, instance, component):
1021
  """Compute the OS log filename for a given instance and operation.
1022

1023
  The instance name and os name are passed in as strings since not all
1024
  operations have these as part of an instance object.
1025

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

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

    
1047

    
1048
def InstanceOsAdd(instance, reinstall, debug):
1049
  """Add an OS to an instance.
1050

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

1059
  """
1060
  inst_os = OSFromDisk(instance.os)
1061

    
1062
  create_env = OSEnvironment(instance, inst_os, debug)
1063
  if reinstall:
1064
    create_env["INSTANCE_REINSTALL"] = "1"
1065

    
1066
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1067

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

    
1079

    
1080
def RunRenameInstance(instance, old_name, debug):
1081
  """Run the OS rename script for an instance.
1082

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

1092
  """
1093
  inst_os = OSFromDisk(instance.os)
1094

    
1095
  rename_env = OSEnvironment(instance, inst_os, debug)
1096
  rename_env["OLD_INSTANCE_NAME"] = old_name
1097

    
1098
  logfile = _InstanceLogName("rename", instance.os,
1099
                             "%s-%s" % (old_name, instance.name), None)
1100

    
1101
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1102
                        cwd=inst_os.path, output=logfile, reset_env=True)
1103

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

    
1112

    
1113
def _GetBlockDevSymlinkPath(instance_name, idx):
1114
  return utils.PathJoin(constants.DISK_LINKS_DIR, "%s%s%d" %
1115
                        (instance_name, constants.DISK_SEPARATOR, idx))
1116

    
1117

    
1118
def _SymlinkBlockDev(instance_name, device_path, idx):
1119
  """Set up symlinks to a instance's block device.
1120

1121
  This is an auxiliary function run when an instance is start (on the primary
1122
  node) or when an instance is migrated (on the target node).
1123

1124

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

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

    
1143
  return link_name
1144

    
1145

    
1146
def _RemoveBlockDevLinks(instance_name, disks):
1147
  """Remove the block device symlinks belonging to the given instance.
1148

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

    
1158

    
1159
def _GatherAndLinkBlockDevs(instance):
1160
  """Set up an instance's block device(s).
1161

1162
  This is run on the primary node at instance startup. The block
1163
  devices must be already assembled.
1164

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

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

    
1184
    block_devices.append((disk, link_name))
1185

    
1186
  return block_devices
1187

    
1188

    
1189
def StartInstance(instance, startup_paused):
1190
  """Start an instance.
1191

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

1198
  """
1199
  running_instances = GetInstanceList([instance.hypervisor])
1200

    
1201
  if instance.name in running_instances:
1202
    logging.info("Instance %s already running, not starting", instance.name)
1203
    return
1204

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

    
1215

    
1216
def InstanceShutdown(instance, timeout):
1217
  """Shut an instance down.
1218

1219
  @note: this functions uses polling with a hardcoded timeout.
1220

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

1227
  """
1228
  hv_name = instance.hypervisor
1229
  hyper = hypervisor.GetHypervisor(hv_name)
1230
  iname = instance.name
1231

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

    
1236
  class _TryShutdown:
1237
    def __init__(self):
1238
      self.tried_once = False
1239

    
1240
    def __call__(self):
1241
      if iname not in hyper.ListInstances():
1242
        return
1243

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

    
1252
        _Fail("Failed to stop instance %s: %s", iname, err)
1253

    
1254
      self.tried_once = True
1255

    
1256
      raise utils.RetryAgain()
1257

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

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

    
1272
    time.sleep(1)
1273

    
1274
    if iname in hyper.ListInstances():
1275
      _Fail("Could not shutdown instance %s even by destroy", iname)
1276

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

    
1282
  _RemoveBlockDevLinks(iname, instance.disks)
1283

    
1284

    
1285
def InstanceReboot(instance, reboot_type, shutdown_timeout):
1286
  """Reboot an instance.
1287

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

1305
  """
1306
  running_instances = GetInstanceList([instance.hypervisor])
1307

    
1308
  if instance.name not in running_instances:
1309
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1310

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

    
1326

    
1327
def MigrationInfo(instance):
1328
  """Gather information about an instance to be migrated.
1329

1330
  @type instance: L{objects.Instance}
1331
  @param instance: the instance definition
1332

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

    
1341

    
1342
def AcceptInstance(instance, info, target):
1343
  """Prepare the node to accept an instance.
1344

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

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

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

    
1370

    
1371
def FinalizeMigrationDst(instance, info, success):
1372
  """Finalize any preparation to accept an instance.
1373

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

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

    
1388

    
1389
def MigrateInstance(instance, target, live):
1390
  """Migrates an instance to another node.
1391

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

1401
  """
1402
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1403

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

    
1409

    
1410
def FinalizeMigrationSource(instance, success, live):
1411
  """Finalize the instance migration on the source node.
1412

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

1421
  """
1422
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1423

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

    
1430

    
1431
def GetMigrationStatus(instance):
1432
  """Get the migration status
1433

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

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

    
1449

    
1450
def BlockdevCreate(disk, size, owner, on_primary, info):
1451
  """Creates a block device for an instance.
1452

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

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

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

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

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

    
1509
  device.SetInfo(info)
1510

    
1511
  return device.unique_id
1512

    
1513

    
1514
def _WipeDevice(path, offset, size):
1515
  """This function actually wipes the device.
1516

1517
  @param path: The path to the device to wipe
1518
  @param offset: The offset in MiB in the file
1519
  @param size: The size in MiB to write
1520

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

    
1527
  if result.failed:
1528
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1529
          result.fail_reason, result.output)
1530

    
1531

    
1532
def BlockdevWipe(disk, offset, size):
1533
  """Wipes a block device.
1534

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

1542
  """
1543
  try:
1544
    rdev = _RecursiveFindBD(disk)
1545
  except errors.BlockDeviceError:
1546
    rdev = None
1547

    
1548
  if not rdev:
1549
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1550

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

    
1557
  _WipeDevice(rdev.dev_path, offset, size)
1558

    
1559

    
1560
def BlockdevPauseResumeSync(disks, pause):
1561
  """Pause or resume the sync of the block device.
1562

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

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

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

    
1581
    result = rdev.PauseResumeSync(pause)
1582

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

    
1592
  return success
1593

    
1594

    
1595
def BlockdevRemove(disk):
1596
  """Remove a block device.
1597

1598
  @note: This is intended to be called recursively.
1599

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

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

    
1622
  if disk.children:
1623
    for child in disk.children:
1624
      try:
1625
        BlockdevRemove(child)
1626
      except RPCFail, err:
1627
        msgs.append(str(err))
1628

    
1629
  if msgs:
1630
    _Fail("; ".join(msgs))
1631

    
1632

    
1633
def _RecursiveAssembleBD(disk, owner, as_primary):
1634
  """Activate a block device for an instance.
1635

1636
  This is run on the primary and secondary nodes for an instance.
1637

1638
  @note: this function is called recursively.
1639

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

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

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

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

    
1682
  else:
1683
    result = True
1684
  return result
1685

    
1686

    
1687
def BlockdevAssemble(disk, owner, as_primary, idx):
1688
  """Activate a block device for an instance.
1689

1690
  This is a wrapper over _RecursiveAssembleBD.
1691

1692
  @rtype: str or boolean
1693
  @return: a C{/dev/...} path for primary nodes, and
1694
      C{True} for secondary nodes
1695

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

    
1709
  return result
1710

    
1711

    
1712
def BlockdevShutdown(disk):
1713
  """Shut down a block device.
1714

1715
  First, if the device is assembled (Attach() is successful), then
1716
  the device is shutdown. Then the children of the device are
1717
  shutdown.
1718

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

1723
  @type disk: L{objects.Disk}
1724
  @param disk: the description of the disk we should
1725
      shutdown
1726
  @rtype: None
1727

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

    
1739
  if disk.children:
1740
    for child in disk.children:
1741
      try:
1742
        BlockdevShutdown(child)
1743
      except RPCFail, err:
1744
        msgs.append(str(err))
1745

    
1746
  if msgs:
1747
    _Fail("; ".join(msgs))
1748

    
1749

    
1750
def BlockdevAddchildren(parent_cdev, new_cdevs):
1751
  """Extend a mirrored block device.
1752

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

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

    
1768

    
1769
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1770
  """Shrink a mirrored block device.
1771

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

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

    
1797

    
1798
def BlockdevGetmirrorstatus(disks):
1799
  """Get the mirroring status of a list of devices.
1800

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

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

    
1815
    stats.append(rbd.CombinedSyncStatus())
1816

    
1817
  return stats
1818

    
1819

    
1820
def BlockdevGetmirrorstatusMulti(disks):
1821
  """Get the mirroring status of a list of devices.
1822

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

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

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

    
1846
  assert len(disks) == len(result)
1847

    
1848
  return result
1849

    
1850

    
1851
def _RecursiveFindBD(disk):
1852
  """Check if a device is activated.
1853

1854
  If so, return information about the real device.
1855

1856
  @type disk: L{objects.Disk}
1857
  @param disk: the disk object we need to find
1858

1859
  @return: None if the device can't be found,
1860
      otherwise the device instance
1861

1862
  """
1863
  children = []
1864
  if disk.children:
1865
    for chdisk in disk.children:
1866
      children.append(_RecursiveFindBD(chdisk))
1867

    
1868
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1869

    
1870

    
1871
def _OpenRealBD(disk):
1872
  """Opens the underlying block device of a disk.
1873

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

1877
  """
1878
  real_disk = _RecursiveFindBD(disk)
1879
  if real_disk is None:
1880
    _Fail("Block device '%s' is not set up", disk)
1881

    
1882
  real_disk.Open()
1883

    
1884
  return real_disk
1885

    
1886

    
1887
def BlockdevFind(disk):
1888
  """Check if a device is activated.
1889

1890
  If it is, return information about the real device.
1891

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

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

    
1904
  if rbd is None:
1905
    return None
1906

    
1907
  return rbd.GetSyncStatus()
1908

    
1909

    
1910
def BlockdevGetsize(disks):
1911
  """Computes the size of the given disks.
1912

1913
  If a disk is not found, returns None instead.
1914

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

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

    
1935

    
1936
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
1937
  """Export a block device to a remote node.
1938

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

1949
  """
1950
  real_disk = _OpenRealBD(disk)
1951

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

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

    
1966
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1967
                                                   constants.GANETI_RUNAS,
1968
                                                   destcmd)
1969

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

    
1973
  result = utils.RunCmd(["bash", "-c", command])
1974

    
1975
  if result.failed:
1976
    _Fail("Disk copy command '%s' returned error: %s"
1977
          " output: %s", command, result.fail_reason, result.output)
1978

    
1979

    
1980
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1981
  """Write a file to the filesystem.
1982

1983
  This allows the master to overwrite(!) a file. It will only perform
1984
  the operation if the file belongs to a list of configuration files.
1985

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

2002
  """
2003
  if not os.path.isabs(file_name):
2004
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2005

    
2006
  if file_name not in _ALLOWED_UPLOAD_FILES:
2007
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2008
          file_name)
2009

    
2010
  raw_data = _Decompress(data)
2011

    
2012
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2013
    _Fail("Invalid username/groupname type")
2014

    
2015
  getents = runtime.GetEnts()
2016
  uid = getents.LookupUser(uid)
2017
  gid = getents.LookupGroup(gid)
2018

    
2019
  utils.SafeWriteFile(file_name, None,
2020
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2021
                      atime=atime, mtime=mtime)
2022

    
2023

    
2024
def RunOob(oob_program, command, node, timeout):
2025
  """Executes oob_program with given command on given node.
2026

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

2032
  @return: stdout
2033
  @raise RPCFail: If execution fails for some reason
2034

2035
  """
2036
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2037

    
2038
  if result.failed:
2039
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2040
          result.fail_reason, result.output)
2041

    
2042
  return result.stdout
2043

    
2044

    
2045
def WriteSsconfFiles(values):
2046
  """Update all ssconf files.
2047

2048
  Wrapper around the SimpleStore.WriteFiles.
2049

2050
  """
2051
  ssconf.SimpleStore().WriteFiles(values)
2052

    
2053

    
2054
def _ErrnoOrStr(err):
2055
  """Format an EnvironmentError exception.
2056

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

2061
  @type err: L{EnvironmentError}
2062
  @param err: the exception to format
2063

2064
  """
2065
  if hasattr(err, "errno"):
2066
    detail = errno.errorcode[err.errno]
2067
  else:
2068
    detail = str(err)
2069
  return detail
2070

    
2071

    
2072
def _OSOndiskAPIVersion(os_dir):
2073
  """Compute and return the API version of a given OS.
2074

2075
  This function will try to read the API version of the OS residing in
2076
  the 'os_dir' directory.
2077

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

2084
  """
2085
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2086

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

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

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

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

    
2109
  return True, api_versions
2110

    
2111

    
2112
def DiagnoseOS(top_dirs=None):
2113
  """Compute the validity for all OSes.
2114

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

2131
  """
2132
  if top_dirs is None:
2133
    top_dirs = constants.OS_SEARCH_PATH
2134

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

    
2157
  return result
2158

    
2159

    
2160
def _TryOSFromDisk(name, base_dir=None):
2161
  """Create an OS instance from disk.
2162

2163
  This function will return an OS instance if the given name is a
2164
  valid OS name.
2165

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

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

    
2179
  if os_dir is None:
2180
    return False, "Directory for OS %s not found in search path" % name
2181

    
2182
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2183
  if not status:
2184
    # push the error up
2185
    return status, api_versions
2186

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

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

    
2196
  if max(api_versions) >= constants.OS_API_V15:
2197
    os_files[constants.OS_VARIANTS_FILE] = False
2198

    
2199
  if max(api_versions) >= constants.OS_API_V20:
2200
    os_files[constants.OS_PARAMETERS_FILE] = True
2201
  else:
2202
    del os_files[constants.OS_SCRIPT_VERIFY]
2203

    
2204
  for (filename, required) in os_files.items():
2205
    os_files[filename] = utils.PathJoin(os_dir, filename)
2206

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

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

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

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

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

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

    
2258

    
2259
def OSFromDisk(name, base_dir=None):
2260
  """Create an OS instance from disk.
2261

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

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

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

2276
  """
2277
  name_only = objects.OS.GetName(name)
2278
  status, payload = _TryOSFromDisk(name_only, base_dir)
2279

    
2280
  if not status:
2281
    _Fail(payload)
2282

    
2283
  return payload
2284

    
2285

    
2286
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2287
  """Calculate the basic environment for an os script.
2288

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

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

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

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

    
2323
  return result
2324

    
2325

    
2326
def OSEnvironment(instance, inst_os, debug=0):
2327
  """Calculate the environment for an os script.
2328

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

2340
  """
2341
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2342

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

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

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

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

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

    
2385
  return result
2386

    
2387

    
2388
def BlockdevGrow(disk, amount, dryrun):
2389
  """Grow a stack of block devices.
2390

2391
  This function is called recursively, with the childrens being the
2392
  first ones to resize.
2393

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

2405
  """
2406
  r_dev = _RecursiveFindBD(disk)
2407
  if r_dev is None:
2408
    _Fail("Cannot find block device %s", disk)
2409

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

    
2415

    
2416
def BlockdevSnapshot(disk):
2417
  """Create a snapshot copy of a block device.
2418

2419
  This function is called recursively, and the snapshot is actually created
2420
  just for the leaf lvm backend device.
2421

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

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

    
2445

    
2446
def FinalizeExport(instance, snap_disks):
2447
  """Write out the export configuration information.
2448

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

2456
  @rtype: None
2457

2458
  """
2459
  destdir = utils.PathJoin(constants.EXPORT_DIR, instance.name + ".new")
2460
  finaldestdir = utils.PathJoin(constants.EXPORT_DIR, instance.name)
2461

    
2462
  config = objects.SerializableConfigParser()
2463

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

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

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

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

    
2504
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2505

    
2506
  # New-style hypervisor/backend parameters
2507

    
2508
  config.add_section(constants.INISECT_HYP)
2509
  for name, value in instance.hvparams.items():
2510
    if name not in constants.HVC_GLOBALS:
2511
      config.set(constants.INISECT_HYP, name, str(value))
2512

    
2513
  config.add_section(constants.INISECT_BEP)
2514
  for name, value in instance.beparams.items():
2515
    config.set(constants.INISECT_BEP, name, str(value))
2516

    
2517
  config.add_section(constants.INISECT_OSP)
2518
  for name, value in instance.osparams.items():
2519
    config.set(constants.INISECT_OSP, name, str(value))
2520

    
2521
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2522
                  data=config.Dumps())
2523
  shutil.rmtree(finaldestdir, ignore_errors=True)
2524
  shutil.move(destdir, finaldestdir)
2525

    
2526

    
2527
def ExportInfo(dest):
2528
  """Get export configuration information.
2529

2530
  @type dest: str
2531
  @param dest: directory containing the export
2532

2533
  @rtype: L{objects.SerializableConfigParser}
2534
  @return: a serializable config file containing the
2535
      export info
2536

2537
  """
2538
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2539

    
2540
  config = objects.SerializableConfigParser()
2541
  config.read(cff)
2542

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

    
2547
  return config.Dumps()
2548

    
2549

    
2550
def ListExports():
2551
  """Return a list of exports currently available on this machine.
2552

2553
  @rtype: list
2554
  @return: list of the exports
2555

2556
  """
2557
  if os.path.isdir(constants.EXPORT_DIR):
2558
    return sorted(utils.ListVisibleFiles(constants.EXPORT_DIR))
2559
  else:
2560
    _Fail("No exports directory")
2561

    
2562

    
2563
def RemoveExport(export):
2564
  """Remove an existing export from the node.
2565

2566
  @type export: str
2567
  @param export: the name of the export to remove
2568
  @rtype: None
2569

2570
  """
2571
  target = utils.PathJoin(constants.EXPORT_DIR, export)
2572

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

    
2578

    
2579
def BlockdevRename(devlist):
2580
  """Rename a list of block devices.
2581

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

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

    
2619

    
2620
def _TransformFileStorageDir(fs_dir):
2621
  """Checks whether given file_storage_dir is valid.
2622

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

2627
  @type fs_dir: str
2628
  @param fs_dir: the path to check
2629

2630
  @return: the normalized path if valid, None otherwise
2631

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

    
2646

    
2647
def CreateFileStorageDir(file_storage_dir):
2648
  """Create file storage directory.
2649

2650
  @type file_storage_dir: str
2651
  @param file_storage_dir: directory to create
2652

2653
  @rtype: tuple
2654
  @return: tuple with first element a boolean indicating wheter dir
2655
      creation was successful or not
2656

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

    
2670

    
2671
def RemoveFileStorageDir(file_storage_dir):
2672
  """Remove file storage directory.
2673

2674
  Remove it only if it's empty. If not log an error and return.
2675

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

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

    
2695

    
2696
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2697
  """Rename the file storage directory.
2698

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

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

    
2725

    
2726
def _EnsureJobQueueFile(file_name):
2727
  """Checks whether the given filename is in the queue directory.
2728

2729
  @type file_name: str
2730
  @param file_name: the file name we should check
2731
  @rtype: None
2732
  @raises RPCFail: if the file is not valid
2733

2734
  """
2735
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2736
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2737

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

    
2742

    
2743
def JobQueueUpdate(file_name, content):
2744
  """Updates a file in the queue directory.
2745

2746
  This is just a wrapper over L{utils.io.WriteFile}, with proper
2747
  checking.
2748

2749
  @type file_name: str
2750
  @param file_name: the job file name
2751
  @type content: str
2752
  @param content: the new job contents
2753
  @rtype: boolean
2754
  @return: the success of the operation
2755

2756
  """
2757
  _EnsureJobQueueFile(file_name)
2758
  getents = runtime.GetEnts()
2759

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

    
2764

    
2765
def JobQueueRename(old, new):
2766
  """Renames a job queue file.
2767

2768
  This is just a wrapper over os.rename with proper checking.
2769

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

2777
  """
2778
  _EnsureJobQueueFile(old)
2779
  _EnsureJobQueueFile(new)
2780

    
2781
  getents = runtime.GetEnts()
2782

    
2783
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0700,
2784
                   dir_uid=getents.masterd_uid, dir_gid=getents.masterd_gid)
2785

    
2786

    
2787
def BlockdevClose(instance_name, disks):
2788
  """Closes the given block devices.
2789

2790
  This means they will be switched to secondary mode (in case of
2791
  DRBD).
2792

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

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

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

    
2823

    
2824
def ValidateHVParams(hvname, hvparams):
2825
  """Validates the given hypervisor parameters.
2826

2827
  @type hvname: string
2828
  @param hvname: the hypervisor name
2829
  @type hvparams: dict
2830
  @param hvparams: the hypervisor parameters to be validated
2831
  @rtype: None
2832

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

    
2840

    
2841
def _CheckOSPList(os_obj, parameters):
2842
  """Check whether a list of parameters is supported by the OS.
2843

2844
  @type os_obj: L{objects.OS}
2845
  @param os_obj: OS object to check
2846
  @type parameters: list
2847
  @param parameters: the list of parameters to check
2848

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

    
2856

    
2857
def ValidateOS(required, osname, checks, osparams):
2858
  """Validate the given OS' parameters.
2859

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

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

    
2878
  name_only = objects.OS.GetName(osname)
2879
  status, tbv = _TryOSFromDisk(name_only, None)
2880

    
2881
  if not status:
2882
    if required:
2883
      _Fail(tbv)
2884
    else:
2885
      return False
2886

    
2887
  if max(tbv.api_versions) < constants.OS_API_V20:
2888
    return True
2889

    
2890
  if constants.OS_VALIDATE_PARAMETERS in checks:
2891
    _CheckOSPList(tbv, osparams.keys())
2892

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

    
2902
  return True
2903

    
2904

    
2905
def DemoteFromMC():
2906
  """Demotes the current node from master candidate role.
2907

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

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

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

    
2925
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2926

    
2927

    
2928
def _GetX509Filenames(cryptodir, name):
2929
  """Returns the full paths for the private key and certificate.
2930

2931
  """
2932
  return (utils.PathJoin(cryptodir, name),
2933
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
2934
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
2935

    
2936

    
2937
def CreateX509Certificate(validity, cryptodir=constants.CRYPTO_KEYS_DIR):
2938
  """Creates a new X509 certificate for SSL/TLS.
2939

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

2945
  """
2946
  (key_pem, cert_pem) = \
2947
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
2948
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
2949

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

    
2956
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2957

    
2958
    utils.WriteFile(key_file, mode=0400, data=key_pem)
2959
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
2960

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

    
2967

    
2968
def RemoveX509Certificate(name, cryptodir=constants.CRYPTO_KEYS_DIR):
2969
  """Removes a X509 certificate.
2970

2971
  @type name: string
2972
  @param name: Certificate name
2973

2974
  """
2975
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2976

    
2977
  utils.RemoveFile(key_file)
2978
  utils.RemoveFile(cert_file)
2979

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

    
2986

    
2987
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
2988
  """Returns the command for the requested input/output.
2989

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

2996
  """
2997
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
2998

    
2999
  env = None
3000
  prefix = None
3001
  suffix = None
3002
  exp_size = None
3003

    
3004
  if ieio == constants.IEIO_FILE:
3005
    (filename, ) = ieargs
3006

    
3007
    if not utils.IsNormAbsPath(filename):
3008
      _Fail("Path '%s' is not normalized or absolute", filename)
3009

    
3010
    real_filename = os.path.realpath(filename)
3011
    directory = os.path.dirname(real_filename)
3012

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

    
3017
    # Create directory
3018
    utils.Makedirs(directory, mode=0750)
3019

    
3020
    quoted_filename = utils.ShellQuote(filename)
3021

    
3022
    if mode == constants.IEM_IMPORT:
3023
      suffix = "> %s" % quoted_filename
3024
    elif mode == constants.IEM_EXPORT:
3025
      suffix = "< %s" % quoted_filename
3026

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

    
3035
  elif ieio == constants.IEIO_RAW_DISK:
3036
    (disk, ) = ieargs
3037

    
3038
    real_disk = _OpenRealBD(disk)
3039

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

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

    
3060
  elif ieio == constants.IEIO_SCRIPT:
3061
    (disk, disk_index, ) = ieargs
3062

    
3063
    assert isinstance(disk_index, (int, long))
3064

    
3065
    real_disk = _OpenRealBD(disk)
3066

    
3067
    inst_os = OSFromDisk(instance.os)
3068
    env = OSEnvironment(instance, inst_os)
3069

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

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

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

    
3083
    if mode == constants.IEM_IMPORT:
3084
      suffix = "| %s" % script_cmd
3085

    
3086
    elif mode == constants.IEM_EXPORT:
3087
      prefix = "%s |" % script_cmd
3088

    
3089
    # Let script predict size
3090
    exp_size = constants.IE_CUSTOM_SIZE
3091

    
3092
  else:
3093
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3094

    
3095
  return (env, prefix, suffix, exp_size)
3096

    
3097

    
3098
def _CreateImportExportStatusDir(prefix):
3099
  """Creates status directory for import/export.
3100

3101
  """
3102
  return tempfile.mkdtemp(dir=constants.IMPORT_EXPORT_DIR,
3103
                          prefix=("%s-%s-" %
3104
                                  (prefix, utils.TimestampForFilename())))
3105

    
3106

    
3107
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3108
                            ieio, ieioargs):
3109
  """Starts an import or export daemon.
3110

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

3126
  """
3127
  if mode == constants.IEM_IMPORT:
3128
    prefix = "import"
3129

    
3130
    if not (host is None and port is None):
3131
      _Fail("Can not specify host or port on import")
3132

    
3133
  elif mode == constants.IEM_EXPORT:
3134
    prefix = "export"
3135

    
3136
    if host is None or port is None:
3137
      _Fail("Host and port must be specified for an export")
3138

    
3139
  else:
3140
    _Fail("Invalid mode %r", mode)
3141

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

    
3145
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3146
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3147

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

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

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

    
3168
    if opts.ca_pem is None:
3169
      # Use server.pem
3170
      ca = utils.ReadFile(constants.NODED_CERT_FILE)
3171
    else:
3172
      ca = opts.ca_pem
3173

    
3174
    # Write CA file
3175
    utils.WriteFile(ca_file, data=ca, mode=0400)
3176

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

    
3185
    if host:
3186
      cmd.append("--host=%s" % host)
3187

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

    
3191
    if opts.ipv6:
3192
      cmd.append("--ipv6")
3193
    else:
3194
      cmd.append("--ipv4")
3195

    
3196
    if opts.compress:
3197
      cmd.append("--compress=%s" % opts.compress)
3198

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

    
3202
    if exp_size is not None:
3203
      cmd.append("--expected-size=%s" % exp_size)
3204

    
3205
    if cmd_prefix:
3206
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3207

    
3208
    if cmd_suffix:
3209
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3210

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

    
3220
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3221

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

    
3227
    # The import/export name is simply the status directory name
3228
    return os.path.basename(status_dir)
3229

    
3230
  except Exception:
3231
    shutil.rmtree(status_dir, ignore_errors=True)
3232
    raise
3233

    
3234

    
3235
def GetImportExportStatus(names):
3236
  """Returns import/export daemon status.
3237

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

3244
  """
3245
  result = []
3246

    
3247
  for name in names:
3248
    status_file = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name,
3249
                                 _IES_STATUS_FILE)
3250

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

    
3258
    if not data:
3259
      result.append(None)
3260
      continue
3261

    
3262
    result.append(serializer.LoadJson(data))
3263

    
3264
  return result
3265

    
3266

    
3267
def AbortImportExport(name):
3268
  """Sends SIGTERM to a running import/export daemon.
3269

3270
  """
3271
  logging.info("Abort import/export %s", name)
3272

    
3273
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3274
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3275

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

    
3281

    
3282
def CleanupImportExport(name):
3283
  """Cleanup after an import or export.
3284

3285
  If the import/export daemon is still running it's killed. Afterwards the
3286
  whole status directory is removed.
3287

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

    
3291
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3292

    
3293
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3294

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

    
3300
  shutil.rmtree(status_dir, ignore_errors=True)
3301

    
3302

    
3303
def _FindDisks(nodes_ip, disks):
3304
  """Sets the physical ID on disks and returns the block devices.
3305

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

    
3312
  bdevs = []
3313

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

    
3321

    
3322
def DrbdDisconnectNet(nodes_ip, disks):
3323
  """Disconnects the network on a list of drbd devices.
3324

3325
  """
3326
  bdevs = _FindDisks(nodes_ip, disks)
3327

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

    
3336

    
3337
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3338
  """Attaches the network on a list of drbd devices.
3339

3340
  """
3341
  bdevs = _FindDisks(nodes_ip, disks)
3342

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

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

    
3363
  def _Attach():
3364
    all_connected = True
3365

    
3366
    for rd in bdevs:
3367
      stats = rd.GetProcStatus()
3368

    
3369
      all_connected = (all_connected and
3370
                       (stats.is_connected or stats.is_in_resync))
3371

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

    
3381
    if not all_connected:
3382
      raise utils.RetryAgain()
3383

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

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

    
3398

    
3399
def DrbdWaitSync(nodes_ip, disks):
3400
  """Wait until DRBDs have synchronized.
3401

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

    
3409
  bdevs = _FindDisks(nodes_ip, disks)
3410

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

    
3426
  return (alldone, min_resync)
3427

    
3428

    
3429
def GetDrbdUsermodeHelper():
3430
  """Returns DRBD usermode helper currently configured.
3431

3432
  """
3433
  try:
3434
    return bdev.BaseDRBD.GetUsermodeHelper()
3435
  except errors.BlockDeviceError, err:
3436
    _Fail(str(err))
3437

    
3438

    
3439
def PowercycleNode(hypervisor_type):
3440
  """Hard-powercycle the node.
3441

3442
  Because we need to return first, and schedule the powercycle in the
3443
  background, we won't be able to report failures nicely.
3444

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

    
3462

    
3463
class HooksRunner(object):
3464
  """Hook runner.
3465

3466
  This class is instantiated on the node side (ganeti-noded) and not
3467
  on the master side.
3468

3469
  """
3470
  def __init__(self, hooks_base_dir=None):
3471
    """Constructor for hooks runner.
3472

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

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

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

3487
    """
3488
    assert len(node_list) == 1
3489
    node = node_list[0]
3490
    _, myself = ssconf.GetMasterAndMyself()
3491
    assert node == myself
3492

    
3493
    results = self.RunHooks(hpath, phase, env)
3494

    
3495
    # Return values in the form expected by HooksMaster
3496
    return {node: (None, False, results)}
3497

    
3498
  def RunHooks(self, hpath, phase, env):
3499
    """Run the scripts in the hooks directory.
3500

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

3516
    @raise errors.ProgrammerError: for invalid input
3517
        parameters
3518

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

    
3527
    subdir = "%s-%s.d" % (hpath, suffix)
3528
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3529

    
3530
    results = []
3531

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

    
3537
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3538

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

    
3554
    return results
3555

    
3556

    
3557
class IAllocatorRunner(object):
3558
  """IAllocator runner.
3559

3560
  This class is instantiated on the node side (ganeti-noded) and not on
3561
  the master side.
3562

3563
  """
3564
  @staticmethod
3565
  def Run(name, idata):
3566
    """Run an iallocator script.
3567

3568
    @type name: str
3569
    @param name: the iallocator script name
3570
    @type idata: str
3571
    @param idata: the allocator input data
3572

3573
    @rtype: tuple
3574
    @return: two element tuple of:
3575
       - status
3576
       - either error message or stdout of allocator (for success)
3577

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

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

    
3595
    return result.stdout
3596

    
3597

    
3598
class DevCacheManager(object):
3599
  """Simple class for managing a cache of block device information.
3600

3601
  """
3602
  _DEV_PREFIX = "/dev/"
3603
  _ROOT_DIR = constants.BDEV_CACHE_DIR
3604

    
3605
  @classmethod
3606
  def _ConvertPath(cls, dev_path):
3607
    """Converts a /dev/name path to the cache file name.
3608

3609
    This replaces slashes with underscores and strips the /dev
3610
    prefix. It then returns the full path to the cache file.
3611

3612
    @type dev_path: str
3613
    @param dev_path: the C{/dev/} path name
3614
    @rtype: str
3615
    @return: the converted path name
3616

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

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

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

3639
    @rtype: None
3640

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

    
3658
  @classmethod
3659
  def RemoveCache(cls, dev_path):
3660
    """Remove data for a dev_path.
3661

3662
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
3663
    path name and logging.
3664

3665
    @type dev_path: str
3666
    @param dev_path: the pathname of the device
3667

3668
    @rtype: None
3669

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