Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 714ff97c

History | View | Annotate | Download (108.6 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

    
64

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

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

    
82

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

86
  Its argument is the error message.
87

88
  """
89

    
90

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

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

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

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

    
113

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

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

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

    
123

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

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

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

    
136

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

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

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

    
156

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

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

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

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

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

    
186

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

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

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

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

    
210
  return frozenset(allowed_files)
211

    
212

    
213
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
214

    
215

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

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

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

    
226

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

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

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

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

    
251

    
252
def ActivateMasterIp():
253
  """Activate the IP address of the master daemon.
254

255
  """
256
  # GetMasterInfo will raise an exception if not able to return data
257
  master_netdev, master_ip, _, family, master_netmask = GetMasterInfo()
258

    
259
  err_msg = None
260
  if netutils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
261
    if netutils.IPAddress.Own(master_ip):
262
      # we already have the ip:
263
      logging.debug("Master IP already configured, doing nothing")
264
    else:
265
      err_msg = "Someone else has the master ip, not activating"
266
      logging.error(err_msg)
267
  else:
268
    ipcls = netutils.IPAddress.GetClassFromIpFamily(family)
269

    
270
    result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
271
                           "%s/%s" % (master_ip, master_netmask),
272
                           "dev", master_netdev, "label",
273
                           "%s:0" % master_netdev])
274
    if result.failed:
275
      err_msg = "Can't activate master IP: %s" % result.output
276
      logging.error(err_msg)
277

    
278
    else:
279
      # we ignore the exit code of the following cmds
280
      if ipcls == netutils.IP4Address:
281
        utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev, "-s",
282
                      master_ip, master_ip])
283
      elif ipcls == netutils.IP6Address:
284
        try:
285
          utils.RunCmd(["ndisc6", "-q", "-r 3", master_ip, master_netdev])
286
        except errors.OpExecError:
287
          # TODO: Better error reporting
288
          logging.warning("Can't execute ndisc6, please install if missing")
289

    
290
  if err_msg:
291
    _Fail(err_msg)
292

    
293

    
294
def StartMasterDaemons(no_voting):
295
  """Activate local node as master node.
296

297
  The function will start the master daemons (ganeti-masterd and ganeti-rapi).
298

299
  @type no_voting: boolean
300
  @param no_voting: whether to start ganeti-masterd without a node vote
301
      but still non-interactively
302
  @rtype: None
303

304
  """
305

    
306
  if no_voting:
307
    masterd_args = "--no-voting --yes-do-it"
308
  else:
309
    masterd_args = ""
310

    
311
  env = {
312
    "EXTRA_MASTERD_ARGS": masterd_args,
313
    }
314

    
315
  result = utils.RunCmd([constants.DAEMON_UTIL, "start-master"], env=env)
316
  if result.failed:
317
    msg = "Can't start Ganeti master: %s" % result.output
318
    logging.error(msg)
319
    _Fail(msg)
320

    
321

    
322
def DeactivateMasterIp():
323
  """Deactivate the master IP on this node.
324

325
  """
326
  # TODO: log and report back to the caller the error failures; we
327
  # need to decide in which case we fail the RPC for this
328

    
329
  # GetMasterInfo will raise an exception if not able to return data
330
  master_netdev, master_ip, _, _, master_netmask = GetMasterInfo()
331

    
332
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
333
                         "%s/%s" % (master_ip, master_netmask),
334
                         "dev", master_netdev])
335
  if result.failed:
336
    logging.error("Can't remove the master IP, error: %s", result.output)
337
    # but otherwise ignore the failure
338

    
339

    
340
def StopMasterDaemons():
341
  """Stop the master daemons on this node.
342

343
  Stop the master daemons (ganeti-masterd and ganeti-rapi) on this node.
344

345
  @rtype: None
346

347
  """
348
  # TODO: log and report back to the caller the error failures; we
349
  # need to decide in which case we fail the RPC for this
350

    
351
  result = utils.RunCmd([constants.DAEMON_UTIL, "stop-master"])
352
  if result.failed:
353
    logging.error("Could not stop Ganeti master, command %s had exitcode %s"
354
                  " and error %s",
355
                  result.cmd, result.exit_code, result.output)
356

    
357

    
358
def ChangeMasterNetmask(netmask):
359
  """Change the netmask of the master IP.
360

361
  """
362
  master_netdev, master_ip, _, _, old_netmask = GetMasterInfo()
363
  if old_netmask == netmask:
364
    return
365

    
366
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
367
                         "%s/%s" % (master_ip, netmask),
368
                         "dev", master_netdev, "label",
369
                         "%s:0" % master_netdev])
370
  if result.failed:
371
    _Fail("Could not change the master IP netmask")
372

    
373
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
374
                         "%s/%s" % (master_ip, old_netmask),
375
                         "dev", master_netdev, "label",
376
                         "%s:0" % master_netdev])
377
  if result.failed:
378
    _Fail("Could not change the master IP netmask")
379

    
380

    
381
def EtcHostsModify(mode, host, ip):
382
  """Modify a host entry in /etc/hosts.
383

384
  @param mode: The mode to operate. Either add or remove entry
385
  @param host: The host to operate on
386
  @param ip: The ip associated with the entry
387

388
  """
389
  if mode == constants.ETC_HOSTS_ADD:
390
    if not ip:
391
      RPCFail("Mode 'add' needs 'ip' parameter, but parameter not"
392
              " present")
393
    utils.AddHostToEtcHosts(host, ip)
394
  elif mode == constants.ETC_HOSTS_REMOVE:
395
    if ip:
396
      RPCFail("Mode 'remove' does not allow 'ip' parameter, but"
397
              " parameter is present")
398
    utils.RemoveHostFromEtcHosts(host)
399
  else:
400
    RPCFail("Mode not supported")
401

    
402

    
403
def LeaveCluster(modify_ssh_setup):
404
  """Cleans up and remove the current node.
405

406
  This function cleans up and prepares the current node to be removed
407
  from the cluster.
408

409
  If processing is successful, then it raises an
410
  L{errors.QuitGanetiException} which is used as a special case to
411
  shutdown the node daemon.
412

413
  @param modify_ssh_setup: boolean
414

415
  """
416
  _CleanDirectory(constants.DATA_DIR)
417
  _CleanDirectory(constants.CRYPTO_KEYS_DIR)
418
  JobQueuePurge()
419

    
420
  if modify_ssh_setup:
421
    try:
422
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
423

    
424
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
425

    
426
      utils.RemoveFile(priv_key)
427
      utils.RemoveFile(pub_key)
428
    except errors.OpExecError:
429
      logging.exception("Error while processing ssh files")
430

    
431
  try:
432
    utils.RemoveFile(constants.CONFD_HMAC_KEY)
433
    utils.RemoveFile(constants.RAPI_CERT_FILE)
434
    utils.RemoveFile(constants.SPICE_CERT_FILE)
435
    utils.RemoveFile(constants.SPICE_CACERT_FILE)
436
    utils.RemoveFile(constants.NODED_CERT_FILE)
437
  except: # pylint: disable=W0702
438
    logging.exception("Error while removing cluster secrets")
439

    
440
  result = utils.RunCmd([constants.DAEMON_UTIL, "stop", constants.CONFD])
441
  if result.failed:
442
    logging.error("Command %s failed with exitcode %s and error %s",
443
                  result.cmd, result.exit_code, result.output)
444

    
445
  # Raise a custom exception (handled in ganeti-noded)
446
  raise errors.QuitGanetiException(True, "Shutdown scheduled")
447

    
448

    
449
def GetNodeInfo(vgname, hypervisor_type):
450
  """Gives back a hash with different information about the node.
451

452
  @type vgname: C{string}
453
  @param vgname: the name of the volume group to ask for disk space information
454
  @type hypervisor_type: C{str}
455
  @param hypervisor_type: the name of the hypervisor to ask for
456
      memory information
457
  @rtype: C{dict}
458
  @return: dictionary with the following keys:
459
      - vg_size is the size of the configured volume group in MiB
460
      - vg_free is the free size of the volume group in MiB
461
      - memory_dom0 is the memory allocated for domain0 in MiB
462
      - memory_free is the currently available (free) ram in MiB
463
      - memory_total is the total number of ram in MiB
464
      - hv_version: the hypervisor version, if available
465

466
  """
467
  outputarray = {}
468

    
469
  if vgname is not None:
470
    vginfo = bdev.LogicalVolume.GetVGInfo([vgname])
471
    vg_free = vg_size = None
472
    if vginfo:
473
      vg_free = int(round(vginfo[0][0], 0))
474
      vg_size = int(round(vginfo[0][1], 0))
475
    outputarray["vg_size"] = vg_size
476
    outputarray["vg_free"] = vg_free
477

    
478
  if hypervisor_type is not None:
479
    hyper = hypervisor.GetHypervisor(hypervisor_type)
480
    hyp_info = hyper.GetNodeInfo()
481
    if hyp_info is not None:
482
      outputarray.update(hyp_info)
483

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

    
486
  return outputarray
487

    
488

    
489
def VerifyNode(what, cluster_name):
490
  """Verify the status of the local node.
491

492
  Based on the input L{what} parameter, various checks are done on the
493
  local node.
494

495
  If the I{filelist} key is present, this list of
496
  files is checksummed and the file/checksum pairs are returned.
497

498
  If the I{nodelist} key is present, we check that we have
499
  connectivity via ssh with the target nodes (and check the hostname
500
  report).
501

502
  If the I{node-net-test} key is present, we check that we have
503
  connectivity to the given nodes via both primary IP and, if
504
  applicable, secondary IPs.
505

506
  @type what: C{dict}
507
  @param what: a dictionary of things to check:
508
      - filelist: list of files for which to compute checksums
509
      - nodelist: list of nodes we should check ssh communication with
510
      - node-net-test: list of nodes we should check node daemon port
511
        connectivity with
512
      - hypervisor: list with hypervisors to run the verify for
513
  @rtype: dict
514
  @return: a dictionary with the same keys as the input dict, and
515
      values representing the result of the checks
516

517
  """
518
  result = {}
519
  my_name = netutils.Hostname.GetSysName()
520
  port = netutils.GetDaemonPort(constants.NODED)
521
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
522

    
523
  if constants.NV_HYPERVISOR in what and vm_capable:
524
    result[constants.NV_HYPERVISOR] = tmp = {}
525
    for hv_name in what[constants.NV_HYPERVISOR]:
526
      try:
527
        val = hypervisor.GetHypervisor(hv_name).Verify()
528
      except errors.HypervisorError, err:
529
        val = "Error while checking hypervisor: %s" % str(err)
530
      tmp[hv_name] = val
531

    
532
  if constants.NV_HVPARAMS in what and vm_capable:
533
    result[constants.NV_HVPARAMS] = tmp = []
534
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
535
      try:
536
        logging.info("Validating hv %s, %s", hv_name, hvparms)
537
        hypervisor.GetHypervisor(hv_name).ValidateParameters(hvparms)
538
      except errors.HypervisorError, err:
539
        tmp.append((source, hv_name, str(err)))
540

    
541
  if constants.NV_FILELIST in what:
542
    result[constants.NV_FILELIST] = utils.FingerprintFiles(
543
      what[constants.NV_FILELIST])
544

    
545
  if constants.NV_NODELIST in what:
546
    (nodes, bynode) = what[constants.NV_NODELIST]
547

    
548
    # Add nodes from other groups (different for each node)
549
    try:
550
      nodes.extend(bynode[my_name])
551
    except KeyError:
552
      pass
553

    
554
    # Use a random order
555
    random.shuffle(nodes)
556

    
557
    # Try to contact all nodes
558
    val = {}
559
    for node in nodes:
560
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
561
      if not success:
562
        val[node] = message
563

    
564
    result[constants.NV_NODELIST] = val
565

    
566
  if constants.NV_NODENETTEST in what:
567
    result[constants.NV_NODENETTEST] = tmp = {}
568
    my_pip = my_sip = None
569
    for name, pip, sip in what[constants.NV_NODENETTEST]:
570
      if name == my_name:
571
        my_pip = pip
572
        my_sip = sip
573
        break
574
    if not my_pip:
575
      tmp[my_name] = ("Can't find my own primary/secondary IP"
576
                      " in the node list")
577
    else:
578
      for name, pip, sip in what[constants.NV_NODENETTEST]:
579
        fail = []
580
        if not netutils.TcpPing(pip, port, source=my_pip):
581
          fail.append("primary")
582
        if sip != pip:
583
          if not netutils.TcpPing(sip, port, source=my_sip):
584
            fail.append("secondary")
585
        if fail:
586
          tmp[name] = ("failure using the %s interface(s)" %
587
                       " and ".join(fail))
588

    
589
  if constants.NV_MASTERIP in what:
590
    # FIXME: add checks on incoming data structures (here and in the
591
    # rest of the function)
592
    master_name, master_ip = what[constants.NV_MASTERIP]
593
    if master_name == my_name:
594
      source = constants.IP4_ADDRESS_LOCALHOST
595
    else:
596
      source = None
597
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
598
                                                  source=source)
599

    
600
  if constants.NV_OOB_PATHS in what:
601
    result[constants.NV_OOB_PATHS] = tmp = []
602
    for path in what[constants.NV_OOB_PATHS]:
603
      try:
604
        st = os.stat(path)
605
      except OSError, err:
606
        tmp.append("error stating out of band helper: %s" % err)
607
      else:
608
        if stat.S_ISREG(st.st_mode):
609
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
610
            tmp.append(None)
611
          else:
612
            tmp.append("out of band helper %s is not executable" % path)
613
        else:
614
          tmp.append("out of band helper %s is not a file" % path)
615

    
616
  if constants.NV_LVLIST in what and vm_capable:
617
    try:
618
      val = GetVolumeList(utils.ListVolumeGroups().keys())
619
    except RPCFail, err:
620
      val = str(err)
621
    result[constants.NV_LVLIST] = val
622

    
623
  if constants.NV_INSTANCELIST in what and vm_capable:
624
    # GetInstanceList can fail
625
    try:
626
      val = GetInstanceList(what[constants.NV_INSTANCELIST])
627
    except RPCFail, err:
628
      val = str(err)
629
    result[constants.NV_INSTANCELIST] = val
630

    
631
  if constants.NV_VGLIST in what and vm_capable:
632
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
633

    
634
  if constants.NV_PVLIST in what and vm_capable:
635
    result[constants.NV_PVLIST] = \
636
      bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
637
                                   filter_allocatable=False)
638

    
639
  if constants.NV_VERSION in what:
640
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
641
                                    constants.RELEASE_VERSION)
642

    
643
  if constants.NV_HVINFO in what and vm_capable:
644
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
645
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
646

    
647
  if constants.NV_DRBDLIST in what and vm_capable:
648
    try:
649
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
650
    except errors.BlockDeviceError, err:
651
      logging.warning("Can't get used minors list", exc_info=True)
652
      used_minors = str(err)
653
    result[constants.NV_DRBDLIST] = used_minors
654

    
655
  if constants.NV_DRBDHELPER in what and vm_capable:
656
    status = True
657
    try:
658
      payload = bdev.BaseDRBD.GetUsermodeHelper()
659
    except errors.BlockDeviceError, err:
660
      logging.error("Can't get DRBD usermode helper: %s", str(err))
661
      status = False
662
      payload = str(err)
663
    result[constants.NV_DRBDHELPER] = (status, payload)
664

    
665
  if constants.NV_NODESETUP in what:
666
    result[constants.NV_NODESETUP] = tmpr = []
667
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
668
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
669
                  " under /sys, missing required directories /sys/block"
670
                  " and /sys/class/net")
671
    if (not os.path.isdir("/proc/sys") or
672
        not os.path.isfile("/proc/sysrq-trigger")):
673
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
674
                  " under /proc, missing required directory /proc/sys and"
675
                  " the file /proc/sysrq-trigger")
676

    
677
  if constants.NV_TIME in what:
678
    result[constants.NV_TIME] = utils.SplitTime(time.time())
679

    
680
  if constants.NV_OSLIST in what and vm_capable:
681
    result[constants.NV_OSLIST] = DiagnoseOS()
682

    
683
  if constants.NV_BRIDGES in what and vm_capable:
684
    result[constants.NV_BRIDGES] = [bridge
685
                                    for bridge in what[constants.NV_BRIDGES]
686
                                    if not utils.BridgeExists(bridge)]
687
  return result
688

    
689

    
690
def GetBlockDevSizes(devices):
691
  """Return the size of the given block devices
692

693
  @type devices: list
694
  @param devices: list of block device nodes to query
695
  @rtype: dict
696
  @return:
697
    dictionary of all block devices under /dev (key). The value is their
698
    size in MiB.
699

700
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
701

702
  """
703
  DEV_PREFIX = "/dev/"
704
  blockdevs = {}
705

    
706
  for devpath in devices:
707
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
708
      continue
709

    
710
    try:
711
      st = os.stat(devpath)
712
    except EnvironmentError, err:
713
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
714
      continue
715

    
716
    if stat.S_ISBLK(st.st_mode):
717
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
718
      if result.failed:
719
        # We don't want to fail, just do not list this device as available
720
        logging.warning("Cannot get size for block device %s", devpath)
721
        continue
722

    
723
      size = int(result.stdout) / (1024 * 1024)
724
      blockdevs[devpath] = size
725
  return blockdevs
726

    
727

    
728
def GetVolumeList(vg_names):
729
  """Compute list of logical volumes and their size.
730

731
  @type vg_names: list
732
  @param vg_names: the volume groups whose LVs we should list, or
733
      empty for all volume groups
734
  @rtype: dict
735
  @return:
736
      dictionary of all partions (key) with value being a tuple of
737
      their size (in MiB), inactive and online status::
738

739
        {'xenvg/test1': ('20.06', True, True)}
740

741
      in case of errors, a string is returned with the error
742
      details.
743

744
  """
745
  lvs = {}
746
  sep = "|"
747
  if not vg_names:
748
    vg_names = []
749
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
750
                         "--separator=%s" % sep,
751
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
752
  if result.failed:
753
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
754

    
755
  for line in result.stdout.splitlines():
756
    line = line.strip()
757
    match = _LVSLINE_REGEX.match(line)
758
    if not match:
759
      logging.error("Invalid line returned from lvs output: '%s'", line)
760
      continue
761
    vg_name, name, size, attr = match.groups()
762
    inactive = attr[4] == "-"
763
    online = attr[5] == "o"
764
    virtual = attr[0] == "v"
765
    if virtual:
766
      # we don't want to report such volumes as existing, since they
767
      # don't really hold data
768
      continue
769
    lvs[vg_name + "/" + name] = (size, inactive, online)
770

    
771
  return lvs
772

    
773

    
774
def ListVolumeGroups():
775
  """List the volume groups and their size.
776

777
  @rtype: dict
778
  @return: dictionary with keys volume name and values the
779
      size of the volume
780

781
  """
782
  return utils.ListVolumeGroups()
783

    
784

    
785
def NodeVolumes():
786
  """List all volumes on this node.
787

788
  @rtype: list
789
  @return:
790
    A list of dictionaries, each having four keys:
791
      - name: the logical volume name,
792
      - size: the size of the logical volume
793
      - dev: the physical device on which the LV lives
794
      - vg: the volume group to which it belongs
795

796
    In case of errors, we return an empty list and log the
797
    error.
798

799
    Note that since a logical volume can live on multiple physical
800
    volumes, the resulting list might include a logical volume
801
    multiple times.
802

803
  """
804
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
805
                         "--separator=|",
806
                         "--options=lv_name,lv_size,devices,vg_name"])
807
  if result.failed:
808
    _Fail("Failed to list logical volumes, lvs output: %s",
809
          result.output)
810

    
811
  def parse_dev(dev):
812
    return dev.split("(")[0]
813

    
814
  def handle_dev(dev):
815
    return [parse_dev(x) for x in dev.split(",")]
816

    
817
  def map_line(line):
818
    line = [v.strip() for v in line]
819
    return [{"name": line[0], "size": line[1],
820
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
821

    
822
  all_devs = []
823
  for line in result.stdout.splitlines():
824
    if line.count("|") >= 3:
825
      all_devs.extend(map_line(line.split("|")))
826
    else:
827
      logging.warning("Strange line in the output from lvs: '%s'", line)
828
  return all_devs
829

    
830

    
831
def BridgesExist(bridges_list):
832
  """Check if a list of bridges exist on the current node.
833

834
  @rtype: boolean
835
  @return: C{True} if all of them exist, C{False} otherwise
836

837
  """
838
  missing = []
839
  for bridge in bridges_list:
840
    if not utils.BridgeExists(bridge):
841
      missing.append(bridge)
842

    
843
  if missing:
844
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
845

    
846

    
847
def GetInstanceList(hypervisor_list):
848
  """Provides a list of instances.
849

850
  @type hypervisor_list: list
851
  @param hypervisor_list: the list of hypervisors to query information
852

853
  @rtype: list
854
  @return: a list of all running instances on the current node
855
    - instance1.example.com
856
    - instance2.example.com
857

858
  """
859
  results = []
860
  for hname in hypervisor_list:
861
    try:
862
      names = hypervisor.GetHypervisor(hname).ListInstances()
863
      results.extend(names)
864
    except errors.HypervisorError, err:
865
      _Fail("Error enumerating instances (hypervisor %s): %s",
866
            hname, err, exc=True)
867

    
868
  return results
869

    
870

    
871
def GetInstanceInfo(instance, hname):
872
  """Gives back the information about an instance as a dictionary.
873

874
  @type instance: string
875
  @param instance: the instance name
876
  @type hname: string
877
  @param hname: the hypervisor type of the instance
878

879
  @rtype: dict
880
  @return: dictionary with the following keys:
881
      - memory: memory size of instance (int)
882
      - state: xen state of instance (string)
883
      - time: cpu time of instance (float)
884

885
  """
886
  output = {}
887

    
888
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
889
  if iinfo is not None:
890
    output["memory"] = iinfo[2]
891
    output["state"] = iinfo[4]
892
    output["time"] = iinfo[5]
893

    
894
  return output
895

    
896

    
897
def GetInstanceMigratable(instance):
898
  """Gives whether an instance can be migrated.
899

900
  @type instance: L{objects.Instance}
901
  @param instance: object representing the instance to be checked.
902

903
  @rtype: tuple
904
  @return: tuple of (result, description) where:
905
      - result: whether the instance can be migrated or not
906
      - description: a description of the issue, if relevant
907

908
  """
909
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
910
  iname = instance.name
911
  if iname not in hyper.ListInstances():
912
    _Fail("Instance %s is not running", iname)
913

    
914
  for idx in range(len(instance.disks)):
915
    link_name = _GetBlockDevSymlinkPath(iname, idx)
916
    if not os.path.islink(link_name):
917
      logging.warning("Instance %s is missing symlink %s for disk %d",
918
                      iname, link_name, idx)
919

    
920

    
921
def GetAllInstancesInfo(hypervisor_list):
922
  """Gather data about all instances.
923

924
  This is the equivalent of L{GetInstanceInfo}, except that it
925
  computes data for all instances at once, thus being faster if one
926
  needs data about more than one instance.
927

928
  @type hypervisor_list: list
929
  @param hypervisor_list: list of hypervisors to query for instance data
930

931
  @rtype: dict
932
  @return: dictionary of instance: data, with data having the following keys:
933
      - memory: memory size of instance (int)
934
      - state: xen state of instance (string)
935
      - time: cpu time of instance (float)
936
      - vcpus: the number of vcpus
937

938
  """
939
  output = {}
940

    
941
  for hname in hypervisor_list:
942
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
943
    if iinfo:
944
      for name, _, memory, vcpus, state, times in iinfo:
945
        value = {
946
          "memory": memory,
947
          "vcpus": vcpus,
948
          "state": state,
949
          "time": times,
950
          }
951
        if name in output:
952
          # we only check static parameters, like memory and vcpus,
953
          # and not state and time which can change between the
954
          # invocations of the different hypervisors
955
          for key in "memory", "vcpus":
956
            if value[key] != output[name][key]:
957
              _Fail("Instance %s is running twice"
958
                    " with different parameters", name)
959
        output[name] = value
960

    
961
  return output
962

    
963

    
964
def _InstanceLogName(kind, os_name, instance, component):
965
  """Compute the OS log filename for a given instance and operation.
966

967
  The instance name and os name are passed in as strings since not all
968
  operations have these as part of an instance object.
969

970
  @type kind: string
971
  @param kind: the operation type (e.g. add, import, etc.)
972
  @type os_name: string
973
  @param os_name: the os name
974
  @type instance: string
975
  @param instance: the name of the instance being imported/added/etc.
976
  @type component: string or None
977
  @param component: the name of the component of the instance being
978
      transferred
979

980
  """
981
  # TODO: Use tempfile.mkstemp to create unique filename
982
  if component:
983
    assert "/" not in component
984
    c_msg = "-%s" % component
985
  else:
986
    c_msg = ""
987
  base = ("%s-%s-%s%s-%s.log" %
988
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
989
  return utils.PathJoin(constants.LOG_OS_DIR, base)
990

    
991

    
992
def InstanceOsAdd(instance, reinstall, debug):
993
  """Add an OS to an instance.
994

995
  @type instance: L{objects.Instance}
996
  @param instance: Instance whose OS is to be installed
997
  @type reinstall: boolean
998
  @param reinstall: whether this is an instance reinstall
999
  @type debug: integer
1000
  @param debug: debug level, passed to the OS scripts
1001
  @rtype: None
1002

1003
  """
1004
  inst_os = OSFromDisk(instance.os)
1005

    
1006
  create_env = OSEnvironment(instance, inst_os, debug)
1007
  if reinstall:
1008
    create_env["INSTANCE_REINSTALL"] = "1"
1009

    
1010
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1011

    
1012
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1013
                        cwd=inst_os.path, output=logfile, reset_env=True)
1014
  if result.failed:
1015
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1016
                  " output: %s", result.cmd, result.fail_reason, logfile,
1017
                  result.output)
1018
    lines = [utils.SafeEncode(val)
1019
             for val in utils.TailFile(logfile, lines=20)]
1020
    _Fail("OS create script failed (%s), last lines in the"
1021
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1022

    
1023

    
1024
def RunRenameInstance(instance, old_name, debug):
1025
  """Run the OS rename script for an instance.
1026

1027
  @type instance: L{objects.Instance}
1028
  @param instance: Instance whose OS is to be installed
1029
  @type old_name: string
1030
  @param old_name: previous instance name
1031
  @type debug: integer
1032
  @param debug: debug level, passed to the OS scripts
1033
  @rtype: boolean
1034
  @return: the success of the operation
1035

1036
  """
1037
  inst_os = OSFromDisk(instance.os)
1038

    
1039
  rename_env = OSEnvironment(instance, inst_os, debug)
1040
  rename_env["OLD_INSTANCE_NAME"] = old_name
1041

    
1042
  logfile = _InstanceLogName("rename", instance.os,
1043
                             "%s-%s" % (old_name, instance.name), None)
1044

    
1045
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1046
                        cwd=inst_os.path, output=logfile, reset_env=True)
1047

    
1048
  if result.failed:
1049
    logging.error("os create command '%s' returned error: %s output: %s",
1050
                  result.cmd, result.fail_reason, result.output)
1051
    lines = [utils.SafeEncode(val)
1052
             for val in utils.TailFile(logfile, lines=20)]
1053
    _Fail("OS rename script failed (%s), last lines in the"
1054
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1055

    
1056

    
1057
def _GetBlockDevSymlinkPath(instance_name, idx):
1058
  return utils.PathJoin(constants.DISK_LINKS_DIR, "%s%s%d" %
1059
                        (instance_name, constants.DISK_SEPARATOR, idx))
1060

    
1061

    
1062
def _SymlinkBlockDev(instance_name, device_path, idx):
1063
  """Set up symlinks to a instance's block device.
1064

1065
  This is an auxiliary function run when an instance is start (on the primary
1066
  node) or when an instance is migrated (on the target node).
1067

1068

1069
  @param instance_name: the name of the target instance
1070
  @param device_path: path of the physical block device, on the node
1071
  @param idx: the disk index
1072
  @return: absolute path to the disk's symlink
1073

1074
  """
1075
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1076
  try:
1077
    os.symlink(device_path, link_name)
1078
  except OSError, err:
1079
    if err.errno == errno.EEXIST:
1080
      if (not os.path.islink(link_name) or
1081
          os.readlink(link_name) != device_path):
1082
        os.remove(link_name)
1083
        os.symlink(device_path, link_name)
1084
    else:
1085
      raise
1086

    
1087
  return link_name
1088

    
1089

    
1090
def _RemoveBlockDevLinks(instance_name, disks):
1091
  """Remove the block device symlinks belonging to the given instance.
1092

1093
  """
1094
  for idx, _ in enumerate(disks):
1095
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1096
    if os.path.islink(link_name):
1097
      try:
1098
        os.remove(link_name)
1099
      except OSError:
1100
        logging.exception("Can't remove symlink '%s'", link_name)
1101

    
1102

    
1103
def _GatherAndLinkBlockDevs(instance):
1104
  """Set up an instance's block device(s).
1105

1106
  This is run on the primary node at instance startup. The block
1107
  devices must be already assembled.
1108

1109
  @type instance: L{objects.Instance}
1110
  @param instance: the instance whose disks we shoul assemble
1111
  @rtype: list
1112
  @return: list of (disk_object, device_path)
1113

1114
  """
1115
  block_devices = []
1116
  for idx, disk in enumerate(instance.disks):
1117
    device = _RecursiveFindBD(disk)
1118
    if device is None:
1119
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1120
                                    str(disk))
1121
    device.Open()
1122
    try:
1123
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1124
    except OSError, e:
1125
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1126
                                    e.strerror)
1127

    
1128
    block_devices.append((disk, link_name))
1129

    
1130
  return block_devices
1131

    
1132

    
1133
def StartInstance(instance, startup_paused):
1134
  """Start an instance.
1135

1136
  @type instance: L{objects.Instance}
1137
  @param instance: the instance object
1138
  @type startup_paused: bool
1139
  @param instance: pause instance at startup?
1140
  @rtype: None
1141

1142
  """
1143
  running_instances = GetInstanceList([instance.hypervisor])
1144

    
1145
  if instance.name in running_instances:
1146
    logging.info("Instance %s already running, not starting", instance.name)
1147
    return
1148

    
1149
  try:
1150
    block_devices = _GatherAndLinkBlockDevs(instance)
1151
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1152
    hyper.StartInstance(instance, block_devices, startup_paused)
1153
  except errors.BlockDeviceError, err:
1154
    _Fail("Block device error: %s", err, exc=True)
1155
  except errors.HypervisorError, err:
1156
    _RemoveBlockDevLinks(instance.name, instance.disks)
1157
    _Fail("Hypervisor error: %s", err, exc=True)
1158

    
1159

    
1160
def InstanceShutdown(instance, timeout):
1161
  """Shut an instance down.
1162

1163
  @note: this functions uses polling with a hardcoded timeout.
1164

1165
  @type instance: L{objects.Instance}
1166
  @param instance: the instance object
1167
  @type timeout: integer
1168
  @param timeout: maximum timeout for soft shutdown
1169
  @rtype: None
1170

1171
  """
1172
  hv_name = instance.hypervisor
1173
  hyper = hypervisor.GetHypervisor(hv_name)
1174
  iname = instance.name
1175

    
1176
  if instance.name not in hyper.ListInstances():
1177
    logging.info("Instance %s not running, doing nothing", iname)
1178
    return
1179

    
1180
  class _TryShutdown:
1181
    def __init__(self):
1182
      self.tried_once = False
1183

    
1184
    def __call__(self):
1185
      if iname not in hyper.ListInstances():
1186
        return
1187

    
1188
      try:
1189
        hyper.StopInstance(instance, retry=self.tried_once)
1190
      except errors.HypervisorError, err:
1191
        if iname not in hyper.ListInstances():
1192
          # if the instance is no longer existing, consider this a
1193
          # success and go to cleanup
1194
          return
1195

    
1196
        _Fail("Failed to stop instance %s: %s", iname, err)
1197

    
1198
      self.tried_once = True
1199

    
1200
      raise utils.RetryAgain()
1201

    
1202
  try:
1203
    utils.Retry(_TryShutdown(), 5, timeout)
1204
  except utils.RetryTimeout:
1205
    # the shutdown did not succeed
1206
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1207

    
1208
    try:
1209
      hyper.StopInstance(instance, force=True)
1210
    except errors.HypervisorError, err:
1211
      if iname in hyper.ListInstances():
1212
        # only raise an error if the instance still exists, otherwise
1213
        # the error could simply be "instance ... unknown"!
1214
        _Fail("Failed to force stop instance %s: %s", iname, err)
1215

    
1216
    time.sleep(1)
1217

    
1218
    if iname in hyper.ListInstances():
1219
      _Fail("Could not shutdown instance %s even by destroy", iname)
1220

    
1221
  try:
1222
    hyper.CleanupInstance(instance.name)
1223
  except errors.HypervisorError, err:
1224
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1225

    
1226
  _RemoveBlockDevLinks(iname, instance.disks)
1227

    
1228

    
1229
def InstanceReboot(instance, reboot_type, shutdown_timeout):
1230
  """Reboot an instance.
1231

1232
  @type instance: L{objects.Instance}
1233
  @param instance: the instance object to reboot
1234
  @type reboot_type: str
1235
  @param reboot_type: the type of reboot, one the following
1236
    constants:
1237
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1238
        instance OS, do not recreate the VM
1239
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1240
        restart the VM (at the hypervisor level)
1241
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1242
        not accepted here, since that mode is handled differently, in
1243
        cmdlib, and translates into full stop and start of the
1244
        instance (instead of a call_instance_reboot RPC)
1245
  @type shutdown_timeout: integer
1246
  @param shutdown_timeout: maximum timeout for soft shutdown
1247
  @rtype: None
1248

1249
  """
1250
  running_instances = GetInstanceList([instance.hypervisor])
1251

    
1252
  if instance.name not in running_instances:
1253
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1254

    
1255
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1256
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1257
    try:
1258
      hyper.RebootInstance(instance)
1259
    except errors.HypervisorError, err:
1260
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1261
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1262
    try:
1263
      InstanceShutdown(instance, shutdown_timeout)
1264
      return StartInstance(instance, False)
1265
    except errors.HypervisorError, err:
1266
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1267
  else:
1268
    _Fail("Invalid reboot_type received: %s", reboot_type)
1269

    
1270

    
1271
def MigrationInfo(instance):
1272
  """Gather information about an instance to be migrated.
1273

1274
  @type instance: L{objects.Instance}
1275
  @param instance: the instance definition
1276

1277
  """
1278
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1279
  try:
1280
    info = hyper.MigrationInfo(instance)
1281
  except errors.HypervisorError, err:
1282
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1283
  return info
1284

    
1285

    
1286
def AcceptInstance(instance, info, target):
1287
  """Prepare the node to accept an instance.
1288

1289
  @type instance: L{objects.Instance}
1290
  @param instance: the instance definition
1291
  @type info: string/data (opaque)
1292
  @param info: migration information, from the source node
1293
  @type target: string
1294
  @param target: target host (usually ip), on this node
1295

1296
  """
1297
  # TODO: why is this required only for DTS_EXT_MIRROR?
1298
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1299
    # Create the symlinks, as the disks are not active
1300
    # in any way
1301
    try:
1302
      _GatherAndLinkBlockDevs(instance)
1303
    except errors.BlockDeviceError, err:
1304
      _Fail("Block device error: %s", err, exc=True)
1305

    
1306
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1307
  try:
1308
    hyper.AcceptInstance(instance, info, target)
1309
  except errors.HypervisorError, err:
1310
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1311
      _RemoveBlockDevLinks(instance.name, instance.disks)
1312
    _Fail("Failed to accept instance: %s", err, exc=True)
1313

    
1314

    
1315
def FinalizeMigrationDst(instance, info, success):
1316
  """Finalize any preparation to accept an instance.
1317

1318
  @type instance: L{objects.Instance}
1319
  @param instance: the instance definition
1320
  @type info: string/data (opaque)
1321
  @param info: migration information, from the source node
1322
  @type success: boolean
1323
  @param success: whether the migration was a success or a failure
1324

1325
  """
1326
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1327
  try:
1328
    hyper.FinalizeMigrationDst(instance, info, success)
1329
  except errors.HypervisorError, err:
1330
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1331

    
1332

    
1333
def MigrateInstance(instance, target, live):
1334
  """Migrates an instance to another node.
1335

1336
  @type instance: L{objects.Instance}
1337
  @param instance: the instance definition
1338
  @type target: string
1339
  @param target: the target node name
1340
  @type live: boolean
1341
  @param live: whether the migration should be done live or not (the
1342
      interpretation of this parameter is left to the hypervisor)
1343
  @raise RPCFail: if migration fails for some reason
1344

1345
  """
1346
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1347

    
1348
  try:
1349
    hyper.MigrateInstance(instance, target, live)
1350
  except errors.HypervisorError, err:
1351
    _Fail("Failed to migrate instance: %s", err, exc=True)
1352

    
1353

    
1354
def FinalizeMigrationSource(instance, success, live):
1355
  """Finalize the instance migration on the source node.
1356

1357
  @type instance: L{objects.Instance}
1358
  @param instance: the instance definition of the migrated instance
1359
  @type success: bool
1360
  @param success: whether the migration succeeded or not
1361
  @type live: bool
1362
  @param live: whether the user requested a live migration or not
1363
  @raise RPCFail: If the execution fails for some reason
1364

1365
  """
1366
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1367

    
1368
  try:
1369
    hyper.FinalizeMigrationSource(instance, success, live)
1370
  except Exception, err:  # pylint: disable=W0703
1371
    _Fail("Failed to finalize the migration on the source node: %s", err,
1372
          exc=True)
1373

    
1374

    
1375
def GetMigrationStatus(instance):
1376
  """Get the migration status
1377

1378
  @type instance: L{objects.Instance}
1379
  @param instance: the instance that is being migrated
1380
  @rtype: L{objects.MigrationStatus}
1381
  @return: the status of the current migration (one of
1382
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1383
           progress info that can be retrieved from the hypervisor
1384
  @raise RPCFail: If the migration status cannot be retrieved
1385

1386
  """
1387
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1388
  try:
1389
    return hyper.GetMigrationStatus(instance)
1390
  except Exception, err:  # pylint: disable=W0703
1391
    _Fail("Failed to get migration status: %s", err, exc=True)
1392

    
1393

    
1394
def BlockdevCreate(disk, size, owner, on_primary, info):
1395
  """Creates a block device for an instance.
1396

1397
  @type disk: L{objects.Disk}
1398
  @param disk: the object describing the disk we should create
1399
  @type size: int
1400
  @param size: the size of the physical underlying device, in MiB
1401
  @type owner: str
1402
  @param owner: the name of the instance for which disk is created,
1403
      used for device cache data
1404
  @type on_primary: boolean
1405
  @param on_primary:  indicates if it is the primary node or not
1406
  @type info: string
1407
  @param info: string that will be sent to the physical device
1408
      creation, used for example to set (LVM) tags on LVs
1409

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

1414
  """
1415
  # TODO: remove the obsolete "size" argument
1416
  # pylint: disable=W0613
1417
  clist = []
1418
  if disk.children:
1419
    for child in disk.children:
1420
      try:
1421
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1422
      except errors.BlockDeviceError, err:
1423
        _Fail("Can't assemble device %s: %s", child, err)
1424
      if on_primary or disk.AssembleOnSecondary():
1425
        # we need the children open in case the device itself has to
1426
        # be assembled
1427
        try:
1428
          # pylint: disable=E1103
1429
          crdev.Open()
1430
        except errors.BlockDeviceError, err:
1431
          _Fail("Can't make child '%s' read-write: %s", child, err)
1432
      clist.append(crdev)
1433

    
1434
  try:
1435
    device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
1436
  except errors.BlockDeviceError, err:
1437
    _Fail("Can't create block device: %s", err)
1438

    
1439
  if on_primary or disk.AssembleOnSecondary():
1440
    try:
1441
      device.Assemble()
1442
    except errors.BlockDeviceError, err:
1443
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1444
    device.SetSyncSpeed(constants.SYNC_SPEED)
1445
    if on_primary or disk.OpenOnSecondary():
1446
      try:
1447
        device.Open(force=True)
1448
      except errors.BlockDeviceError, err:
1449
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1450
    DevCacheManager.UpdateCache(device.dev_path, owner,
1451
                                on_primary, disk.iv_name)
1452

    
1453
  device.SetInfo(info)
1454

    
1455
  return device.unique_id
1456

    
1457

    
1458
def _WipeDevice(path, offset, size):
1459
  """This function actually wipes the device.
1460

1461
  @param path: The path to the device to wipe
1462
  @param offset: The offset in MiB in the file
1463
  @param size: The size in MiB to write
1464

1465
  """
1466
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1467
         "bs=%d" % constants.WIPE_BLOCK_SIZE, "oflag=direct", "of=%s" % path,
1468
         "count=%d" % size]
1469
  result = utils.RunCmd(cmd)
1470

    
1471
  if result.failed:
1472
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1473
          result.fail_reason, result.output)
1474

    
1475

    
1476
def BlockdevWipe(disk, offset, size):
1477
  """Wipes a block device.
1478

1479
  @type disk: L{objects.Disk}
1480
  @param disk: the disk object we want to wipe
1481
  @type offset: int
1482
  @param offset: The offset in MiB in the file
1483
  @type size: int
1484
  @param size: The size in MiB to write
1485

1486
  """
1487
  try:
1488
    rdev = _RecursiveFindBD(disk)
1489
  except errors.BlockDeviceError:
1490
    rdev = None
1491

    
1492
  if not rdev:
1493
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1494

    
1495
  # Do cross verify some of the parameters
1496
  if offset > rdev.size:
1497
    _Fail("Offset is bigger than device size")
1498
  if (offset + size) > rdev.size:
1499
    _Fail("The provided offset and size to wipe is bigger than device size")
1500

    
1501
  _WipeDevice(rdev.dev_path, offset, size)
1502

    
1503

    
1504
def BlockdevPauseResumeSync(disks, pause):
1505
  """Pause or resume the sync of the block device.
1506

1507
  @type disks: list of L{objects.Disk}
1508
  @param disks: the disks object we want to pause/resume
1509
  @type pause: bool
1510
  @param pause: Wheater to pause or resume
1511

1512
  """
1513
  success = []
1514
  for disk in disks:
1515
    try:
1516
      rdev = _RecursiveFindBD(disk)
1517
    except errors.BlockDeviceError:
1518
      rdev = None
1519

    
1520
    if not rdev:
1521
      success.append((False, ("Cannot change sync for device %s:"
1522
                              " device not found" % disk.iv_name)))
1523
      continue
1524

    
1525
    result = rdev.PauseResumeSync(pause)
1526

    
1527
    if result:
1528
      success.append((result, None))
1529
    else:
1530
      if pause:
1531
        msg = "Pause"
1532
      else:
1533
        msg = "Resume"
1534
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1535

    
1536
  return success
1537

    
1538

    
1539
def BlockdevRemove(disk):
1540
  """Remove a block device.
1541

1542
  @note: This is intended to be called recursively.
1543

1544
  @type disk: L{objects.Disk}
1545
  @param disk: the disk object we should remove
1546
  @rtype: boolean
1547
  @return: the success of the operation
1548

1549
  """
1550
  msgs = []
1551
  try:
1552
    rdev = _RecursiveFindBD(disk)
1553
  except errors.BlockDeviceError, err:
1554
    # probably can't attach
1555
    logging.info("Can't attach to device %s in remove", disk)
1556
    rdev = None
1557
  if rdev is not None:
1558
    r_path = rdev.dev_path
1559
    try:
1560
      rdev.Remove()
1561
    except errors.BlockDeviceError, err:
1562
      msgs.append(str(err))
1563
    if not msgs:
1564
      DevCacheManager.RemoveCache(r_path)
1565

    
1566
  if disk.children:
1567
    for child in disk.children:
1568
      try:
1569
        BlockdevRemove(child)
1570
      except RPCFail, err:
1571
        msgs.append(str(err))
1572

    
1573
  if msgs:
1574
    _Fail("; ".join(msgs))
1575

    
1576

    
1577
def _RecursiveAssembleBD(disk, owner, as_primary):
1578
  """Activate a block device for an instance.
1579

1580
  This is run on the primary and secondary nodes for an instance.
1581

1582
  @note: this function is called recursively.
1583

1584
  @type disk: L{objects.Disk}
1585
  @param disk: the disk we try to assemble
1586
  @type owner: str
1587
  @param owner: the name of the instance which owns the disk
1588
  @type as_primary: boolean
1589
  @param as_primary: if we should make the block device
1590
      read/write
1591

1592
  @return: the assembled device or None (in case no device
1593
      was assembled)
1594
  @raise errors.BlockDeviceError: in case there is an error
1595
      during the activation of the children or the device
1596
      itself
1597

1598
  """
1599
  children = []
1600
  if disk.children:
1601
    mcn = disk.ChildrenNeeded()
1602
    if mcn == -1:
1603
      mcn = 0 # max number of Nones allowed
1604
    else:
1605
      mcn = len(disk.children) - mcn # max number of Nones
1606
    for chld_disk in disk.children:
1607
      try:
1608
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1609
      except errors.BlockDeviceError, err:
1610
        if children.count(None) >= mcn:
1611
          raise
1612
        cdev = None
1613
        logging.error("Error in child activation (but continuing): %s",
1614
                      str(err))
1615
      children.append(cdev)
1616

    
1617
  if as_primary or disk.AssembleOnSecondary():
1618
    r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
1619
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1620
    result = r_dev
1621
    if as_primary or disk.OpenOnSecondary():
1622
      r_dev.Open()
1623
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1624
                                as_primary, disk.iv_name)
1625

    
1626
  else:
1627
    result = True
1628
  return result
1629

    
1630

    
1631
def BlockdevAssemble(disk, owner, as_primary, idx):
1632
  """Activate a block device for an instance.
1633

1634
  This is a wrapper over _RecursiveAssembleBD.
1635

1636
  @rtype: str or boolean
1637
  @return: a C{/dev/...} path for primary nodes, and
1638
      C{True} for secondary nodes
1639

1640
  """
1641
  try:
1642
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1643
    if isinstance(result, bdev.BlockDev):
1644
      # pylint: disable=E1103
1645
      result = result.dev_path
1646
      if as_primary:
1647
        _SymlinkBlockDev(owner, result, idx)
1648
  except errors.BlockDeviceError, err:
1649
    _Fail("Error while assembling disk: %s", err, exc=True)
1650
  except OSError, err:
1651
    _Fail("Error while symlinking disk: %s", err, exc=True)
1652

    
1653
  return result
1654

    
1655

    
1656
def BlockdevShutdown(disk):
1657
  """Shut down a block device.
1658

1659
  First, if the device is assembled (Attach() is successful), then
1660
  the device is shutdown. Then the children of the device are
1661
  shutdown.
1662

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

1667
  @type disk: L{objects.Disk}
1668
  @param disk: the description of the disk we should
1669
      shutdown
1670
  @rtype: None
1671

1672
  """
1673
  msgs = []
1674
  r_dev = _RecursiveFindBD(disk)
1675
  if r_dev is not None:
1676
    r_path = r_dev.dev_path
1677
    try:
1678
      r_dev.Shutdown()
1679
      DevCacheManager.RemoveCache(r_path)
1680
    except errors.BlockDeviceError, err:
1681
      msgs.append(str(err))
1682

    
1683
  if disk.children:
1684
    for child in disk.children:
1685
      try:
1686
        BlockdevShutdown(child)
1687
      except RPCFail, err:
1688
        msgs.append(str(err))
1689

    
1690
  if msgs:
1691
    _Fail("; ".join(msgs))
1692

    
1693

    
1694
def BlockdevAddchildren(parent_cdev, new_cdevs):
1695
  """Extend a mirrored block device.
1696

1697
  @type parent_cdev: L{objects.Disk}
1698
  @param parent_cdev: the disk to which we should add children
1699
  @type new_cdevs: list of L{objects.Disk}
1700
  @param new_cdevs: the list of children which we should add
1701
  @rtype: None
1702

1703
  """
1704
  parent_bdev = _RecursiveFindBD(parent_cdev)
1705
  if parent_bdev is None:
1706
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1707
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1708
  if new_bdevs.count(None) > 0:
1709
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1710
  parent_bdev.AddChildren(new_bdevs)
1711

    
1712

    
1713
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1714
  """Shrink a mirrored block device.
1715

1716
  @type parent_cdev: L{objects.Disk}
1717
  @param parent_cdev: the disk from which we should remove children
1718
  @type new_cdevs: list of L{objects.Disk}
1719
  @param new_cdevs: the list of children which we should remove
1720
  @rtype: None
1721

1722
  """
1723
  parent_bdev = _RecursiveFindBD(parent_cdev)
1724
  if parent_bdev is None:
1725
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1726
  devs = []
1727
  for disk in new_cdevs:
1728
    rpath = disk.StaticDevPath()
1729
    if rpath is None:
1730
      bd = _RecursiveFindBD(disk)
1731
      if bd is None:
1732
        _Fail("Can't find device %s while removing children", disk)
1733
      else:
1734
        devs.append(bd.dev_path)
1735
    else:
1736
      if not utils.IsNormAbsPath(rpath):
1737
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
1738
      devs.append(rpath)
1739
  parent_bdev.RemoveChildren(devs)
1740

    
1741

    
1742
def BlockdevGetmirrorstatus(disks):
1743
  """Get the mirroring status of a list of devices.
1744

1745
  @type disks: list of L{objects.Disk}
1746
  @param disks: the list of disks which we should query
1747
  @rtype: disk
1748
  @return: List of L{objects.BlockDevStatus}, one for each disk
1749
  @raise errors.BlockDeviceError: if any of the disks cannot be
1750
      found
1751

1752
  """
1753
  stats = []
1754
  for dsk in disks:
1755
    rbd = _RecursiveFindBD(dsk)
1756
    if rbd is None:
1757
      _Fail("Can't find device %s", dsk)
1758

    
1759
    stats.append(rbd.CombinedSyncStatus())
1760

    
1761
  return stats
1762

    
1763

    
1764
def BlockdevGetmirrorstatusMulti(disks):
1765
  """Get the mirroring status of a list of devices.
1766

1767
  @type disks: list of L{objects.Disk}
1768
  @param disks: the list of disks which we should query
1769
  @rtype: disk
1770
  @return: List of tuples, (bool, status), one for each disk; bool denotes
1771
    success/failure, status is L{objects.BlockDevStatus} on success, string
1772
    otherwise
1773

1774
  """
1775
  result = []
1776
  for disk in disks:
1777
    try:
1778
      rbd = _RecursiveFindBD(disk)
1779
      if rbd is None:
1780
        result.append((False, "Can't find device %s" % disk))
1781
        continue
1782

    
1783
      status = rbd.CombinedSyncStatus()
1784
    except errors.BlockDeviceError, err:
1785
      logging.exception("Error while getting disk status")
1786
      result.append((False, str(err)))
1787
    else:
1788
      result.append((True, status))
1789

    
1790
  assert len(disks) == len(result)
1791

    
1792
  return result
1793

    
1794

    
1795
def _RecursiveFindBD(disk):
1796
  """Check if a device is activated.
1797

1798
  If so, return information about the real device.
1799

1800
  @type disk: L{objects.Disk}
1801
  @param disk: the disk object we need to find
1802

1803
  @return: None if the device can't be found,
1804
      otherwise the device instance
1805

1806
  """
1807
  children = []
1808
  if disk.children:
1809
    for chdisk in disk.children:
1810
      children.append(_RecursiveFindBD(chdisk))
1811

    
1812
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1813

    
1814

    
1815
def _OpenRealBD(disk):
1816
  """Opens the underlying block device of a disk.
1817

1818
  @type disk: L{objects.Disk}
1819
  @param disk: the disk object we want to open
1820

1821
  """
1822
  real_disk = _RecursiveFindBD(disk)
1823
  if real_disk is None:
1824
    _Fail("Block device '%s' is not set up", disk)
1825

    
1826
  real_disk.Open()
1827

    
1828
  return real_disk
1829

    
1830

    
1831
def BlockdevFind(disk):
1832
  """Check if a device is activated.
1833

1834
  If it is, return information about the real device.
1835

1836
  @type disk: L{objects.Disk}
1837
  @param disk: the disk to find
1838
  @rtype: None or objects.BlockDevStatus
1839
  @return: None if the disk cannot be found, otherwise a the current
1840
           information
1841

1842
  """
1843
  try:
1844
    rbd = _RecursiveFindBD(disk)
1845
  except errors.BlockDeviceError, err:
1846
    _Fail("Failed to find device: %s", err, exc=True)
1847

    
1848
  if rbd is None:
1849
    return None
1850

    
1851
  return rbd.GetSyncStatus()
1852

    
1853

    
1854
def BlockdevGetsize(disks):
1855
  """Computes the size of the given disks.
1856

1857
  If a disk is not found, returns None instead.
1858

1859
  @type disks: list of L{objects.Disk}
1860
  @param disks: the list of disk to compute the size for
1861
  @rtype: list
1862
  @return: list with elements None if the disk cannot be found,
1863
      otherwise the size
1864

1865
  """
1866
  result = []
1867
  for cf in disks:
1868
    try:
1869
      rbd = _RecursiveFindBD(cf)
1870
    except errors.BlockDeviceError:
1871
      result.append(None)
1872
      continue
1873
    if rbd is None:
1874
      result.append(None)
1875
    else:
1876
      result.append(rbd.GetActualSize())
1877
  return result
1878

    
1879

    
1880
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
1881
  """Export a block device to a remote node.
1882

1883
  @type disk: L{objects.Disk}
1884
  @param disk: the description of the disk to export
1885
  @type dest_node: str
1886
  @param dest_node: the destination node to export to
1887
  @type dest_path: str
1888
  @param dest_path: the destination path on the target node
1889
  @type cluster_name: str
1890
  @param cluster_name: the cluster name, needed for SSH hostalias
1891
  @rtype: None
1892

1893
  """
1894
  real_disk = _OpenRealBD(disk)
1895

    
1896
  # the block size on the read dd is 1MiB to match our units
1897
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
1898
                               "dd if=%s bs=1048576 count=%s",
1899
                               real_disk.dev_path, str(disk.size))
1900

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

    
1910
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1911
                                                   constants.GANETI_RUNAS,
1912
                                                   destcmd)
1913

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

    
1917
  result = utils.RunCmd(["bash", "-c", command])
1918

    
1919
  if result.failed:
1920
    _Fail("Disk copy command '%s' returned error: %s"
1921
          " output: %s", command, result.fail_reason, result.output)
1922

    
1923

    
1924
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1925
  """Write a file to the filesystem.
1926

1927
  This allows the master to overwrite(!) a file. It will only perform
1928
  the operation if the file belongs to a list of configuration files.
1929

1930
  @type file_name: str
1931
  @param file_name: the target file name
1932
  @type data: str
1933
  @param data: the new contents of the file
1934
  @type mode: int
1935
  @param mode: the mode to give the file (can be None)
1936
  @type uid: string
1937
  @param uid: the owner of the file
1938
  @type gid: string
1939
  @param gid: the group of the file
1940
  @type atime: float
1941
  @param atime: the atime to set on the file (can be None)
1942
  @type mtime: float
1943
  @param mtime: the mtime to set on the file (can be None)
1944
  @rtype: None
1945

1946
  """
1947
  if not os.path.isabs(file_name):
1948
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
1949

    
1950
  if file_name not in _ALLOWED_UPLOAD_FILES:
1951
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
1952
          file_name)
1953

    
1954
  raw_data = _Decompress(data)
1955

    
1956
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
1957
    _Fail("Invalid username/groupname type")
1958

    
1959
  getents = runtime.GetEnts()
1960
  uid = getents.LookupUser(uid)
1961
  gid = getents.LookupGroup(gid)
1962

    
1963
  utils.SafeWriteFile(file_name, None,
1964
                      data=raw_data, mode=mode, uid=uid, gid=gid,
1965
                      atime=atime, mtime=mtime)
1966

    
1967

    
1968
def RunOob(oob_program, command, node, timeout):
1969
  """Executes oob_program with given command on given node.
1970

1971
  @param oob_program: The path to the executable oob_program
1972
  @param command: The command to invoke on oob_program
1973
  @param node: The node given as an argument to the program
1974
  @param timeout: Timeout after which we kill the oob program
1975

1976
  @return: stdout
1977
  @raise RPCFail: If execution fails for some reason
1978

1979
  """
1980
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
1981

    
1982
  if result.failed:
1983
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
1984
          result.fail_reason, result.output)
1985

    
1986
  return result.stdout
1987

    
1988

    
1989
def WriteSsconfFiles(values):
1990
  """Update all ssconf files.
1991

1992
  Wrapper around the SimpleStore.WriteFiles.
1993

1994
  """
1995
  ssconf.SimpleStore().WriteFiles(values)
1996

    
1997

    
1998
def _ErrnoOrStr(err):
1999
  """Format an EnvironmentError exception.
2000

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

2005
  @type err: L{EnvironmentError}
2006
  @param err: the exception to format
2007

2008
  """
2009
  if hasattr(err, "errno"):
2010
    detail = errno.errorcode[err.errno]
2011
  else:
2012
    detail = str(err)
2013
  return detail
2014

    
2015

    
2016
def _OSOndiskAPIVersion(os_dir):
2017
  """Compute and return the API version of a given OS.
2018

2019
  This function will try to read the API version of the OS residing in
2020
  the 'os_dir' directory.
2021

2022
  @type os_dir: str
2023
  @param os_dir: the directory in which we should look for the OS
2024
  @rtype: tuple
2025
  @return: tuple (status, data) with status denoting the validity and
2026
      data holding either the vaid versions or an error message
2027

2028
  """
2029
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2030

    
2031
  try:
2032
    st = os.stat(api_file)
2033
  except EnvironmentError, err:
2034
    return False, ("Required file '%s' not found under path %s: %s" %
2035
                   (constants.OS_API_FILE, os_dir, _ErrnoOrStr(err)))
2036

    
2037
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2038
    return False, ("File '%s' in %s is not a regular file" %
2039
                   (constants.OS_API_FILE, os_dir))
2040

    
2041
  try:
2042
    api_versions = utils.ReadFile(api_file).splitlines()
2043
  except EnvironmentError, err:
2044
    return False, ("Error while reading the API version file at %s: %s" %
2045
                   (api_file, _ErrnoOrStr(err)))
2046

    
2047
  try:
2048
    api_versions = [int(version.strip()) for version in api_versions]
2049
  except (TypeError, ValueError), err:
2050
    return False, ("API version(s) can't be converted to integer: %s" %
2051
                   str(err))
2052

    
2053
  return True, api_versions
2054

    
2055

    
2056
def DiagnoseOS(top_dirs=None):
2057
  """Compute the validity for all OSes.
2058

2059
  @type top_dirs: list
2060
  @param top_dirs: the list of directories in which to
2061
      search (if not given defaults to
2062
      L{constants.OS_SEARCH_PATH})
2063
  @rtype: list of L{objects.OS}
2064
  @return: a list of tuples (name, path, status, diagnose, variants,
2065
      parameters, api_version) for all (potential) OSes under all
2066
      search paths, where:
2067
          - name is the (potential) OS name
2068
          - path is the full path to the OS
2069
          - status True/False is the validity of the OS
2070
          - diagnose is the error message for an invalid OS, otherwise empty
2071
          - variants is a list of supported OS variants, if any
2072
          - parameters is a list of (name, help) parameters, if any
2073
          - api_version is a list of support OS API versions
2074

2075
  """
2076
  if top_dirs is None:
2077
    top_dirs = constants.OS_SEARCH_PATH
2078

    
2079
  result = []
2080
  for dir_name in top_dirs:
2081
    if os.path.isdir(dir_name):
2082
      try:
2083
        f_names = utils.ListVisibleFiles(dir_name)
2084
      except EnvironmentError, err:
2085
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2086
        break
2087
      for name in f_names:
2088
        os_path = utils.PathJoin(dir_name, name)
2089
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2090
        if status:
2091
          diagnose = ""
2092
          variants = os_inst.supported_variants
2093
          parameters = os_inst.supported_parameters
2094
          api_versions = os_inst.api_versions
2095
        else:
2096
          diagnose = os_inst
2097
          variants = parameters = api_versions = []
2098
        result.append((name, os_path, status, diagnose, variants,
2099
                       parameters, api_versions))
2100

    
2101
  return result
2102

    
2103

    
2104
def _TryOSFromDisk(name, base_dir=None):
2105
  """Create an OS instance from disk.
2106

2107
  This function will return an OS instance if the given name is a
2108
  valid OS name.
2109

2110
  @type base_dir: string
2111
  @keyword base_dir: Base directory containing OS installations.
2112
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2113
  @rtype: tuple
2114
  @return: success and either the OS instance if we find a valid one,
2115
      or error message
2116

2117
  """
2118
  if base_dir is None:
2119
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
2120
  else:
2121
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2122

    
2123
  if os_dir is None:
2124
    return False, "Directory for OS %s not found in search path" % name
2125

    
2126
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2127
  if not status:
2128
    # push the error up
2129
    return status, api_versions
2130

    
2131
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2132
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2133
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2134

    
2135
  # OS Files dictionary, we will populate it with the absolute path
2136
  # names; if the value is True, then it is a required file, otherwise
2137
  # an optional one
2138
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2139

    
2140
  if max(api_versions) >= constants.OS_API_V15:
2141
    os_files[constants.OS_VARIANTS_FILE] = False
2142

    
2143
  if max(api_versions) >= constants.OS_API_V20:
2144
    os_files[constants.OS_PARAMETERS_FILE] = True
2145
  else:
2146
    del os_files[constants.OS_SCRIPT_VERIFY]
2147

    
2148
  for (filename, required) in os_files.items():
2149
    os_files[filename] = utils.PathJoin(os_dir, filename)
2150

    
2151
    try:
2152
      st = os.stat(os_files[filename])
2153
    except EnvironmentError, err:
2154
      if err.errno == errno.ENOENT and not required:
2155
        del os_files[filename]
2156
        continue
2157
      return False, ("File '%s' under path '%s' is missing (%s)" %
2158
                     (filename, os_dir, _ErrnoOrStr(err)))
2159

    
2160
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2161
      return False, ("File '%s' under path '%s' is not a regular file" %
2162
                     (filename, os_dir))
2163

    
2164
    if filename in constants.OS_SCRIPTS:
2165
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2166
        return False, ("File '%s' under path '%s' is not executable" %
2167
                       (filename, os_dir))
2168

    
2169
  variants = []
2170
  if constants.OS_VARIANTS_FILE in os_files:
2171
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2172
    try:
2173
      variants = utils.ReadFile(variants_file).splitlines()
2174
    except EnvironmentError, err:
2175
      # we accept missing files, but not other errors
2176
      if err.errno != errno.ENOENT:
2177
        return False, ("Error while reading the OS variants file at %s: %s" %
2178
                       (variants_file, _ErrnoOrStr(err)))
2179

    
2180
  parameters = []
2181
  if constants.OS_PARAMETERS_FILE in os_files:
2182
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2183
    try:
2184
      parameters = utils.ReadFile(parameters_file).splitlines()
2185
    except EnvironmentError, err:
2186
      return False, ("Error while reading the OS parameters file at %s: %s" %
2187
                     (parameters_file, _ErrnoOrStr(err)))
2188
    parameters = [v.split(None, 1) for v in parameters]
2189

    
2190
  os_obj = objects.OS(name=name, path=os_dir,
2191
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2192
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2193
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2194
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2195
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2196
                                                 None),
2197
                      supported_variants=variants,
2198
                      supported_parameters=parameters,
2199
                      api_versions=api_versions)
2200
  return True, os_obj
2201

    
2202

    
2203
def OSFromDisk(name, base_dir=None):
2204
  """Create an OS instance from disk.
2205

2206
  This function will return an OS instance if the given name is a
2207
  valid OS name. Otherwise, it will raise an appropriate
2208
  L{RPCFail} exception, detailing why this is not a valid OS.
2209

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

2213
  @type base_dir: string
2214
  @keyword base_dir: Base directory containing OS installations.
2215
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2216
  @rtype: L{objects.OS}
2217
  @return: the OS instance if we find a valid one
2218
  @raise RPCFail: if we don't find a valid OS
2219

2220
  """
2221
  name_only = objects.OS.GetName(name)
2222
  status, payload = _TryOSFromDisk(name_only, base_dir)
2223

    
2224
  if not status:
2225
    _Fail(payload)
2226

    
2227
  return payload
2228

    
2229

    
2230
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2231
  """Calculate the basic environment for an os script.
2232

2233
  @type os_name: str
2234
  @param os_name: full operating system name (including variant)
2235
  @type inst_os: L{objects.OS}
2236
  @param inst_os: operating system for which the environment is being built
2237
  @type os_params: dict
2238
  @param os_params: the OS parameters
2239
  @type debug: integer
2240
  @param debug: debug level (0 or 1, for OS Api 10)
2241
  @rtype: dict
2242
  @return: dict of environment variables
2243
  @raise errors.BlockDeviceError: if the block device
2244
      cannot be found
2245

2246
  """
2247
  result = {}
2248
  api_version = \
2249
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2250
  result["OS_API_VERSION"] = "%d" % api_version
2251
  result["OS_NAME"] = inst_os.name
2252
  result["DEBUG_LEVEL"] = "%d" % debug
2253

    
2254
  # OS variants
2255
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2256
    variant = objects.OS.GetVariant(os_name)
2257
    if not variant:
2258
      variant = inst_os.supported_variants[0]
2259
  else:
2260
    variant = ""
2261
  result["OS_VARIANT"] = variant
2262

    
2263
  # OS params
2264
  for pname, pvalue in os_params.items():
2265
    result["OSP_%s" % pname.upper()] = pvalue
2266

    
2267
  return result
2268

    
2269

    
2270
def OSEnvironment(instance, inst_os, debug=0):
2271
  """Calculate the environment for an os script.
2272

2273
  @type instance: L{objects.Instance}
2274
  @param instance: target instance for the os script run
2275
  @type inst_os: L{objects.OS}
2276
  @param inst_os: operating system for which the environment is being built
2277
  @type debug: integer
2278
  @param debug: debug level (0 or 1, for OS Api 10)
2279
  @rtype: dict
2280
  @return: dict of environment variables
2281
  @raise errors.BlockDeviceError: if the block device
2282
      cannot be found
2283

2284
  """
2285
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2286

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

    
2290
  result["HYPERVISOR"] = instance.hypervisor
2291
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2292
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2293
  result["INSTANCE_SECONDARY_NODES"] = \
2294
      ("%s" % " ".join(instance.secondary_nodes))
2295

    
2296
  # Disks
2297
  for idx, disk in enumerate(instance.disks):
2298
    real_disk = _OpenRealBD(disk)
2299
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2300
    result["DISK_%d_ACCESS" % idx] = disk.mode
2301
    if constants.HV_DISK_TYPE in instance.hvparams:
2302
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2303
        instance.hvparams[constants.HV_DISK_TYPE]
2304
    if disk.dev_type in constants.LDS_BLOCK:
2305
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2306
    elif disk.dev_type == constants.LD_FILE:
2307
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2308
        "file:%s" % disk.physical_id[0]
2309

    
2310
  # NICs
2311
  for idx, nic in enumerate(instance.nics):
2312
    result["NIC_%d_MAC" % idx] = nic.mac
2313
    if nic.ip:
2314
      result["NIC_%d_IP" % idx] = nic.ip
2315
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2316
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2317
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2318
    if nic.nicparams[constants.NIC_LINK]:
2319
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2320
    if constants.HV_NIC_TYPE in instance.hvparams:
2321
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2322
        instance.hvparams[constants.HV_NIC_TYPE]
2323

    
2324
  # HV/BE params
2325
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2326
    for key, value in source.items():
2327
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2328

    
2329
  return result
2330

    
2331

    
2332
def BlockdevGrow(disk, amount, dryrun):
2333
  """Grow a stack of block devices.
2334

2335
  This function is called recursively, with the childrens being the
2336
  first ones to resize.
2337

2338
  @type disk: L{objects.Disk}
2339
  @param disk: the disk to be grown
2340
  @type amount: integer
2341
  @param amount: the amount (in mebibytes) to grow with
2342
  @type dryrun: boolean
2343
  @param dryrun: whether to execute the operation in simulation mode
2344
      only, without actually increasing the size
2345
  @rtype: (status, result)
2346
  @return: a tuple with the status of the operation (True/False), and
2347
      the errors message if status is False
2348

2349
  """
2350
  r_dev = _RecursiveFindBD(disk)
2351
  if r_dev is None:
2352
    _Fail("Cannot find block device %s", disk)
2353

    
2354
  try:
2355
    r_dev.Grow(amount, dryrun)
2356
  except errors.BlockDeviceError, err:
2357
    _Fail("Failed to grow block device: %s", err, exc=True)
2358

    
2359

    
2360
def BlockdevSnapshot(disk):
2361
  """Create a snapshot copy of a block device.
2362

2363
  This function is called recursively, and the snapshot is actually created
2364
  just for the leaf lvm backend device.
2365

2366
  @type disk: L{objects.Disk}
2367
  @param disk: the disk to be snapshotted
2368
  @rtype: string
2369
  @return: snapshot disk ID as (vg, lv)
2370

2371
  """
2372
  if disk.dev_type == constants.LD_DRBD8:
2373
    if not disk.children:
2374
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2375
            disk.unique_id)
2376
    return BlockdevSnapshot(disk.children[0])
2377
  elif disk.dev_type == constants.LD_LV:
2378
    r_dev = _RecursiveFindBD(disk)
2379
    if r_dev is not None:
2380
      # FIXME: choose a saner value for the snapshot size
2381
      # let's stay on the safe side and ask for the full size, for now
2382
      return r_dev.Snapshot(disk.size)
2383
    else:
2384
      _Fail("Cannot find block device %s", disk)
2385
  else:
2386
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2387
          disk.unique_id, disk.dev_type)
2388

    
2389

    
2390
def FinalizeExport(instance, snap_disks):
2391
  """Write out the export configuration information.
2392

2393
  @type instance: L{objects.Instance}
2394
  @param instance: the instance which we export, used for
2395
      saving configuration
2396
  @type snap_disks: list of L{objects.Disk}
2397
  @param snap_disks: list of snapshot block devices, which
2398
      will be used to get the actual name of the dump file
2399

2400
  @rtype: None
2401

2402
  """
2403
  destdir = utils.PathJoin(constants.EXPORT_DIR, instance.name + ".new")
2404
  finaldestdir = utils.PathJoin(constants.EXPORT_DIR, instance.name)
2405

    
2406
  config = objects.SerializableConfigParser()
2407

    
2408
  config.add_section(constants.INISECT_EXP)
2409
  config.set(constants.INISECT_EXP, "version", "0")
2410
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2411
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2412
  config.set(constants.INISECT_EXP, "os", instance.os)
2413
  config.set(constants.INISECT_EXP, "compression", "none")
2414

    
2415
  config.add_section(constants.INISECT_INS)
2416
  config.set(constants.INISECT_INS, "name", instance.name)
2417
  config.set(constants.INISECT_INS, "memory", "%d" %
2418
             instance.beparams[constants.BE_MEMORY])
2419
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2420
             instance.beparams[constants.BE_VCPUS])
2421
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2422
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2423
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2424

    
2425
  nic_total = 0
2426
  for nic_count, nic in enumerate(instance.nics):
2427
    nic_total += 1
2428
    config.set(constants.INISECT_INS, "nic%d_mac" %
2429
               nic_count, "%s" % nic.mac)
2430
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2431
    for param in constants.NICS_PARAMETER_TYPES:
2432
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2433
                 "%s" % nic.nicparams.get(param, None))
2434
  # TODO: redundant: on load can read nics until it doesn't exist
2435
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2436

    
2437
  disk_total = 0
2438
  for disk_count, disk in enumerate(snap_disks):
2439
    if disk:
2440
      disk_total += 1
2441
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2442
                 ("%s" % disk.iv_name))
2443
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2444
                 ("%s" % disk.physical_id[1]))
2445
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2446
                 ("%d" % disk.size))
2447

    
2448
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2449

    
2450
  # New-style hypervisor/backend parameters
2451

    
2452
  config.add_section(constants.INISECT_HYP)
2453
  for name, value in instance.hvparams.items():
2454
    if name not in constants.HVC_GLOBALS:
2455
      config.set(constants.INISECT_HYP, name, str(value))
2456

    
2457
  config.add_section(constants.INISECT_BEP)
2458
  for name, value in instance.beparams.items():
2459
    config.set(constants.INISECT_BEP, name, str(value))
2460

    
2461
  config.add_section(constants.INISECT_OSP)
2462
  for name, value in instance.osparams.items():
2463
    config.set(constants.INISECT_OSP, name, str(value))
2464

    
2465
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2466
                  data=config.Dumps())
2467
  shutil.rmtree(finaldestdir, ignore_errors=True)
2468
  shutil.move(destdir, finaldestdir)
2469

    
2470

    
2471
def ExportInfo(dest):
2472
  """Get export configuration information.
2473

2474
  @type dest: str
2475
  @param dest: directory containing the export
2476

2477
  @rtype: L{objects.SerializableConfigParser}
2478
  @return: a serializable config file containing the
2479
      export info
2480

2481
  """
2482
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2483

    
2484
  config = objects.SerializableConfigParser()
2485
  config.read(cff)
2486

    
2487
  if (not config.has_section(constants.INISECT_EXP) or
2488
      not config.has_section(constants.INISECT_INS)):
2489
    _Fail("Export info file doesn't have the required fields")
2490

    
2491
  return config.Dumps()
2492

    
2493

    
2494
def ListExports():
2495
  """Return a list of exports currently available on this machine.
2496

2497
  @rtype: list
2498
  @return: list of the exports
2499

2500
  """
2501
  if os.path.isdir(constants.EXPORT_DIR):
2502
    return sorted(utils.ListVisibleFiles(constants.EXPORT_DIR))
2503
  else:
2504
    _Fail("No exports directory")
2505

    
2506

    
2507
def RemoveExport(export):
2508
  """Remove an existing export from the node.
2509

2510
  @type export: str
2511
  @param export: the name of the export to remove
2512
  @rtype: None
2513

2514
  """
2515
  target = utils.PathJoin(constants.EXPORT_DIR, export)
2516

    
2517
  try:
2518
    shutil.rmtree(target)
2519
  except EnvironmentError, err:
2520
    _Fail("Error while removing the export: %s", err, exc=True)
2521

    
2522

    
2523
def BlockdevRename(devlist):
2524
  """Rename a list of block devices.
2525

2526
  @type devlist: list of tuples
2527
  @param devlist: list of tuples of the form  (disk,
2528
      new_logical_id, new_physical_id); disk is an
2529
      L{objects.Disk} object describing the current disk,
2530
      and new logical_id/physical_id is the name we
2531
      rename it to
2532
  @rtype: boolean
2533
  @return: True if all renames succeeded, False otherwise
2534

2535
  """
2536
  msgs = []
2537
  result = True
2538
  for disk, unique_id in devlist:
2539
    dev = _RecursiveFindBD(disk)
2540
    if dev is None:
2541
      msgs.append("Can't find device %s in rename" % str(disk))
2542
      result = False
2543
      continue
2544
    try:
2545
      old_rpath = dev.dev_path
2546
      dev.Rename(unique_id)
2547
      new_rpath = dev.dev_path
2548
      if old_rpath != new_rpath:
2549
        DevCacheManager.RemoveCache(old_rpath)
2550
        # FIXME: we should add the new cache information here, like:
2551
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2552
        # but we don't have the owner here - maybe parse from existing
2553
        # cache? for now, we only lose lvm data when we rename, which
2554
        # is less critical than DRBD or MD
2555
    except errors.BlockDeviceError, err:
2556
      msgs.append("Can't rename device '%s' to '%s': %s" %
2557
                  (dev, unique_id, err))
2558
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2559
      result = False
2560
  if not result:
2561
    _Fail("; ".join(msgs))
2562

    
2563

    
2564
def _TransformFileStorageDir(fs_dir):
2565
  """Checks whether given file_storage_dir is valid.
2566

2567
  Checks wheter the given fs_dir is within the cluster-wide default
2568
  file_storage_dir or the shared_file_storage_dir, which are stored in
2569
  SimpleStore. Only paths under those directories are allowed.
2570

2571
  @type fs_dir: str
2572
  @param fs_dir: the path to check
2573

2574
  @return: the normalized path if valid, None otherwise
2575

2576
  """
2577
  if not constants.ENABLE_FILE_STORAGE:
2578
    _Fail("File storage disabled at configure time")
2579
  cfg = _GetConfig()
2580
  fs_dir = os.path.normpath(fs_dir)
2581
  base_fstore = cfg.GetFileStorageDir()
2582
  base_shared = cfg.GetSharedFileStorageDir()
2583
  if not (utils.IsBelowDir(base_fstore, fs_dir) or
2584
          utils.IsBelowDir(base_shared, fs_dir)):
2585
    _Fail("File storage directory '%s' is not under base file"
2586
          " storage directory '%s' or shared storage directory '%s'",
2587
          fs_dir, base_fstore, base_shared)
2588
  return fs_dir
2589

    
2590

    
2591
def CreateFileStorageDir(file_storage_dir):
2592
  """Create file storage directory.
2593

2594
  @type file_storage_dir: str
2595
  @param file_storage_dir: directory to create
2596

2597
  @rtype: tuple
2598
  @return: tuple with first element a boolean indicating wheter dir
2599
      creation was successful or not
2600

2601
  """
2602
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2603
  if os.path.exists(file_storage_dir):
2604
    if not os.path.isdir(file_storage_dir):
2605
      _Fail("Specified storage dir '%s' is not a directory",
2606
            file_storage_dir)
2607
  else:
2608
    try:
2609
      os.makedirs(file_storage_dir, 0750)
2610
    except OSError, err:
2611
      _Fail("Cannot create file storage directory '%s': %s",
2612
            file_storage_dir, err, exc=True)
2613

    
2614

    
2615
def RemoveFileStorageDir(file_storage_dir):
2616
  """Remove file storage directory.
2617

2618
  Remove it only if it's empty. If not log an error and return.
2619

2620
  @type file_storage_dir: str
2621
  @param file_storage_dir: the directory we should cleanup
2622
  @rtype: tuple (success,)
2623
  @return: tuple of one element, C{success}, denoting
2624
      whether the operation was successful
2625

2626
  """
2627
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2628
  if os.path.exists(file_storage_dir):
2629
    if not os.path.isdir(file_storage_dir):
2630
      _Fail("Specified Storage directory '%s' is not a directory",
2631
            file_storage_dir)
2632
    # deletes dir only if empty, otherwise we want to fail the rpc call
2633
    try:
2634
      os.rmdir(file_storage_dir)
2635
    except OSError, err:
2636
      _Fail("Cannot remove file storage directory '%s': %s",
2637
            file_storage_dir, err)
2638

    
2639

    
2640
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2641
  """Rename the file storage directory.
2642

2643
  @type old_file_storage_dir: str
2644
  @param old_file_storage_dir: the current path
2645
  @type new_file_storage_dir: str
2646
  @param new_file_storage_dir: the name we should rename to
2647
  @rtype: tuple (success,)
2648
  @return: tuple of one element, C{success}, denoting
2649
      whether the operation was successful
2650

2651
  """
2652
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2653
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2654
  if not os.path.exists(new_file_storage_dir):
2655
    if os.path.isdir(old_file_storage_dir):
2656
      try:
2657
        os.rename(old_file_storage_dir, new_file_storage_dir)
2658
      except OSError, err:
2659
        _Fail("Cannot rename '%s' to '%s': %s",
2660
              old_file_storage_dir, new_file_storage_dir, err)
2661
    else:
2662
      _Fail("Specified storage dir '%s' is not a directory",
2663
            old_file_storage_dir)
2664
  else:
2665
    if os.path.exists(old_file_storage_dir):
2666
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2667
            old_file_storage_dir, new_file_storage_dir)
2668

    
2669

    
2670
def _EnsureJobQueueFile(file_name):
2671
  """Checks whether the given filename is in the queue directory.
2672

2673
  @type file_name: str
2674
  @param file_name: the file name we should check
2675
  @rtype: None
2676
  @raises RPCFail: if the file is not valid
2677

2678
  """
2679
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2680
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2681

    
2682
  if not result:
2683
    _Fail("Passed job queue file '%s' does not belong to"
2684
          " the queue directory '%s'", file_name, queue_dir)
2685

    
2686

    
2687
def JobQueueUpdate(file_name, content):
2688
  """Updates a file in the queue directory.
2689

2690
  This is just a wrapper over L{utils.io.WriteFile}, with proper
2691
  checking.
2692

2693
  @type file_name: str
2694
  @param file_name: the job file name
2695
  @type content: str
2696
  @param content: the new job contents
2697
  @rtype: boolean
2698
  @return: the success of the operation
2699

2700
  """
2701
  _EnsureJobQueueFile(file_name)
2702
  getents = runtime.GetEnts()
2703

    
2704
  # Write and replace the file atomically
2705
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
2706
                  gid=getents.masterd_gid)
2707

    
2708

    
2709
def JobQueueRename(old, new):
2710
  """Renames a job queue file.
2711

2712
  This is just a wrapper over os.rename with proper checking.
2713

2714
  @type old: str
2715
  @param old: the old (actual) file name
2716
  @type new: str
2717
  @param new: the desired file name
2718
  @rtype: tuple
2719
  @return: the success of the operation and payload
2720

2721
  """
2722
  _EnsureJobQueueFile(old)
2723
  _EnsureJobQueueFile(new)
2724

    
2725
  utils.RenameFile(old, new, mkdir=True)
2726

    
2727

    
2728
def BlockdevClose(instance_name, disks):
2729
  """Closes the given block devices.
2730

2731
  This means they will be switched to secondary mode (in case of
2732
  DRBD).
2733

2734
  @param instance_name: if the argument is not empty, the symlinks
2735
      of this instance will be removed
2736
  @type disks: list of L{objects.Disk}
2737
  @param disks: the list of disks to be closed
2738
  @rtype: tuple (success, message)
2739
  @return: a tuple of success and message, where success
2740
      indicates the succes of the operation, and message
2741
      which will contain the error details in case we
2742
      failed
2743

2744
  """
2745
  bdevs = []
2746
  for cf in disks:
2747
    rd = _RecursiveFindBD(cf)
2748
    if rd is None:
2749
      _Fail("Can't find device %s", cf)
2750
    bdevs.append(rd)
2751

    
2752
  msg = []
2753
  for rd in bdevs:
2754
    try:
2755
      rd.Close()
2756
    except errors.BlockDeviceError, err:
2757
      msg.append(str(err))
2758
  if msg:
2759
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2760
  else:
2761
    if instance_name:
2762
      _RemoveBlockDevLinks(instance_name, disks)
2763

    
2764

    
2765
def ValidateHVParams(hvname, hvparams):
2766
  """Validates the given hypervisor parameters.
2767

2768
  @type hvname: string
2769
  @param hvname: the hypervisor name
2770
  @type hvparams: dict
2771
  @param hvparams: the hypervisor parameters to be validated
2772
  @rtype: None
2773

2774
  """
2775
  try:
2776
    hv_type = hypervisor.GetHypervisor(hvname)
2777
    hv_type.ValidateParameters(hvparams)
2778
  except errors.HypervisorError, err:
2779
    _Fail(str(err), log=False)
2780

    
2781

    
2782
def _CheckOSPList(os_obj, parameters):
2783
  """Check whether a list of parameters is supported by the OS.
2784

2785
  @type os_obj: L{objects.OS}
2786
  @param os_obj: OS object to check
2787
  @type parameters: list
2788
  @param parameters: the list of parameters to check
2789

2790
  """
2791
  supported = [v[0] for v in os_obj.supported_parameters]
2792
  delta = frozenset(parameters).difference(supported)
2793
  if delta:
2794
    _Fail("The following parameters are not supported"
2795
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
2796

    
2797

    
2798
def ValidateOS(required, osname, checks, osparams):
2799
  """Validate the given OS' parameters.
2800

2801
  @type required: boolean
2802
  @param required: whether absence of the OS should translate into
2803
      failure or not
2804
  @type osname: string
2805
  @param osname: the OS to be validated
2806
  @type checks: list
2807
  @param checks: list of the checks to run (currently only 'parameters')
2808
  @type osparams: dict
2809
  @param osparams: dictionary with OS parameters
2810
  @rtype: boolean
2811
  @return: True if the validation passed, or False if the OS was not
2812
      found and L{required} was false
2813

2814
  """
2815
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
2816
    _Fail("Unknown checks required for OS %s: %s", osname,
2817
          set(checks).difference(constants.OS_VALIDATE_CALLS))
2818

    
2819
  name_only = objects.OS.GetName(osname)
2820
  status, tbv = _TryOSFromDisk(name_only, None)
2821

    
2822
  if not status:
2823
    if required:
2824
      _Fail(tbv)
2825
    else:
2826
      return False
2827

    
2828
  if max(tbv.api_versions) < constants.OS_API_V20:
2829
    return True
2830

    
2831
  if constants.OS_VALIDATE_PARAMETERS in checks:
2832
    _CheckOSPList(tbv, osparams.keys())
2833

    
2834
  validate_env = OSCoreEnv(osname, tbv, osparams)
2835
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
2836
                        cwd=tbv.path, reset_env=True)
2837
  if result.failed:
2838
    logging.error("os validate command '%s' returned error: %s output: %s",
2839
                  result.cmd, result.fail_reason, result.output)
2840
    _Fail("OS validation script failed (%s), output: %s",
2841
          result.fail_reason, result.output, log=False)
2842

    
2843
  return True
2844

    
2845

    
2846
def DemoteFromMC():
2847
  """Demotes the current node from master candidate role.
2848

2849
  """
2850
  # try to ensure we're not the master by mistake
2851
  master, myself = ssconf.GetMasterAndMyself()
2852
  if master == myself:
2853
    _Fail("ssconf status shows I'm the master node, will not demote")
2854

    
2855
  result = utils.RunCmd([constants.DAEMON_UTIL, "check", constants.MASTERD])
2856
  if not result.failed:
2857
    _Fail("The master daemon is running, will not demote")
2858

    
2859
  try:
2860
    if os.path.isfile(constants.CLUSTER_CONF_FILE):
2861
      utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2862
  except EnvironmentError, err:
2863
    if err.errno != errno.ENOENT:
2864
      _Fail("Error while backing up cluster file: %s", err, exc=True)
2865

    
2866
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2867

    
2868

    
2869
def _GetX509Filenames(cryptodir, name):
2870
  """Returns the full paths for the private key and certificate.
2871

2872
  """
2873
  return (utils.PathJoin(cryptodir, name),
2874
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
2875
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
2876

    
2877

    
2878
def CreateX509Certificate(validity, cryptodir=constants.CRYPTO_KEYS_DIR):
2879
  """Creates a new X509 certificate for SSL/TLS.
2880

2881
  @type validity: int
2882
  @param validity: Validity in seconds
2883
  @rtype: tuple; (string, string)
2884
  @return: Certificate name and public part
2885

2886
  """
2887
  (key_pem, cert_pem) = \
2888
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
2889
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
2890

    
2891
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
2892
                              prefix="x509-%s-" % utils.TimestampForFilename())
2893
  try:
2894
    name = os.path.basename(cert_dir)
2895
    assert len(name) > 5
2896

    
2897
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2898

    
2899
    utils.WriteFile(key_file, mode=0400, data=key_pem)
2900
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
2901

    
2902
    # Never return private key as it shouldn't leave the node
2903
    return (name, cert_pem)
2904
  except Exception:
2905
    shutil.rmtree(cert_dir, ignore_errors=True)
2906
    raise
2907

    
2908

    
2909
def RemoveX509Certificate(name, cryptodir=constants.CRYPTO_KEYS_DIR):
2910
  """Removes a X509 certificate.
2911

2912
  @type name: string
2913
  @param name: Certificate name
2914

2915
  """
2916
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
2917

    
2918
  utils.RemoveFile(key_file)
2919
  utils.RemoveFile(cert_file)
2920

    
2921
  try:
2922
    os.rmdir(cert_dir)
2923
  except EnvironmentError, err:
2924
    _Fail("Cannot remove certificate directory '%s': %s",
2925
          cert_dir, err)
2926

    
2927

    
2928
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
2929
  """Returns the command for the requested input/output.
2930

2931
  @type instance: L{objects.Instance}
2932
  @param instance: The instance object
2933
  @param mode: Import/export mode
2934
  @param ieio: Input/output type
2935
  @param ieargs: Input/output arguments
2936

2937
  """
2938
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
2939

    
2940
  env = None
2941
  prefix = None
2942
  suffix = None
2943
  exp_size = None
2944

    
2945
  if ieio == constants.IEIO_FILE:
2946
    (filename, ) = ieargs
2947

    
2948
    if not utils.IsNormAbsPath(filename):
2949
      _Fail("Path '%s' is not normalized or absolute", filename)
2950

    
2951
    real_filename = os.path.realpath(filename)
2952
    directory = os.path.dirname(real_filename)
2953

    
2954
    if not utils.IsBelowDir(constants.EXPORT_DIR, real_filename):
2955
      _Fail("File '%s' is not under exports directory '%s': %s",
2956
            filename, constants.EXPORT_DIR, real_filename)
2957

    
2958
    # Create directory
2959
    utils.Makedirs(directory, mode=0750)
2960

    
2961
    quoted_filename = utils.ShellQuote(filename)
2962

    
2963
    if mode == constants.IEM_IMPORT:
2964
      suffix = "> %s" % quoted_filename
2965
    elif mode == constants.IEM_EXPORT:
2966
      suffix = "< %s" % quoted_filename
2967

    
2968
      # Retrieve file size
2969
      try:
2970
        st = os.stat(filename)
2971
      except EnvironmentError, err:
2972
        logging.error("Can't stat(2) %s: %s", filename, err)
2973
      else:
2974
        exp_size = utils.BytesToMebibyte(st.st_size)
2975

    
2976
  elif ieio == constants.IEIO_RAW_DISK:
2977
    (disk, ) = ieargs
2978

    
2979
    real_disk = _OpenRealBD(disk)
2980

    
2981
    if mode == constants.IEM_IMPORT:
2982
      # we set here a smaller block size as, due to transport buffering, more
2983
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
2984
      # is not already there or we pass a wrong path; we use notrunc to no
2985
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
2986
      # much memory; this means that at best, we flush every 64k, which will
2987
      # not be very fast
2988
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
2989
                                    " bs=%s oflag=dsync"),
2990
                                    real_disk.dev_path,
2991
                                    str(64 * 1024))
2992

    
2993
    elif mode == constants.IEM_EXPORT:
2994
      # the block size on the read dd is 1MiB to match our units
2995
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
2996
                                   real_disk.dev_path,
2997
                                   str(1024 * 1024), # 1 MB
2998
                                   str(disk.size))
2999
      exp_size = disk.size
3000

    
3001
  elif ieio == constants.IEIO_SCRIPT:
3002
    (disk, disk_index, ) = ieargs
3003

    
3004
    assert isinstance(disk_index, (int, long))
3005

    
3006
    real_disk = _OpenRealBD(disk)
3007

    
3008
    inst_os = OSFromDisk(instance.os)
3009
    env = OSEnvironment(instance, inst_os)
3010

    
3011
    if mode == constants.IEM_IMPORT:
3012
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3013
      env["IMPORT_INDEX"] = str(disk_index)
3014
      script = inst_os.import_script
3015

    
3016
    elif mode == constants.IEM_EXPORT:
3017
      env["EXPORT_DEVICE"] = real_disk.dev_path
3018
      env["EXPORT_INDEX"] = str(disk_index)
3019
      script = inst_os.export_script
3020

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

    
3024
    if mode == constants.IEM_IMPORT:
3025
      suffix = "| %s" % script_cmd
3026

    
3027
    elif mode == constants.IEM_EXPORT:
3028
      prefix = "%s |" % script_cmd
3029

    
3030
    # Let script predict size
3031
    exp_size = constants.IE_CUSTOM_SIZE
3032

    
3033
  else:
3034
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3035

    
3036
  return (env, prefix, suffix, exp_size)
3037

    
3038

    
3039
def _CreateImportExportStatusDir(prefix):
3040
  """Creates status directory for import/export.
3041

3042
  """
3043
  return tempfile.mkdtemp(dir=constants.IMPORT_EXPORT_DIR,
3044
                          prefix=("%s-%s-" %
3045
                                  (prefix, utils.TimestampForFilename())))
3046

    
3047

    
3048
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3049
                            ieio, ieioargs):
3050
  """Starts an import or export daemon.
3051

3052
  @param mode: Import/output mode
3053
  @type opts: L{objects.ImportExportOptions}
3054
  @param opts: Daemon options
3055
  @type host: string
3056
  @param host: Remote host for export (None for import)
3057
  @type port: int
3058
  @param port: Remote port for export (None for import)
3059
  @type instance: L{objects.Instance}
3060
  @param instance: Instance object
3061
  @type component: string
3062
  @param component: which part of the instance is transferred now,
3063
      e.g. 'disk/0'
3064
  @param ieio: Input/output type
3065
  @param ieioargs: Input/output arguments
3066

3067
  """
3068
  if mode == constants.IEM_IMPORT:
3069
    prefix = "import"
3070

    
3071
    if not (host is None and port is None):
3072
      _Fail("Can not specify host or port on import")
3073

    
3074
  elif mode == constants.IEM_EXPORT:
3075
    prefix = "export"
3076

    
3077
    if host is None or port is None:
3078
      _Fail("Host and port must be specified for an export")
3079

    
3080
  else:
3081
    _Fail("Invalid mode %r", mode)
3082

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

    
3086
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3087
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3088

    
3089
  if opts.key_name is None:
3090
    # Use server.pem
3091
    key_path = constants.NODED_CERT_FILE
3092
    cert_path = constants.NODED_CERT_FILE
3093
    assert opts.ca_pem is None
3094
  else:
3095
    (_, key_path, cert_path) = _GetX509Filenames(constants.CRYPTO_KEYS_DIR,
3096
                                                 opts.key_name)
3097
    assert opts.ca_pem is not None
3098

    
3099
  for i in [key_path, cert_path]:
3100
    if not os.path.exists(i):
3101
      _Fail("File '%s' does not exist" % i)
3102

    
3103
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3104
  try:
3105
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3106
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3107
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3108

    
3109
    if opts.ca_pem is None:
3110
      # Use server.pem
3111
      ca = utils.ReadFile(constants.NODED_CERT_FILE)
3112
    else:
3113
      ca = opts.ca_pem
3114

    
3115
    # Write CA file
3116
    utils.WriteFile(ca_file, data=ca, mode=0400)
3117

    
3118
    cmd = [
3119
      constants.IMPORT_EXPORT_DAEMON,
3120
      status_file, mode,
3121
      "--key=%s" % key_path,
3122
      "--cert=%s" % cert_path,
3123
      "--ca=%s" % ca_file,
3124
      ]
3125

    
3126
    if host:
3127
      cmd.append("--host=%s" % host)
3128

    
3129
    if port:
3130
      cmd.append("--port=%s" % port)
3131

    
3132
    if opts.ipv6:
3133
      cmd.append("--ipv6")
3134
    else:
3135
      cmd.append("--ipv4")
3136

    
3137
    if opts.compress:
3138
      cmd.append("--compress=%s" % opts.compress)
3139

    
3140
    if opts.magic:
3141
      cmd.append("--magic=%s" % opts.magic)
3142

    
3143
    if exp_size is not None:
3144
      cmd.append("--expected-size=%s" % exp_size)
3145

    
3146
    if cmd_prefix:
3147
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3148

    
3149
    if cmd_suffix:
3150
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3151

    
3152
    if mode == constants.IEM_EXPORT:
3153
      # Retry connection a few times when connecting to remote peer
3154
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3155
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3156
    elif opts.connect_timeout is not None:
3157
      assert mode == constants.IEM_IMPORT
3158
      # Overall timeout for establishing connection while listening
3159
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3160

    
3161
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3162

    
3163
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3164
    # support for receiving a file descriptor for output
3165
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3166
                      output=logfile)
3167

    
3168
    # The import/export name is simply the status directory name
3169
    return os.path.basename(status_dir)
3170

    
3171
  except Exception:
3172
    shutil.rmtree(status_dir, ignore_errors=True)
3173
    raise
3174

    
3175

    
3176
def GetImportExportStatus(names):
3177
  """Returns import/export daemon status.
3178

3179
  @type names: sequence
3180
  @param names: List of names
3181
  @rtype: List of dicts
3182
  @return: Returns a list of the state of each named import/export or None if a
3183
           status couldn't be read
3184

3185
  """
3186
  result = []
3187

    
3188
  for name in names:
3189
    status_file = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name,
3190
                                 _IES_STATUS_FILE)
3191

    
3192
    try:
3193
      data = utils.ReadFile(status_file)
3194
    except EnvironmentError, err:
3195
      if err.errno != errno.ENOENT:
3196
        raise
3197
      data = None
3198

    
3199
    if not data:
3200
      result.append(None)
3201
      continue
3202

    
3203
    result.append(serializer.LoadJson(data))
3204

    
3205
  return result
3206

    
3207

    
3208
def AbortImportExport(name):
3209
  """Sends SIGTERM to a running import/export daemon.
3210

3211
  """
3212
  logging.info("Abort import/export %s", name)
3213

    
3214
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3215
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3216

    
3217
  if pid:
3218
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3219
                 name, pid)
3220
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3221

    
3222

    
3223
def CleanupImportExport(name):
3224
  """Cleanup after an import or export.
3225

3226
  If the import/export daemon is still running it's killed. Afterwards the
3227
  whole status directory is removed.
3228

3229
  """
3230
  logging.info("Finalizing import/export %s", name)
3231

    
3232
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3233

    
3234
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3235

    
3236
  if pid:
3237
    logging.info("Import/export %s is still running with PID %s",
3238
                 name, pid)
3239
    utils.KillProcess(pid, waitpid=False)
3240

    
3241
  shutil.rmtree(status_dir, ignore_errors=True)
3242

    
3243

    
3244
def _FindDisks(nodes_ip, disks):
3245
  """Sets the physical ID on disks and returns the block devices.
3246

3247
  """
3248
  # set the correct physical ID
3249
  my_name = netutils.Hostname.GetSysName()
3250
  for cf in disks:
3251
    cf.SetPhysicalID(my_name, nodes_ip)
3252

    
3253
  bdevs = []
3254

    
3255
  for cf in disks:
3256
    rd = _RecursiveFindBD(cf)
3257
    if rd is None:
3258
      _Fail("Can't find device %s", cf)
3259
    bdevs.append(rd)
3260
  return bdevs
3261

    
3262

    
3263
def DrbdDisconnectNet(nodes_ip, disks):
3264
  """Disconnects the network on a list of drbd devices.
3265

3266
  """
3267
  bdevs = _FindDisks(nodes_ip, disks)
3268

    
3269
  # disconnect disks
3270
  for rd in bdevs:
3271
    try:
3272
      rd.DisconnectNet()
3273
    except errors.BlockDeviceError, err:
3274
      _Fail("Can't change network configuration to standalone mode: %s",
3275
            err, exc=True)
3276

    
3277

    
3278
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3279
  """Attaches the network on a list of drbd devices.
3280

3281
  """
3282
  bdevs = _FindDisks(nodes_ip, disks)
3283

    
3284
  if multimaster:
3285
    for idx, rd in enumerate(bdevs):
3286
      try:
3287
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3288
      except EnvironmentError, err:
3289
        _Fail("Can't create symlink: %s", err)
3290
  # reconnect disks, switch to new master configuration and if
3291
  # needed primary mode
3292
  for rd in bdevs:
3293
    try:
3294
      rd.AttachNet(multimaster)
3295
    except errors.BlockDeviceError, err:
3296
      _Fail("Can't change network configuration: %s", err)
3297

    
3298
  # wait until the disks are connected; we need to retry the re-attach
3299
  # if the device becomes standalone, as this might happen if the one
3300
  # node disconnects and reconnects in a different mode before the
3301
  # other node reconnects; in this case, one or both of the nodes will
3302
  # decide it has wrong configuration and switch to standalone
3303

    
3304
  def _Attach():
3305
    all_connected = True
3306

    
3307
    for rd in bdevs:
3308
      stats = rd.GetProcStatus()
3309

    
3310
      all_connected = (all_connected and
3311
                       (stats.is_connected or stats.is_in_resync))
3312

    
3313
      if stats.is_standalone:
3314
        # peer had different config info and this node became
3315
        # standalone, even though this should not happen with the
3316
        # new staged way of changing disk configs
3317
        try:
3318
          rd.AttachNet(multimaster)
3319
        except errors.BlockDeviceError, err:
3320
          _Fail("Can't change network configuration: %s", err)
3321

    
3322
    if not all_connected:
3323
      raise utils.RetryAgain()
3324

    
3325
  try:
3326
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3327
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3328
  except utils.RetryTimeout:
3329
    _Fail("Timeout in disk reconnecting")
3330

    
3331
  if multimaster:
3332
    # change to primary mode
3333
    for rd in bdevs:
3334
      try:
3335
        rd.Open()
3336
      except errors.BlockDeviceError, err:
3337
        _Fail("Can't change to primary mode: %s", err)
3338

    
3339

    
3340
def DrbdWaitSync(nodes_ip, disks):
3341
  """Wait until DRBDs have synchronized.
3342

3343
  """
3344
  def _helper(rd):
3345
    stats = rd.GetProcStatus()
3346
    if not (stats.is_connected or stats.is_in_resync):
3347
      raise utils.RetryAgain()
3348
    return stats
3349

    
3350
  bdevs = _FindDisks(nodes_ip, disks)
3351

    
3352
  min_resync = 100
3353
  alldone = True
3354
  for rd in bdevs:
3355
    try:
3356
      # poll each second for 15 seconds
3357
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3358
    except utils.RetryTimeout:
3359
      stats = rd.GetProcStatus()
3360
      # last check
3361
      if not (stats.is_connected or stats.is_in_resync):
3362
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3363
    alldone = alldone and (not stats.is_in_resync)
3364
    if stats.sync_percent is not None:
3365
      min_resync = min(min_resync, stats.sync_percent)
3366

    
3367
  return (alldone, min_resync)
3368

    
3369

    
3370
def GetDrbdUsermodeHelper():
3371
  """Returns DRBD usermode helper currently configured.
3372

3373
  """
3374
  try:
3375
    return bdev.BaseDRBD.GetUsermodeHelper()
3376
  except errors.BlockDeviceError, err:
3377
    _Fail(str(err))
3378

    
3379

    
3380
def PowercycleNode(hypervisor_type):
3381
  """Hard-powercycle the node.
3382

3383
  Because we need to return first, and schedule the powercycle in the
3384
  background, we won't be able to report failures nicely.
3385

3386
  """
3387
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3388
  try:
3389
    pid = os.fork()
3390
  except OSError:
3391
    # if we can't fork, we'll pretend that we're in the child process
3392
    pid = 0
3393
  if pid > 0:
3394
    return "Reboot scheduled in 5 seconds"
3395
  # ensure the child is running on ram
3396
  try:
3397
    utils.Mlockall()
3398
  except Exception: # pylint: disable=W0703
3399
    pass
3400
  time.sleep(5)
3401
  hyper.PowercycleNode()
3402

    
3403

    
3404
class HooksRunner(object):
3405
  """Hook runner.
3406

3407
  This class is instantiated on the node side (ganeti-noded) and not
3408
  on the master side.
3409

3410
  """
3411
  def __init__(self, hooks_base_dir=None):
3412
    """Constructor for hooks runner.
3413

3414
    @type hooks_base_dir: str or None
3415
    @param hooks_base_dir: if not None, this overrides the
3416
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
3417

3418
    """
3419
    if hooks_base_dir is None:
3420
      hooks_base_dir = constants.HOOKS_BASE_DIR
3421
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3422
    # constant
3423
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
3424

    
3425
  def RunHooks(self, hpath, phase, env):
3426
    """Run the scripts in the hooks directory.
3427

3428
    @type hpath: str
3429
    @param hpath: the path to the hooks directory which
3430
        holds the scripts
3431
    @type phase: str
3432
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
3433
        L{constants.HOOKS_PHASE_POST}
3434
    @type env: dict
3435
    @param env: dictionary with the environment for the hook
3436
    @rtype: list
3437
    @return: list of 3-element tuples:
3438
      - script path
3439
      - script result, either L{constants.HKR_SUCCESS} or
3440
        L{constants.HKR_FAIL}
3441
      - output of the script
3442

3443
    @raise errors.ProgrammerError: for invalid input
3444
        parameters
3445

3446
    """
3447
    if phase == constants.HOOKS_PHASE_PRE:
3448
      suffix = "pre"
3449
    elif phase == constants.HOOKS_PHASE_POST:
3450
      suffix = "post"
3451
    else:
3452
      _Fail("Unknown hooks phase '%s'", phase)
3453

    
3454
    subdir = "%s-%s.d" % (hpath, suffix)
3455
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3456

    
3457
    results = []
3458

    
3459
    if not os.path.isdir(dir_name):
3460
      # for non-existing/non-dirs, we simply exit instead of logging a
3461
      # warning at every operation
3462
      return results
3463

    
3464
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3465

    
3466
    for (relname, relstatus, runresult)  in runparts_results:
3467
      if relstatus == constants.RUNPARTS_SKIP:
3468
        rrval = constants.HKR_SKIP
3469
        output = ""
3470
      elif relstatus == constants.RUNPARTS_ERR:
3471
        rrval = constants.HKR_FAIL
3472
        output = "Hook script execution error: %s" % runresult
3473
      elif relstatus == constants.RUNPARTS_RUN:
3474
        if runresult.failed:
3475
          rrval = constants.HKR_FAIL
3476
        else:
3477
          rrval = constants.HKR_SUCCESS
3478
        output = utils.SafeEncode(runresult.output.strip())
3479
      results.append(("%s/%s" % (subdir, relname), rrval, output))
3480

    
3481
    return results
3482

    
3483

    
3484
class IAllocatorRunner(object):
3485
  """IAllocator runner.
3486

3487
  This class is instantiated on the node side (ganeti-noded) and not on
3488
  the master side.
3489

3490
  """
3491
  @staticmethod
3492
  def Run(name, idata):
3493
    """Run an iallocator script.
3494

3495
    @type name: str
3496
    @param name: the iallocator script name
3497
    @type idata: str
3498
    @param idata: the allocator input data
3499

3500
    @rtype: tuple
3501
    @return: two element tuple of:
3502
       - status
3503
       - either error message or stdout of allocator (for success)
3504

3505
    """
3506
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
3507
                                  os.path.isfile)
3508
    if alloc_script is None:
3509
      _Fail("iallocator module '%s' not found in the search path", name)
3510

    
3511
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
3512
    try:
3513
      os.write(fd, idata)
3514
      os.close(fd)
3515
      result = utils.RunCmd([alloc_script, fin_name])
3516
      if result.failed:
3517
        _Fail("iallocator module '%s' failed: %s, output '%s'",
3518
              name, result.fail_reason, result.output)
3519
    finally:
3520
      os.unlink(fin_name)
3521

    
3522
    return result.stdout
3523

    
3524

    
3525
class DevCacheManager(object):
3526
  """Simple class for managing a cache of block device information.
3527

3528
  """
3529
  _DEV_PREFIX = "/dev/"
3530
  _ROOT_DIR = constants.BDEV_CACHE_DIR
3531

    
3532
  @classmethod
3533
  def _ConvertPath(cls, dev_path):
3534
    """Converts a /dev/name path to the cache file name.
3535

3536
    This replaces slashes with underscores and strips the /dev
3537
    prefix. It then returns the full path to the cache file.
3538

3539
    @type dev_path: str
3540
    @param dev_path: the C{/dev/} path name
3541
    @rtype: str
3542
    @return: the converted path name
3543

3544
    """
3545
    if dev_path.startswith(cls._DEV_PREFIX):
3546
      dev_path = dev_path[len(cls._DEV_PREFIX):]
3547
    dev_path = dev_path.replace("/", "_")
3548
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
3549
    return fpath
3550

    
3551
  @classmethod
3552
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
3553
    """Updates the cache information for a given device.
3554

3555
    @type dev_path: str
3556
    @param dev_path: the pathname of the device
3557
    @type owner: str
3558
    @param owner: the owner (instance name) of the device
3559
    @type on_primary: bool
3560
    @param on_primary: whether this is the primary
3561
        node nor not
3562
    @type iv_name: str
3563
    @param iv_name: the instance-visible name of the
3564
        device, as in objects.Disk.iv_name
3565

3566
    @rtype: None
3567

3568
    """
3569
    if dev_path is None:
3570
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
3571
      return
3572
    fpath = cls._ConvertPath(dev_path)
3573
    if on_primary:
3574
      state = "primary"
3575
    else:
3576
      state = "secondary"
3577
    if iv_name is None:
3578
      iv_name = "not_visible"
3579
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
3580
    try:
3581
      utils.WriteFile(fpath, data=fdata)
3582
    except EnvironmentError, err:
3583
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
3584

    
3585
  @classmethod
3586
  def RemoveCache(cls, dev_path):
3587
    """Remove data for a dev_path.
3588

3589
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
3590
    path name and logging.
3591

3592
    @type dev_path: str
3593
    @param dev_path: the pathname of the device
3594

3595
    @rtype: None
3596

3597
    """
3598
    if dev_path is None:
3599
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
3600
      return
3601
    fpath = cls._ConvertPath(dev_path)
3602
    try:
3603
      utils.RemoveFile(fpath)
3604
    except EnvironmentError, err:
3605
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)