Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 72b35807

History | View | Annotate | Download (114.8 kB)

1
#
2
#
3

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

    
21

    
22
"""Functions used by the node daemon
23

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

29
"""
30

    
31
# pylint: disable=E1103
32

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

    
37

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

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

    
68

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

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

    
86
# Actions for the master setup script
87
_MASTER_START = "start"
88
_MASTER_STOP = "stop"
89

    
90

    
91
class RPCFail(Exception):
92
  """Class denoting RPC failure.
93

94
  Its argument is the error message.
95

96
  """
97

    
98

    
99
def _Fail(msg, *args, **kwargs):
100
  """Log an error and the raise an RPCFail exception.
101

102
  This exception is then handled specially in the ganeti daemon and
103
  turned into a 'failed' return type. As such, this function is a
104
  useful shortcut for logging the error and returning it to the master
105
  daemon.
106

107
  @type msg: string
108
  @param msg: the text of the exception
109
  @raise RPCFail
110

111
  """
112
  if args:
113
    msg = msg % args
114
  if "log" not in kwargs or kwargs["log"]: # if we should log this error
115
    if "exc" in kwargs and kwargs["exc"]:
116
      logging.exception(msg)
117
    else:
118
      logging.error(msg)
119
  raise RPCFail(msg)
120

    
121

    
122
def _GetConfig():
123
  """Simple wrapper to return a SimpleStore.
124

125
  @rtype: L{ssconf.SimpleStore}
126
  @return: a SimpleStore instance
127

128
  """
129
  return ssconf.SimpleStore()
130

    
131

    
132
def _GetSshRunner(cluster_name):
133
  """Simple wrapper to return an SshRunner.
134

135
  @type cluster_name: str
136
  @param cluster_name: the cluster name, which is needed
137
      by the SshRunner constructor
138
  @rtype: L{ssh.SshRunner}
139
  @return: an SshRunner instance
140

141
  """
142
  return ssh.SshRunner(cluster_name)
143

    
144

    
145
def _Decompress(data):
146
  """Unpacks data compressed by the RPC client.
147

148
  @type data: list or tuple
149
  @param data: Data sent by RPC client
150
  @rtype: str
151
  @return: Decompressed data
152

153
  """
154
  assert isinstance(data, (list, tuple))
155
  assert len(data) == 2
156
  (encoding, content) = data
157
  if encoding == constants.RPC_ENCODING_NONE:
158
    return content
159
  elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
160
    return zlib.decompress(base64.b64decode(content))
161
  else:
162
    raise AssertionError("Unknown data encoding")
163

    
164

    
165
def _CleanDirectory(path, exclude=None):
166
  """Removes all regular files in a directory.
167

168
  @type path: str
169
  @param path: the directory to clean
170
  @type exclude: list
171
  @param exclude: list of files to be excluded, defaults
172
      to the empty list
173

174
  """
175
  if path not in _ALLOWED_CLEAN_DIRS:
176
    _Fail("Path passed to _CleanDirectory not in allowed clean targets: '%s'",
177
          path)
178

    
179
  if not os.path.isdir(path):
180
    return
181
  if exclude is None:
182
    exclude = []
183
  else:
184
    # Normalize excluded paths
185
    exclude = [os.path.normpath(i) for i in exclude]
186

    
187
  for rel_name in utils.ListVisibleFiles(path):
188
    full_name = utils.PathJoin(path, rel_name)
189
    if full_name in exclude:
190
      continue
191
    if os.path.isfile(full_name) and not os.path.islink(full_name):
192
      utils.RemoveFile(full_name)
193

    
194

    
195
def _BuildUploadFileList():
196
  """Build the list of allowed upload files.
197

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

200
  """
201
  allowed_files = set([
202
    pathutils.CLUSTER_CONF_FILE,
203
    pathutils.ETC_HOSTS,
204
    pathutils.SSH_KNOWN_HOSTS_FILE,
205
    pathutils.VNC_PASSWORD_FILE,
206
    pathutils.RAPI_CERT_FILE,
207
    pathutils.SPICE_CERT_FILE,
208
    pathutils.SPICE_CACERT_FILE,
209
    pathutils.RAPI_USERS_FILE,
210
    pathutils.CONFD_HMAC_KEY,
211
    pathutils.CLUSTER_DOMAIN_SECRET_FILE,
212
    ])
213

    
214
  for hv_name in constants.HYPER_TYPES:
215
    hv_class = hypervisor.GetHypervisorClass(hv_name)
216
    allowed_files.update(hv_class.GetAncillaryFiles()[0])
217

    
218
  assert pathutils.FILE_STORAGE_PATHS_FILE not in allowed_files, \
219
    "Allowed file storage paths should never be uploaded via RPC"
220

    
221
  return frozenset(allowed_files)
222

    
223

    
224
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
225

    
226

    
227
def JobQueuePurge():
228
  """Removes job queue files and archived jobs.
229

230
  @rtype: tuple
231
  @return: True, None
232

233
  """
234
  _CleanDirectory(pathutils.QUEUE_DIR, exclude=[pathutils.JOB_QUEUE_LOCK_FILE])
235
  _CleanDirectory(pathutils.JOB_QUEUE_ARCHIVE_DIR)
236

    
237

    
238
def GetMasterInfo():
239
  """Returns master information.
240

241
  This is an utility function to compute master information, either
242
  for consumption here or from the node daemon.
243

244
  @rtype: tuple
245
  @return: master_netdev, master_ip, master_name, primary_ip_family,
246
    master_netmask
247
  @raise RPCFail: in case of errors
248

249
  """
250
  try:
251
    cfg = _GetConfig()
252
    master_netdev = cfg.GetMasterNetdev()
253
    master_ip = cfg.GetMasterIP()
254
    master_netmask = cfg.GetMasterNetmask()
255
    master_node = cfg.GetMasterNode()
256
    primary_ip_family = cfg.GetPrimaryIPFamily()
257
  except errors.ConfigurationError, err:
258
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
259
  return (master_netdev, master_ip, master_node, primary_ip_family,
260
          master_netmask)
261

    
262

    
263
def RunLocalHooks(hook_opcode, hooks_path, env_builder_fn):
264
  """Decorator that runs hooks before and after the decorated function.
265

266
  @type hook_opcode: string
267
  @param hook_opcode: opcode of the hook
268
  @type hooks_path: string
269
  @param hooks_path: path of the hooks
270
  @type env_builder_fn: function
271
  @param env_builder_fn: function that returns a dictionary containing the
272
    environment variables for the hooks. Will get all the parameters of the
273
    decorated function.
274
  @raise RPCFail: in case of pre-hook failure
275

276
  """
277
  def decorator(fn):
278
    def wrapper(*args, **kwargs):
279
      _, myself = ssconf.GetMasterAndMyself()
280
      nodes = ([myself], [myself])  # these hooks run locally
281

    
282
      env_fn = compat.partial(env_builder_fn, *args, **kwargs)
283

    
284
      cfg = _GetConfig()
285
      hr = HooksRunner()
286
      hm = mcpu.HooksMaster(hook_opcode, hooks_path, nodes, hr.RunLocalHooks,
287
                            None, env_fn, logging.warning, cfg.GetClusterName(),
288
                            cfg.GetMasterNode())
289

    
290
      hm.RunPhase(constants.HOOKS_PHASE_PRE)
291
      result = fn(*args, **kwargs)
292
      hm.RunPhase(constants.HOOKS_PHASE_POST)
293

    
294
      return result
295
    return wrapper
296
  return decorator
297

    
298

    
299
def _BuildMasterIpEnv(master_params, use_external_mip_script=None):
300
  """Builds environment variables for master IP hooks.
301

302
  @type master_params: L{objects.MasterNetworkParameters}
303
  @param master_params: network parameters of the master
304
  @type use_external_mip_script: boolean
305
  @param use_external_mip_script: whether to use an external master IP
306
    address setup script (unused, but necessary per the implementation of the
307
    _RunLocalHooks decorator)
308

309
  """
310
  # pylint: disable=W0613
311
  ver = netutils.IPAddress.GetVersionFromAddressFamily(master_params.ip_family)
312
  env = {
313
    "MASTER_NETDEV": master_params.netdev,
314
    "MASTER_IP": master_params.ip,
315
    "MASTER_NETMASK": str(master_params.netmask),
316
    "CLUSTER_IP_VERSION": str(ver),
317
  }
318

    
319
  return env
320

    
321

    
322
def _RunMasterSetupScript(master_params, action, use_external_mip_script):
323
  """Execute the master IP address setup script.
324

325
  @type master_params: L{objects.MasterNetworkParameters}
326
  @param master_params: network parameters of the master
327
  @type action: string
328
  @param action: action to pass to the script. Must be one of
329
    L{backend._MASTER_START} or L{backend._MASTER_STOP}
330
  @type use_external_mip_script: boolean
331
  @param use_external_mip_script: whether to use an external master IP
332
    address setup script
333
  @raise backend.RPCFail: if there are errors during the execution of the
334
    script
335

336
  """
337
  env = _BuildMasterIpEnv(master_params)
338

    
339
  if use_external_mip_script:
340
    setup_script = pathutils.EXTERNAL_MASTER_SETUP_SCRIPT
341
  else:
342
    setup_script = pathutils.DEFAULT_MASTER_SETUP_SCRIPT
343

    
344
  result = utils.RunCmd([setup_script, action], env=env, reset_env=True)
345

    
346
  if result.failed:
347
    _Fail("Failed to %s the master IP. Script return value: %s" %
348
          (action, result.exit_code), log=True)
349

    
350

    
351
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNUP, "master-ip-turnup",
352
               _BuildMasterIpEnv)
353
def ActivateMasterIp(master_params, use_external_mip_script):
354
  """Activate the IP address of the master daemon.
355

356
  @type master_params: L{objects.MasterNetworkParameters}
357
  @param master_params: network parameters of the master
358
  @type use_external_mip_script: boolean
359
  @param use_external_mip_script: whether to use an external master IP
360
    address setup script
361
  @raise RPCFail: in case of errors during the IP startup
362

363
  """
364
  _RunMasterSetupScript(master_params, _MASTER_START,
365
                        use_external_mip_script)
366

    
367

    
368
def StartMasterDaemons(no_voting):
369
  """Activate local node as master node.
370

371
  The function will start the master daemons (ganeti-masterd and ganeti-rapi).
372

373
  @type no_voting: boolean
374
  @param no_voting: whether to start ganeti-masterd without a node vote
375
      but still non-interactively
376
  @rtype: None
377

378
  """
379

    
380
  if no_voting:
381
    masterd_args = "--no-voting --yes-do-it"
382
  else:
383
    masterd_args = ""
384

    
385
  env = {
386
    "EXTRA_MASTERD_ARGS": masterd_args,
387
    }
388

    
389
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "start-master"], env=env)
390
  if result.failed:
391
    msg = "Can't start Ganeti master: %s" % result.output
392
    logging.error(msg)
393
    _Fail(msg)
394

    
395

    
396
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNDOWN, "master-ip-turndown",
397
               _BuildMasterIpEnv)
398
def DeactivateMasterIp(master_params, use_external_mip_script):
399
  """Deactivate the master IP on this node.
400

401
  @type master_params: L{objects.MasterNetworkParameters}
402
  @param master_params: network parameters of the master
403
  @type use_external_mip_script: boolean
404
  @param use_external_mip_script: whether to use an external master IP
405
    address setup script
406
  @raise RPCFail: in case of errors during the IP turndown
407

408
  """
409
  _RunMasterSetupScript(master_params, _MASTER_STOP,
410
                        use_external_mip_script)
411

    
412

    
413
def StopMasterDaemons():
414
  """Stop the master daemons on this node.
415

416
  Stop the master daemons (ganeti-masterd and ganeti-rapi) on this node.
417

418
  @rtype: None
419

420
  """
421
  # TODO: log and report back to the caller the error failures; we
422
  # need to decide in which case we fail the RPC for this
423

    
424
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop-master"])
425
  if result.failed:
426
    logging.error("Could not stop Ganeti master, command %s had exitcode %s"
427
                  " and error %s",
428
                  result.cmd, result.exit_code, result.output)
429

    
430

    
431
def ChangeMasterNetmask(old_netmask, netmask, master_ip, master_netdev):
432
  """Change the netmask of the master IP.
433

434
  @param old_netmask: the old value of the netmask
435
  @param netmask: the new value of the netmask
436
  @param master_ip: the master IP
437
  @param master_netdev: the master network device
438

439
  """
440
  if old_netmask == netmask:
441
    return
442

    
443
  if not netutils.IPAddress.Own(master_ip):
444
    _Fail("The master IP address is not up, not attempting to change its"
445
          " netmask")
446

    
447
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
448
                         "%s/%s" % (master_ip, netmask),
449
                         "dev", master_netdev, "label",
450
                         "%s:0" % master_netdev])
451
  if result.failed:
452
    _Fail("Could not set the new netmask on the master IP address")
453

    
454
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
455
                         "%s/%s" % (master_ip, old_netmask),
456
                         "dev", master_netdev, "label",
457
                         "%s:0" % master_netdev])
458
  if result.failed:
459
    _Fail("Could not bring down the master IP address with the old netmask")
460

    
461

    
462
def EtcHostsModify(mode, host, ip):
463
  """Modify a host entry in /etc/hosts.
464

465
  @param mode: The mode to operate. Either add or remove entry
466
  @param host: The host to operate on
467
  @param ip: The ip associated with the entry
468

469
  """
470
  if mode == constants.ETC_HOSTS_ADD:
471
    if not ip:
472
      RPCFail("Mode 'add' needs 'ip' parameter, but parameter not"
473
              " present")
474
    utils.AddHostToEtcHosts(host, ip)
475
  elif mode == constants.ETC_HOSTS_REMOVE:
476
    if ip:
477
      RPCFail("Mode 'remove' does not allow 'ip' parameter, but"
478
              " parameter is present")
479
    utils.RemoveHostFromEtcHosts(host)
480
  else:
481
    RPCFail("Mode not supported")
482

    
483

    
484
def LeaveCluster(modify_ssh_setup):
485
  """Cleans up and remove the current node.
486

487
  This function cleans up and prepares the current node to be removed
488
  from the cluster.
489

490
  If processing is successful, then it raises an
491
  L{errors.QuitGanetiException} which is used as a special case to
492
  shutdown the node daemon.
493

494
  @param modify_ssh_setup: boolean
495

496
  """
497
  _CleanDirectory(pathutils.DATA_DIR)
498
  _CleanDirectory(pathutils.CRYPTO_KEYS_DIR)
499
  JobQueuePurge()
500

    
501
  if modify_ssh_setup:
502
    try:
503
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.SSH_LOGIN_USER)
504

    
505
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
506

    
507
      utils.RemoveFile(priv_key)
508
      utils.RemoveFile(pub_key)
509
    except errors.OpExecError:
510
      logging.exception("Error while processing ssh files")
511

    
512
  try:
513
    utils.RemoveFile(pathutils.CONFD_HMAC_KEY)
514
    utils.RemoveFile(pathutils.RAPI_CERT_FILE)
515
    utils.RemoveFile(pathutils.SPICE_CERT_FILE)
516
    utils.RemoveFile(pathutils.SPICE_CACERT_FILE)
517
    utils.RemoveFile(pathutils.NODED_CERT_FILE)
518
  except: # pylint: disable=W0702
519
    logging.exception("Error while removing cluster secrets")
520

    
521
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop", constants.CONFD])
522
  if result.failed:
523
    logging.error("Command %s failed with exitcode %s and error %s",
524
                  result.cmd, result.exit_code, result.output)
525

    
526
  # Raise a custom exception (handled in ganeti-noded)
527
  raise errors.QuitGanetiException(True, "Shutdown scheduled")
528

    
529

    
530
def _GetVgInfo(name):
531
  """Retrieves information about a LVM volume group.
532

533
  """
534
  # TODO: GetVGInfo supports returning information for multiple VGs at once
535
  vginfo = bdev.LogicalVolume.GetVGInfo([name])
536
  if vginfo:
537
    vg_free = int(round(vginfo[0][0], 0))
538
    vg_size = int(round(vginfo[0][1], 0))
539
  else:
540
    vg_free = None
541
    vg_size = None
542

    
543
  return {
544
    "name": name,
545
    "vg_free": vg_free,
546
    "vg_size": vg_size,
547
    }
548

    
549

    
550
def _GetHvInfo(name):
551
  """Retrieves node information from a hypervisor.
552

553
  The information returned depends on the hypervisor. Common items:
554

555
    - vg_size is the size of the configured volume group in MiB
556
    - vg_free is the free size of the volume group in MiB
557
    - memory_dom0 is the memory allocated for domain0 in MiB
558
    - memory_free is the currently available (free) ram in MiB
559
    - memory_total is the total number of ram in MiB
560
    - hv_version: the hypervisor version, if available
561

562
  """
563
  return hypervisor.GetHypervisor(name).GetNodeInfo()
564

    
565

    
566
def _GetNamedNodeInfo(names, fn):
567
  """Calls C{fn} for all names in C{names} and returns a dictionary.
568

569
  @rtype: None or dict
570

571
  """
572
  if names is None:
573
    return None
574
  else:
575
    return map(fn, names)
576

    
577

    
578
def GetNodeInfo(vg_names, hv_names):
579
  """Gives back a hash with different information about the node.
580

581
  @type vg_names: list of string
582
  @param vg_names: Names of the volume groups to ask for disk space information
583
  @type hv_names: list of string
584
  @param hv_names: Names of the hypervisors to ask for node information
585
  @rtype: tuple; (string, None/dict, None/dict)
586
  @return: Tuple containing boot ID, volume group information and hypervisor
587
    information
588

589
  """
590
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
591
  vg_info = _GetNamedNodeInfo(vg_names, _GetVgInfo)
592
  hv_info = _GetNamedNodeInfo(hv_names, _GetHvInfo)
593

    
594
  return (bootid, vg_info, hv_info)
595

    
596

    
597
def VerifyNode(what, cluster_name):
598
  """Verify the status of the local node.
599

600
  Based on the input L{what} parameter, various checks are done on the
601
  local node.
602

603
  If the I{filelist} key is present, this list of
604
  files is checksummed and the file/checksum pairs are returned.
605

606
  If the I{nodelist} key is present, we check that we have
607
  connectivity via ssh with the target nodes (and check the hostname
608
  report).
609

610
  If the I{node-net-test} key is present, we check that we have
611
  connectivity to the given nodes via both primary IP and, if
612
  applicable, secondary IPs.
613

614
  @type what: C{dict}
615
  @param what: a dictionary of things to check:
616
      - filelist: list of files for which to compute checksums
617
      - nodelist: list of nodes we should check ssh communication with
618
      - node-net-test: list of nodes we should check node daemon port
619
        connectivity with
620
      - hypervisor: list with hypervisors to run the verify for
621
  @rtype: dict
622
  @return: a dictionary with the same keys as the input dict, and
623
      values representing the result of the checks
624

625
  """
626
  result = {}
627
  my_name = netutils.Hostname.GetSysName()
628
  port = netutils.GetDaemonPort(constants.NODED)
629
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
630

    
631
  if constants.NV_HYPERVISOR in what and vm_capable:
632
    result[constants.NV_HYPERVISOR] = tmp = {}
633
    for hv_name in what[constants.NV_HYPERVISOR]:
634
      try:
635
        val = hypervisor.GetHypervisor(hv_name).Verify()
636
      except errors.HypervisorError, err:
637
        val = "Error while checking hypervisor: %s" % str(err)
638
      tmp[hv_name] = val
639

    
640
  if constants.NV_HVPARAMS in what and vm_capable:
641
    result[constants.NV_HVPARAMS] = tmp = []
642
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
643
      try:
644
        logging.info("Validating hv %s, %s", hv_name, hvparms)
645
        hypervisor.GetHypervisor(hv_name).ValidateParameters(hvparms)
646
      except errors.HypervisorError, err:
647
        tmp.append((source, hv_name, str(err)))
648

    
649
  if constants.NV_FILELIST in what:
650
    fingerprints = utils.FingerprintFiles(map(vcluster.LocalizeVirtualPath,
651
                                              what[constants.NV_FILELIST]))
652
    result[constants.NV_FILELIST] = \
653
      dict((vcluster.MakeVirtualPath(key), value)
654
           for (key, value) in fingerprints.items())
655

    
656
  if constants.NV_NODELIST in what:
657
    (nodes, bynode) = what[constants.NV_NODELIST]
658

    
659
    # Add nodes from other groups (different for each node)
660
    try:
661
      nodes.extend(bynode[my_name])
662
    except KeyError:
663
      pass
664

    
665
    # Use a random order
666
    random.shuffle(nodes)
667

    
668
    # Try to contact all nodes
669
    val = {}
670
    for node in nodes:
671
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
672
      if not success:
673
        val[node] = message
674

    
675
    result[constants.NV_NODELIST] = val
676

    
677
  if constants.NV_NODENETTEST in what:
678
    result[constants.NV_NODENETTEST] = tmp = {}
679
    my_pip = my_sip = None
680
    for name, pip, sip in what[constants.NV_NODENETTEST]:
681
      if name == my_name:
682
        my_pip = pip
683
        my_sip = sip
684
        break
685
    if not my_pip:
686
      tmp[my_name] = ("Can't find my own primary/secondary IP"
687
                      " in the node list")
688
    else:
689
      for name, pip, sip in what[constants.NV_NODENETTEST]:
690
        fail = []
691
        if not netutils.TcpPing(pip, port, source=my_pip):
692
          fail.append("primary")
693
        if sip != pip:
694
          if not netutils.TcpPing(sip, port, source=my_sip):
695
            fail.append("secondary")
696
        if fail:
697
          tmp[name] = ("failure using the %s interface(s)" %
698
                       " and ".join(fail))
699

    
700
  if constants.NV_MASTERIP in what:
701
    # FIXME: add checks on incoming data structures (here and in the
702
    # rest of the function)
703
    master_name, master_ip = what[constants.NV_MASTERIP]
704
    if master_name == my_name:
705
      source = constants.IP4_ADDRESS_LOCALHOST
706
    else:
707
      source = None
708
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
709
                                                     source=source)
710

    
711
  if constants.NV_USERSCRIPTS in what:
712
    result[constants.NV_USERSCRIPTS] = \
713
      [script for script in what[constants.NV_USERSCRIPTS]
714
       if not (os.path.exists(script) and os.access(script, os.X_OK))]
715

    
716
  if constants.NV_OOB_PATHS in what:
717
    result[constants.NV_OOB_PATHS] = tmp = []
718
    for path in what[constants.NV_OOB_PATHS]:
719
      try:
720
        st = os.stat(path)
721
      except OSError, err:
722
        tmp.append("error stating out of band helper: %s" % err)
723
      else:
724
        if stat.S_ISREG(st.st_mode):
725
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
726
            tmp.append(None)
727
          else:
728
            tmp.append("out of band helper %s is not executable" % path)
729
        else:
730
          tmp.append("out of band helper %s is not a file" % path)
731

    
732
  if constants.NV_LVLIST in what and vm_capable:
733
    try:
734
      val = GetVolumeList(utils.ListVolumeGroups().keys())
735
    except RPCFail, err:
736
      val = str(err)
737
    result[constants.NV_LVLIST] = val
738

    
739
  if constants.NV_INSTANCELIST in what and vm_capable:
740
    # GetInstanceList can fail
741
    try:
742
      val = GetInstanceList(what[constants.NV_INSTANCELIST])
743
    except RPCFail, err:
744
      val = str(err)
745
    result[constants.NV_INSTANCELIST] = val
746

    
747
  if constants.NV_VGLIST in what and vm_capable:
748
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
749

    
750
  if constants.NV_PVLIST in what and vm_capable:
751
    result[constants.NV_PVLIST] = \
752
      bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
753
                                   filter_allocatable=False)
754

    
755
  if constants.NV_VERSION in what:
756
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
757
                                    constants.RELEASE_VERSION)
758

    
759
  if constants.NV_HVINFO in what and vm_capable:
760
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
761
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
762

    
763
  if constants.NV_DRBDLIST in what and vm_capable:
764
    try:
765
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
766
    except errors.BlockDeviceError, err:
767
      logging.warning("Can't get used minors list", exc_info=True)
768
      used_minors = str(err)
769
    result[constants.NV_DRBDLIST] = used_minors
770

    
771
  if constants.NV_DRBDHELPER in what and vm_capable:
772
    status = True
773
    try:
774
      payload = bdev.BaseDRBD.GetUsermodeHelper()
775
    except errors.BlockDeviceError, err:
776
      logging.error("Can't get DRBD usermode helper: %s", str(err))
777
      status = False
778
      payload = str(err)
779
    result[constants.NV_DRBDHELPER] = (status, payload)
780

    
781
  if constants.NV_NODESETUP in what:
782
    result[constants.NV_NODESETUP] = tmpr = []
783
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
784
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
785
                  " under /sys, missing required directories /sys/block"
786
                  " and /sys/class/net")
787
    if (not os.path.isdir("/proc/sys") or
788
        not os.path.isfile("/proc/sysrq-trigger")):
789
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
790
                  " under /proc, missing required directory /proc/sys and"
791
                  " the file /proc/sysrq-trigger")
792

    
793
  if constants.NV_TIME in what:
794
    result[constants.NV_TIME] = utils.SplitTime(time.time())
795

    
796
  if constants.NV_OSLIST in what and vm_capable:
797
    result[constants.NV_OSLIST] = DiagnoseOS()
798

    
799
  if constants.NV_BRIDGES in what and vm_capable:
800
    result[constants.NV_BRIDGES] = [bridge
801
                                    for bridge in what[constants.NV_BRIDGES]
802
                                    if not utils.BridgeExists(bridge)]
803

    
804
  if what.get(constants.NV_FILE_STORAGE_PATHS) == my_name:
805
    result[constants.NV_FILE_STORAGE_PATHS] = \
806
      bdev.ComputeWrongFileStoragePaths()
807

    
808
  return result
809

    
810

    
811
def GetBlockDevSizes(devices):
812
  """Return the size of the given block devices
813

814
  @type devices: list
815
  @param devices: list of block device nodes to query
816
  @rtype: dict
817
  @return:
818
    dictionary of all block devices under /dev (key). The value is their
819
    size in MiB.
820

821
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
822

823
  """
824
  DEV_PREFIX = "/dev/"
825
  blockdevs = {}
826

    
827
  for devpath in devices:
828
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
829
      continue
830

    
831
    try:
832
      st = os.stat(devpath)
833
    except EnvironmentError, err:
834
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
835
      continue
836

    
837
    if stat.S_ISBLK(st.st_mode):
838
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
839
      if result.failed:
840
        # We don't want to fail, just do not list this device as available
841
        logging.warning("Cannot get size for block device %s", devpath)
842
        continue
843

    
844
      size = int(result.stdout) / (1024 * 1024)
845
      blockdevs[devpath] = size
846
  return blockdevs
847

    
848

    
849
def GetVolumeList(vg_names):
850
  """Compute list of logical volumes and their size.
851

852
  @type vg_names: list
853
  @param vg_names: the volume groups whose LVs we should list, or
854
      empty for all volume groups
855
  @rtype: dict
856
  @return:
857
      dictionary of all partions (key) with value being a tuple of
858
      their size (in MiB), inactive and online status::
859

860
        {'xenvg/test1': ('20.06', True, True)}
861

862
      in case of errors, a string is returned with the error
863
      details.
864

865
  """
866
  lvs = {}
867
  sep = "|"
868
  if not vg_names:
869
    vg_names = []
870
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
871
                         "--separator=%s" % sep,
872
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
873
  if result.failed:
874
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
875

    
876
  for line in result.stdout.splitlines():
877
    line = line.strip()
878
    match = _LVSLINE_REGEX.match(line)
879
    if not match:
880
      logging.error("Invalid line returned from lvs output: '%s'", line)
881
      continue
882
    vg_name, name, size, attr = match.groups()
883
    inactive = attr[4] == "-"
884
    online = attr[5] == "o"
885
    virtual = attr[0] == "v"
886
    if virtual:
887
      # we don't want to report such volumes as existing, since they
888
      # don't really hold data
889
      continue
890
    lvs[vg_name + "/" + name] = (size, inactive, online)
891

    
892
  return lvs
893

    
894

    
895
def ListVolumeGroups():
896
  """List the volume groups and their size.
897

898
  @rtype: dict
899
  @return: dictionary with keys volume name and values the
900
      size of the volume
901

902
  """
903
  return utils.ListVolumeGroups()
904

    
905

    
906
def NodeVolumes():
907
  """List all volumes on this node.
908

909
  @rtype: list
910
  @return:
911
    A list of dictionaries, each having four keys:
912
      - name: the logical volume name,
913
      - size: the size of the logical volume
914
      - dev: the physical device on which the LV lives
915
      - vg: the volume group to which it belongs
916

917
    In case of errors, we return an empty list and log the
918
    error.
919

920
    Note that since a logical volume can live on multiple physical
921
    volumes, the resulting list might include a logical volume
922
    multiple times.
923

924
  """
925
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
926
                         "--separator=|",
927
                         "--options=lv_name,lv_size,devices,vg_name"])
928
  if result.failed:
929
    _Fail("Failed to list logical volumes, lvs output: %s",
930
          result.output)
931

    
932
  def parse_dev(dev):
933
    return dev.split("(")[0]
934

    
935
  def handle_dev(dev):
936
    return [parse_dev(x) for x in dev.split(",")]
937

    
938
  def map_line(line):
939
    line = [v.strip() for v in line]
940
    return [{"name": line[0], "size": line[1],
941
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
942

    
943
  all_devs = []
944
  for line in result.stdout.splitlines():
945
    if line.count("|") >= 3:
946
      all_devs.extend(map_line(line.split("|")))
947
    else:
948
      logging.warning("Strange line in the output from lvs: '%s'", line)
949
  return all_devs
950

    
951

    
952
def BridgesExist(bridges_list):
953
  """Check if a list of bridges exist on the current node.
954

955
  @rtype: boolean
956
  @return: C{True} if all of them exist, C{False} otherwise
957

958
  """
959
  missing = []
960
  for bridge in bridges_list:
961
    if not utils.BridgeExists(bridge):
962
      missing.append(bridge)
963

    
964
  if missing:
965
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
966

    
967

    
968
def GetInstanceList(hypervisor_list):
969
  """Provides a list of instances.
970

971
  @type hypervisor_list: list
972
  @param hypervisor_list: the list of hypervisors to query information
973

974
  @rtype: list
975
  @return: a list of all running instances on the current node
976
    - instance1.example.com
977
    - instance2.example.com
978

979
  """
980
  results = []
981
  for hname in hypervisor_list:
982
    try:
983
      names = hypervisor.GetHypervisor(hname).ListInstances()
984
      results.extend(names)
985
    except errors.HypervisorError, err:
986
      _Fail("Error enumerating instances (hypervisor %s): %s",
987
            hname, err, exc=True)
988

    
989
  return results
990

    
991

    
992
def GetInstanceInfo(instance, hname):
993
  """Gives back the information about an instance as a dictionary.
994

995
  @type instance: string
996
  @param instance: the instance name
997
  @type hname: string
998
  @param hname: the hypervisor type of the instance
999

1000
  @rtype: dict
1001
  @return: dictionary with the following keys:
1002
      - memory: memory size of instance (int)
1003
      - state: xen state of instance (string)
1004
      - time: cpu time of instance (float)
1005
      - vcpus: the number of vcpus (int)
1006

1007
  """
1008
  output = {}
1009

    
1010
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
1011
  if iinfo is not None:
1012
    output["memory"] = iinfo[2]
1013
    output["vcpus"] = iinfo[3]
1014
    output["state"] = iinfo[4]
1015
    output["time"] = iinfo[5]
1016

    
1017
  return output
1018

    
1019

    
1020
def GetInstanceMigratable(instance):
1021
  """Gives whether an instance can be migrated.
1022

1023
  @type instance: L{objects.Instance}
1024
  @param instance: object representing the instance to be checked.
1025

1026
  @rtype: tuple
1027
  @return: tuple of (result, description) where:
1028
      - result: whether the instance can be migrated or not
1029
      - description: a description of the issue, if relevant
1030

1031
  """
1032
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1033
  iname = instance.name
1034
  if iname not in hyper.ListInstances():
1035
    _Fail("Instance %s is not running", iname)
1036

    
1037
  for idx in range(len(instance.disks)):
1038
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1039
    if not os.path.islink(link_name):
1040
      logging.warning("Instance %s is missing symlink %s for disk %d",
1041
                      iname, link_name, idx)
1042

    
1043

    
1044
def GetAllInstancesInfo(hypervisor_list):
1045
  """Gather data about all instances.
1046

1047
  This is the equivalent of L{GetInstanceInfo}, except that it
1048
  computes data for all instances at once, thus being faster if one
1049
  needs data about more than one instance.
1050

1051
  @type hypervisor_list: list
1052
  @param hypervisor_list: list of hypervisors to query for instance data
1053

1054
  @rtype: dict
1055
  @return: dictionary of instance: data, with data having the following keys:
1056
      - memory: memory size of instance (int)
1057
      - state: xen state of instance (string)
1058
      - time: cpu time of instance (float)
1059
      - vcpus: the number of vcpus
1060

1061
  """
1062
  output = {}
1063

    
1064
  for hname in hypervisor_list:
1065
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
1066
    if iinfo:
1067
      for name, _, memory, vcpus, state, times in iinfo:
1068
        value = {
1069
          "memory": memory,
1070
          "vcpus": vcpus,
1071
          "state": state,
1072
          "time": times,
1073
          }
1074
        if name in output:
1075
          # we only check static parameters, like memory and vcpus,
1076
          # and not state and time which can change between the
1077
          # invocations of the different hypervisors
1078
          for key in "memory", "vcpus":
1079
            if value[key] != output[name][key]:
1080
              _Fail("Instance %s is running twice"
1081
                    " with different parameters", name)
1082
        output[name] = value
1083

    
1084
  return output
1085

    
1086

    
1087
def _InstanceLogName(kind, os_name, instance, component):
1088
  """Compute the OS log filename for a given instance and operation.
1089

1090
  The instance name and os name are passed in as strings since not all
1091
  operations have these as part of an instance object.
1092

1093
  @type kind: string
1094
  @param kind: the operation type (e.g. add, import, etc.)
1095
  @type os_name: string
1096
  @param os_name: the os name
1097
  @type instance: string
1098
  @param instance: the name of the instance being imported/added/etc.
1099
  @type component: string or None
1100
  @param component: the name of the component of the instance being
1101
      transferred
1102

1103
  """
1104
  # TODO: Use tempfile.mkstemp to create unique filename
1105
  if component:
1106
    assert "/" not in component
1107
    c_msg = "-%s" % component
1108
  else:
1109
    c_msg = ""
1110
  base = ("%s-%s-%s%s-%s.log" %
1111
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1112
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1113

    
1114

    
1115
def InstanceOsAdd(instance, reinstall, debug):
1116
  """Add an OS to an instance.
1117

1118
  @type instance: L{objects.Instance}
1119
  @param instance: Instance whose OS is to be installed
1120
  @type reinstall: boolean
1121
  @param reinstall: whether this is an instance reinstall
1122
  @type debug: integer
1123
  @param debug: debug level, passed to the OS scripts
1124
  @rtype: None
1125

1126
  """
1127
  inst_os = OSFromDisk(instance.os)
1128

    
1129
  create_env = OSEnvironment(instance, inst_os, debug)
1130
  if reinstall:
1131
    create_env["INSTANCE_REINSTALL"] = "1"
1132

    
1133
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1134

    
1135
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1136
                        cwd=inst_os.path, output=logfile, reset_env=True)
1137
  if result.failed:
1138
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1139
                  " output: %s", result.cmd, result.fail_reason, logfile,
1140
                  result.output)
1141
    lines = [utils.SafeEncode(val)
1142
             for val in utils.TailFile(logfile, lines=20)]
1143
    _Fail("OS create script failed (%s), last lines in the"
1144
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1145

    
1146

    
1147
def RunRenameInstance(instance, old_name, debug):
1148
  """Run the OS rename script for an instance.
1149

1150
  @type instance: L{objects.Instance}
1151
  @param instance: Instance whose OS is to be installed
1152
  @type old_name: string
1153
  @param old_name: previous instance name
1154
  @type debug: integer
1155
  @param debug: debug level, passed to the OS scripts
1156
  @rtype: boolean
1157
  @return: the success of the operation
1158

1159
  """
1160
  inst_os = OSFromDisk(instance.os)
1161

    
1162
  rename_env = OSEnvironment(instance, inst_os, debug)
1163
  rename_env["OLD_INSTANCE_NAME"] = old_name
1164

    
1165
  logfile = _InstanceLogName("rename", instance.os,
1166
                             "%s-%s" % (old_name, instance.name), None)
1167

    
1168
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1169
                        cwd=inst_os.path, output=logfile, reset_env=True)
1170

    
1171
  if result.failed:
1172
    logging.error("os create command '%s' returned error: %s output: %s",
1173
                  result.cmd, result.fail_reason, result.output)
1174
    lines = [utils.SafeEncode(val)
1175
             for val in utils.TailFile(logfile, lines=20)]
1176
    _Fail("OS rename script failed (%s), last lines in the"
1177
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1178

    
1179

    
1180
def _GetBlockDevSymlinkPath(instance_name, idx):
1181
  return utils.PathJoin(pathutils.DISK_LINKS_DIR, "%s%s%d" %
1182
                        (instance_name, constants.DISK_SEPARATOR, idx))
1183

    
1184

    
1185
def _SymlinkBlockDev(instance_name, device_path, idx):
1186
  """Set up symlinks to a instance's block device.
1187

1188
  This is an auxiliary function run when an instance is start (on the primary
1189
  node) or when an instance is migrated (on the target node).
1190

1191

1192
  @param instance_name: the name of the target instance
1193
  @param device_path: path of the physical block device, on the node
1194
  @param idx: the disk index
1195
  @return: absolute path to the disk's symlink
1196

1197
  """
1198
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1199
  try:
1200
    os.symlink(device_path, link_name)
1201
  except OSError, err:
1202
    if err.errno == errno.EEXIST:
1203
      if (not os.path.islink(link_name) or
1204
          os.readlink(link_name) != device_path):
1205
        os.remove(link_name)
1206
        os.symlink(device_path, link_name)
1207
    else:
1208
      raise
1209

    
1210
  return link_name
1211

    
1212

    
1213
def _RemoveBlockDevLinks(instance_name, disks):
1214
  """Remove the block device symlinks belonging to the given instance.
1215

1216
  """
1217
  for idx, _ in enumerate(disks):
1218
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1219
    if os.path.islink(link_name):
1220
      try:
1221
        os.remove(link_name)
1222
      except OSError:
1223
        logging.exception("Can't remove symlink '%s'", link_name)
1224

    
1225

    
1226
def _GatherAndLinkBlockDevs(instance):
1227
  """Set up an instance's block device(s).
1228

1229
  This is run on the primary node at instance startup. The block
1230
  devices must be already assembled.
1231

1232
  @type instance: L{objects.Instance}
1233
  @param instance: the instance whose disks we shoul assemble
1234
  @rtype: list
1235
  @return: list of (disk_object, device_path)
1236

1237
  """
1238
  block_devices = []
1239
  for idx, disk in enumerate(instance.disks):
1240
    device = _RecursiveFindBD(disk)
1241
    if device is None:
1242
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1243
                                    str(disk))
1244
    device.Open()
1245
    try:
1246
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1247
    except OSError, e:
1248
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1249
                                    e.strerror)
1250

    
1251
    block_devices.append((disk, link_name))
1252

    
1253
  return block_devices
1254

    
1255

    
1256
def StartInstance(instance, startup_paused):
1257
  """Start an instance.
1258

1259
  @type instance: L{objects.Instance}
1260
  @param instance: the instance object
1261
  @type startup_paused: bool
1262
  @param instance: pause instance at startup?
1263
  @rtype: None
1264

1265
  """
1266
  running_instances = GetInstanceList([instance.hypervisor])
1267

    
1268
  if instance.name in running_instances:
1269
    logging.info("Instance %s already running, not starting", instance.name)
1270
    return
1271

    
1272
  try:
1273
    block_devices = _GatherAndLinkBlockDevs(instance)
1274
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1275
    hyper.StartInstance(instance, block_devices, startup_paused)
1276
  except errors.BlockDeviceError, err:
1277
    _Fail("Block device error: %s", err, exc=True)
1278
  except errors.HypervisorError, err:
1279
    _RemoveBlockDevLinks(instance.name, instance.disks)
1280
    _Fail("Hypervisor error: %s", err, exc=True)
1281

    
1282

    
1283
def InstanceShutdown(instance, timeout):
1284
  """Shut an instance down.
1285

1286
  @note: this functions uses polling with a hardcoded timeout.
1287

1288
  @type instance: L{objects.Instance}
1289
  @param instance: the instance object
1290
  @type timeout: integer
1291
  @param timeout: maximum timeout for soft shutdown
1292
  @rtype: None
1293

1294
  """
1295
  hv_name = instance.hypervisor
1296
  hyper = hypervisor.GetHypervisor(hv_name)
1297
  iname = instance.name
1298

    
1299
  if instance.name not in hyper.ListInstances():
1300
    logging.info("Instance %s not running, doing nothing", iname)
1301
    return
1302

    
1303
  class _TryShutdown:
1304
    def __init__(self):
1305
      self.tried_once = False
1306

    
1307
    def __call__(self):
1308
      if iname not in hyper.ListInstances():
1309
        return
1310

    
1311
      try:
1312
        hyper.StopInstance(instance, retry=self.tried_once)
1313
      except errors.HypervisorError, err:
1314
        if iname not in hyper.ListInstances():
1315
          # if the instance is no longer existing, consider this a
1316
          # success and go to cleanup
1317
          return
1318

    
1319
        _Fail("Failed to stop instance %s: %s", iname, err)
1320

    
1321
      self.tried_once = True
1322

    
1323
      raise utils.RetryAgain()
1324

    
1325
  try:
1326
    utils.Retry(_TryShutdown(), 5, timeout)
1327
  except utils.RetryTimeout:
1328
    # the shutdown did not succeed
1329
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1330

    
1331
    try:
1332
      hyper.StopInstance(instance, force=True)
1333
    except errors.HypervisorError, err:
1334
      if iname in hyper.ListInstances():
1335
        # only raise an error if the instance still exists, otherwise
1336
        # the error could simply be "instance ... unknown"!
1337
        _Fail("Failed to force stop instance %s: %s", iname, err)
1338

    
1339
    time.sleep(1)
1340

    
1341
    if iname in hyper.ListInstances():
1342
      _Fail("Could not shutdown instance %s even by destroy", iname)
1343

    
1344
  try:
1345
    hyper.CleanupInstance(instance.name)
1346
  except errors.HypervisorError, err:
1347
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1348

    
1349
  _RemoveBlockDevLinks(iname, instance.disks)
1350

    
1351

    
1352
def InstanceReboot(instance, reboot_type, shutdown_timeout):
1353
  """Reboot an instance.
1354

1355
  @type instance: L{objects.Instance}
1356
  @param instance: the instance object to reboot
1357
  @type reboot_type: str
1358
  @param reboot_type: the type of reboot, one the following
1359
    constants:
1360
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1361
        instance OS, do not recreate the VM
1362
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1363
        restart the VM (at the hypervisor level)
1364
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1365
        not accepted here, since that mode is handled differently, in
1366
        cmdlib, and translates into full stop and start of the
1367
        instance (instead of a call_instance_reboot RPC)
1368
  @type shutdown_timeout: integer
1369
  @param shutdown_timeout: maximum timeout for soft shutdown
1370
  @rtype: None
1371

1372
  """
1373
  running_instances = GetInstanceList([instance.hypervisor])
1374

    
1375
  if instance.name not in running_instances:
1376
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1377

    
1378
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1379
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1380
    try:
1381
      hyper.RebootInstance(instance)
1382
    except errors.HypervisorError, err:
1383
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1384
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1385
    try:
1386
      InstanceShutdown(instance, shutdown_timeout)
1387
      return StartInstance(instance, False)
1388
    except errors.HypervisorError, err:
1389
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1390
  else:
1391
    _Fail("Invalid reboot_type received: %s", reboot_type)
1392

    
1393

    
1394
def InstanceBalloonMemory(instance, memory):
1395
  """Resize an instance's memory.
1396

1397
  @type instance: L{objects.Instance}
1398
  @param instance: the instance object
1399
  @type memory: int
1400
  @param memory: new memory amount in MB
1401
  @rtype: None
1402

1403
  """
1404
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1405
  running = hyper.ListInstances()
1406
  if instance.name not in running:
1407
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1408
    return
1409
  try:
1410
    hyper.BalloonInstanceMemory(instance, memory)
1411
  except errors.HypervisorError, err:
1412
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1413

    
1414

    
1415
def MigrationInfo(instance):
1416
  """Gather information about an instance to be migrated.
1417

1418
  @type instance: L{objects.Instance}
1419
  @param instance: the instance definition
1420

1421
  """
1422
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1423
  try:
1424
    info = hyper.MigrationInfo(instance)
1425
  except errors.HypervisorError, err:
1426
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1427
  return info
1428

    
1429

    
1430
def AcceptInstance(instance, info, target):
1431
  """Prepare the node to accept an instance.
1432

1433
  @type instance: L{objects.Instance}
1434
  @param instance: the instance definition
1435
  @type info: string/data (opaque)
1436
  @param info: migration information, from the source node
1437
  @type target: string
1438
  @param target: target host (usually ip), on this node
1439

1440
  """
1441
  # TODO: why is this required only for DTS_EXT_MIRROR?
1442
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1443
    # Create the symlinks, as the disks are not active
1444
    # in any way
1445
    try:
1446
      _GatherAndLinkBlockDevs(instance)
1447
    except errors.BlockDeviceError, err:
1448
      _Fail("Block device error: %s", err, exc=True)
1449

    
1450
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1451
  try:
1452
    hyper.AcceptInstance(instance, info, target)
1453
  except errors.HypervisorError, err:
1454
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1455
      _RemoveBlockDevLinks(instance.name, instance.disks)
1456
    _Fail("Failed to accept instance: %s", err, exc=True)
1457

    
1458

    
1459
def FinalizeMigrationDst(instance, info, success):
1460
  """Finalize any preparation to accept an instance.
1461

1462
  @type instance: L{objects.Instance}
1463
  @param instance: the instance definition
1464
  @type info: string/data (opaque)
1465
  @param info: migration information, from the source node
1466
  @type success: boolean
1467
  @param success: whether the migration was a success or a failure
1468

1469
  """
1470
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1471
  try:
1472
    hyper.FinalizeMigrationDst(instance, info, success)
1473
  except errors.HypervisorError, err:
1474
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1475

    
1476

    
1477
def MigrateInstance(instance, target, live):
1478
  """Migrates an instance to another node.
1479

1480
  @type instance: L{objects.Instance}
1481
  @param instance: the instance definition
1482
  @type target: string
1483
  @param target: the target node name
1484
  @type live: boolean
1485
  @param live: whether the migration should be done live or not (the
1486
      interpretation of this parameter is left to the hypervisor)
1487
  @raise RPCFail: if migration fails for some reason
1488

1489
  """
1490
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1491

    
1492
  try:
1493
    hyper.MigrateInstance(instance, target, live)
1494
  except errors.HypervisorError, err:
1495
    _Fail("Failed to migrate instance: %s", err, exc=True)
1496

    
1497

    
1498
def FinalizeMigrationSource(instance, success, live):
1499
  """Finalize the instance migration on the source node.
1500

1501
  @type instance: L{objects.Instance}
1502
  @param instance: the instance definition of the migrated instance
1503
  @type success: bool
1504
  @param success: whether the migration succeeded or not
1505
  @type live: bool
1506
  @param live: whether the user requested a live migration or not
1507
  @raise RPCFail: If the execution fails for some reason
1508

1509
  """
1510
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1511

    
1512
  try:
1513
    hyper.FinalizeMigrationSource(instance, success, live)
1514
  except Exception, err:  # pylint: disable=W0703
1515
    _Fail("Failed to finalize the migration on the source node: %s", err,
1516
          exc=True)
1517

    
1518

    
1519
def GetMigrationStatus(instance):
1520
  """Get the migration status
1521

1522
  @type instance: L{objects.Instance}
1523
  @param instance: the instance that is being migrated
1524
  @rtype: L{objects.MigrationStatus}
1525
  @return: the status of the current migration (one of
1526
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1527
           progress info that can be retrieved from the hypervisor
1528
  @raise RPCFail: If the migration status cannot be retrieved
1529

1530
  """
1531
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1532
  try:
1533
    return hyper.GetMigrationStatus(instance)
1534
  except Exception, err:  # pylint: disable=W0703
1535
    _Fail("Failed to get migration status: %s", err, exc=True)
1536

    
1537

    
1538
def BlockdevCreate(disk, size, owner, on_primary, info):
1539
  """Creates a block device for an instance.
1540

1541
  @type disk: L{objects.Disk}
1542
  @param disk: the object describing the disk we should create
1543
  @type size: int
1544
  @param size: the size of the physical underlying device, in MiB
1545
  @type owner: str
1546
  @param owner: the name of the instance for which disk is created,
1547
      used for device cache data
1548
  @type on_primary: boolean
1549
  @param on_primary:  indicates if it is the primary node or not
1550
  @type info: string
1551
  @param info: string that will be sent to the physical device
1552
      creation, used for example to set (LVM) tags on LVs
1553

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

1558
  """
1559
  # TODO: remove the obsolete "size" argument
1560
  # pylint: disable=W0613
1561
  clist = []
1562
  if disk.children:
1563
    for child in disk.children:
1564
      try:
1565
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1566
      except errors.BlockDeviceError, err:
1567
        _Fail("Can't assemble device %s: %s", child, err)
1568
      if on_primary or disk.AssembleOnSecondary():
1569
        # we need the children open in case the device itself has to
1570
        # be assembled
1571
        try:
1572
          # pylint: disable=E1103
1573
          crdev.Open()
1574
        except errors.BlockDeviceError, err:
1575
          _Fail("Can't make child '%s' read-write: %s", child, err)
1576
      clist.append(crdev)
1577

    
1578
  try:
1579
    device = bdev.Create(disk, clist)
1580
  except errors.BlockDeviceError, err:
1581
    _Fail("Can't create block device: %s", err)
1582

    
1583
  if on_primary or disk.AssembleOnSecondary():
1584
    try:
1585
      device.Assemble()
1586
    except errors.BlockDeviceError, err:
1587
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1588
    if on_primary or disk.OpenOnSecondary():
1589
      try:
1590
        device.Open(force=True)
1591
      except errors.BlockDeviceError, err:
1592
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1593
    DevCacheManager.UpdateCache(device.dev_path, owner,
1594
                                on_primary, disk.iv_name)
1595

    
1596
  device.SetInfo(info)
1597

    
1598
  return device.unique_id
1599

    
1600

    
1601
def _WipeDevice(path, offset, size):
1602
  """This function actually wipes the device.
1603

1604
  @param path: The path to the device to wipe
1605
  @param offset: The offset in MiB in the file
1606
  @param size: The size in MiB to write
1607

1608
  """
1609
  # Internal sizes are always in Mebibytes; if the following "dd" command
1610
  # should use a different block size the offset and size given to this
1611
  # function must be adjusted accordingly before being passed to "dd".
1612
  block_size = 1024 * 1024
1613

    
1614
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1615
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
1616
         "count=%d" % size]
1617
  result = utils.RunCmd(cmd)
1618

    
1619
  if result.failed:
1620
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1621
          result.fail_reason, result.output)
1622

    
1623

    
1624
def BlockdevWipe(disk, offset, size):
1625
  """Wipes a block device.
1626

1627
  @type disk: L{objects.Disk}
1628
  @param disk: the disk object we want to wipe
1629
  @type offset: int
1630
  @param offset: The offset in MiB in the file
1631
  @type size: int
1632
  @param size: The size in MiB to write
1633

1634
  """
1635
  try:
1636
    rdev = _RecursiveFindBD(disk)
1637
  except errors.BlockDeviceError:
1638
    rdev = None
1639

    
1640
  if not rdev:
1641
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1642

    
1643
  # Do cross verify some of the parameters
1644
  if offset < 0:
1645
    _Fail("Negative offset")
1646
  if size < 0:
1647
    _Fail("Negative size")
1648
  if offset > rdev.size:
1649
    _Fail("Offset is bigger than device size")
1650
  if (offset + size) > rdev.size:
1651
    _Fail("The provided offset and size to wipe is bigger than device size")
1652

    
1653
  _WipeDevice(rdev.dev_path, offset, size)
1654

    
1655

    
1656
def BlockdevPauseResumeSync(disks, pause):
1657
  """Pause or resume the sync of the block device.
1658

1659
  @type disks: list of L{objects.Disk}
1660
  @param disks: the disks object we want to pause/resume
1661
  @type pause: bool
1662
  @param pause: Wheater to pause or resume
1663

1664
  """
1665
  success = []
1666
  for disk in disks:
1667
    try:
1668
      rdev = _RecursiveFindBD(disk)
1669
    except errors.BlockDeviceError:
1670
      rdev = None
1671

    
1672
    if not rdev:
1673
      success.append((False, ("Cannot change sync for device %s:"
1674
                              " device not found" % disk.iv_name)))
1675
      continue
1676

    
1677
    result = rdev.PauseResumeSync(pause)
1678

    
1679
    if result:
1680
      success.append((result, None))
1681
    else:
1682
      if pause:
1683
        msg = "Pause"
1684
      else:
1685
        msg = "Resume"
1686
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1687

    
1688
  return success
1689

    
1690

    
1691
def BlockdevRemove(disk):
1692
  """Remove a block device.
1693

1694
  @note: This is intended to be called recursively.
1695

1696
  @type disk: L{objects.Disk}
1697
  @param disk: the disk object we should remove
1698
  @rtype: boolean
1699
  @return: the success of the operation
1700

1701
  """
1702
  msgs = []
1703
  try:
1704
    rdev = _RecursiveFindBD(disk)
1705
  except errors.BlockDeviceError, err:
1706
    # probably can't attach
1707
    logging.info("Can't attach to device %s in remove", disk)
1708
    rdev = None
1709
  if rdev is not None:
1710
    r_path = rdev.dev_path
1711
    try:
1712
      rdev.Remove()
1713
    except errors.BlockDeviceError, err:
1714
      msgs.append(str(err))
1715
    if not msgs:
1716
      DevCacheManager.RemoveCache(r_path)
1717

    
1718
  if disk.children:
1719
    for child in disk.children:
1720
      try:
1721
        BlockdevRemove(child)
1722
      except RPCFail, err:
1723
        msgs.append(str(err))
1724

    
1725
  if msgs:
1726
    _Fail("; ".join(msgs))
1727

    
1728

    
1729
def _RecursiveAssembleBD(disk, owner, as_primary):
1730
  """Activate a block device for an instance.
1731

1732
  This is run on the primary and secondary nodes for an instance.
1733

1734
  @note: this function is called recursively.
1735

1736
  @type disk: L{objects.Disk}
1737
  @param disk: the disk we try to assemble
1738
  @type owner: str
1739
  @param owner: the name of the instance which owns the disk
1740
  @type as_primary: boolean
1741
  @param as_primary: if we should make the block device
1742
      read/write
1743

1744
  @return: the assembled device or None (in case no device
1745
      was assembled)
1746
  @raise errors.BlockDeviceError: in case there is an error
1747
      during the activation of the children or the device
1748
      itself
1749

1750
  """
1751
  children = []
1752
  if disk.children:
1753
    mcn = disk.ChildrenNeeded()
1754
    if mcn == -1:
1755
      mcn = 0 # max number of Nones allowed
1756
    else:
1757
      mcn = len(disk.children) - mcn # max number of Nones
1758
    for chld_disk in disk.children:
1759
      try:
1760
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1761
      except errors.BlockDeviceError, err:
1762
        if children.count(None) >= mcn:
1763
          raise
1764
        cdev = None
1765
        logging.error("Error in child activation (but continuing): %s",
1766
                      str(err))
1767
      children.append(cdev)
1768

    
1769
  if as_primary or disk.AssembleOnSecondary():
1770
    r_dev = bdev.Assemble(disk, children)
1771
    result = r_dev
1772
    if as_primary or disk.OpenOnSecondary():
1773
      r_dev.Open()
1774
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1775
                                as_primary, disk.iv_name)
1776

    
1777
  else:
1778
    result = True
1779
  return result
1780

    
1781

    
1782
def BlockdevAssemble(disk, owner, as_primary, idx):
1783
  """Activate a block device for an instance.
1784

1785
  This is a wrapper over _RecursiveAssembleBD.
1786

1787
  @rtype: str or boolean
1788
  @return: a C{/dev/...} path for primary nodes, and
1789
      C{True} for secondary nodes
1790

1791
  """
1792
  try:
1793
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1794
    if isinstance(result, bdev.BlockDev):
1795
      # pylint: disable=E1103
1796
      result = result.dev_path
1797
      if as_primary:
1798
        _SymlinkBlockDev(owner, result, idx)
1799
  except errors.BlockDeviceError, err:
1800
    _Fail("Error while assembling disk: %s", err, exc=True)
1801
  except OSError, err:
1802
    _Fail("Error while symlinking disk: %s", err, exc=True)
1803

    
1804
  return result
1805

    
1806

    
1807
def BlockdevShutdown(disk):
1808
  """Shut down a block device.
1809

1810
  First, if the device is assembled (Attach() is successful), then
1811
  the device is shutdown. Then the children of the device are
1812
  shutdown.
1813

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

1818
  @type disk: L{objects.Disk}
1819
  @param disk: the description of the disk we should
1820
      shutdown
1821
  @rtype: None
1822

1823
  """
1824
  msgs = []
1825
  r_dev = _RecursiveFindBD(disk)
1826
  if r_dev is not None:
1827
    r_path = r_dev.dev_path
1828
    try:
1829
      r_dev.Shutdown()
1830
      DevCacheManager.RemoveCache(r_path)
1831
    except errors.BlockDeviceError, err:
1832
      msgs.append(str(err))
1833

    
1834
  if disk.children:
1835
    for child in disk.children:
1836
      try:
1837
        BlockdevShutdown(child)
1838
      except RPCFail, err:
1839
        msgs.append(str(err))
1840

    
1841
  if msgs:
1842
    _Fail("; ".join(msgs))
1843

    
1844

    
1845
def BlockdevAddchildren(parent_cdev, new_cdevs):
1846
  """Extend a mirrored block device.
1847

1848
  @type parent_cdev: L{objects.Disk}
1849
  @param parent_cdev: the disk to which we should add children
1850
  @type new_cdevs: list of L{objects.Disk}
1851
  @param new_cdevs: the list of children which we should add
1852
  @rtype: None
1853

1854
  """
1855
  parent_bdev = _RecursiveFindBD(parent_cdev)
1856
  if parent_bdev is None:
1857
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1858
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1859
  if new_bdevs.count(None) > 0:
1860
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1861
  parent_bdev.AddChildren(new_bdevs)
1862

    
1863

    
1864
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1865
  """Shrink a mirrored block device.
1866

1867
  @type parent_cdev: L{objects.Disk}
1868
  @param parent_cdev: the disk from which we should remove children
1869
  @type new_cdevs: list of L{objects.Disk}
1870
  @param new_cdevs: the list of children which we should remove
1871
  @rtype: None
1872

1873
  """
1874
  parent_bdev = _RecursiveFindBD(parent_cdev)
1875
  if parent_bdev is None:
1876
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1877
  devs = []
1878
  for disk in new_cdevs:
1879
    rpath = disk.StaticDevPath()
1880
    if rpath is None:
1881
      bd = _RecursiveFindBD(disk)
1882
      if bd is None:
1883
        _Fail("Can't find device %s while removing children", disk)
1884
      else:
1885
        devs.append(bd.dev_path)
1886
    else:
1887
      if not utils.IsNormAbsPath(rpath):
1888
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
1889
      devs.append(rpath)
1890
  parent_bdev.RemoveChildren(devs)
1891

    
1892

    
1893
def BlockdevGetmirrorstatus(disks):
1894
  """Get the mirroring status of a list of devices.
1895

1896
  @type disks: list of L{objects.Disk}
1897
  @param disks: the list of disks which we should query
1898
  @rtype: disk
1899
  @return: List of L{objects.BlockDevStatus}, one for each disk
1900
  @raise errors.BlockDeviceError: if any of the disks cannot be
1901
      found
1902

1903
  """
1904
  stats = []
1905
  for dsk in disks:
1906
    rbd = _RecursiveFindBD(dsk)
1907
    if rbd is None:
1908
      _Fail("Can't find device %s", dsk)
1909

    
1910
    stats.append(rbd.CombinedSyncStatus())
1911

    
1912
  return stats
1913

    
1914

    
1915
def BlockdevGetmirrorstatusMulti(disks):
1916
  """Get the mirroring status of a list of devices.
1917

1918
  @type disks: list of L{objects.Disk}
1919
  @param disks: the list of disks which we should query
1920
  @rtype: disk
1921
  @return: List of tuples, (bool, status), one for each disk; bool denotes
1922
    success/failure, status is L{objects.BlockDevStatus} on success, string
1923
    otherwise
1924

1925
  """
1926
  result = []
1927
  for disk in disks:
1928
    try:
1929
      rbd = _RecursiveFindBD(disk)
1930
      if rbd is None:
1931
        result.append((False, "Can't find device %s" % disk))
1932
        continue
1933

    
1934
      status = rbd.CombinedSyncStatus()
1935
    except errors.BlockDeviceError, err:
1936
      logging.exception("Error while getting disk status")
1937
      result.append((False, str(err)))
1938
    else:
1939
      result.append((True, status))
1940

    
1941
  assert len(disks) == len(result)
1942

    
1943
  return result
1944

    
1945

    
1946
def _RecursiveFindBD(disk):
1947
  """Check if a device is activated.
1948

1949
  If so, return information about the real device.
1950

1951
  @type disk: L{objects.Disk}
1952
  @param disk: the disk object we need to find
1953

1954
  @return: None if the device can't be found,
1955
      otherwise the device instance
1956

1957
  """
1958
  children = []
1959
  if disk.children:
1960
    for chdisk in disk.children:
1961
      children.append(_RecursiveFindBD(chdisk))
1962

    
1963
  return bdev.FindDevice(disk, children)
1964

    
1965

    
1966
def _OpenRealBD(disk):
1967
  """Opens the underlying block device of a disk.
1968

1969
  @type disk: L{objects.Disk}
1970
  @param disk: the disk object we want to open
1971

1972
  """
1973
  real_disk = _RecursiveFindBD(disk)
1974
  if real_disk is None:
1975
    _Fail("Block device '%s' is not set up", disk)
1976

    
1977
  real_disk.Open()
1978

    
1979
  return real_disk
1980

    
1981

    
1982
def BlockdevFind(disk):
1983
  """Check if a device is activated.
1984

1985
  If it is, return information about the real device.
1986

1987
  @type disk: L{objects.Disk}
1988
  @param disk: the disk to find
1989
  @rtype: None or objects.BlockDevStatus
1990
  @return: None if the disk cannot be found, otherwise a the current
1991
           information
1992

1993
  """
1994
  try:
1995
    rbd = _RecursiveFindBD(disk)
1996
  except errors.BlockDeviceError, err:
1997
    _Fail("Failed to find device: %s", err, exc=True)
1998

    
1999
  if rbd is None:
2000
    return None
2001

    
2002
  return rbd.GetSyncStatus()
2003

    
2004

    
2005
def BlockdevGetsize(disks):
2006
  """Computes the size of the given disks.
2007

2008
  If a disk is not found, returns None instead.
2009

2010
  @type disks: list of L{objects.Disk}
2011
  @param disks: the list of disk to compute the size for
2012
  @rtype: list
2013
  @return: list with elements None if the disk cannot be found,
2014
      otherwise the size
2015

2016
  """
2017
  result = []
2018
  for cf in disks:
2019
    try:
2020
      rbd = _RecursiveFindBD(cf)
2021
    except errors.BlockDeviceError:
2022
      result.append(None)
2023
      continue
2024
    if rbd is None:
2025
      result.append(None)
2026
    else:
2027
      result.append(rbd.GetActualSize())
2028
  return result
2029

    
2030

    
2031
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2032
  """Export a block device to a remote node.
2033

2034
  @type disk: L{objects.Disk}
2035
  @param disk: the description of the disk to export
2036
  @type dest_node: str
2037
  @param dest_node: the destination node to export to
2038
  @type dest_path: str
2039
  @param dest_path: the destination path on the target node
2040
  @type cluster_name: str
2041
  @param cluster_name: the cluster name, needed for SSH hostalias
2042
  @rtype: None
2043

2044
  """
2045
  real_disk = _OpenRealBD(disk)
2046

    
2047
  # the block size on the read dd is 1MiB to match our units
2048
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2049
                               "dd if=%s bs=1048576 count=%s",
2050
                               real_disk.dev_path, str(disk.size))
2051

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

    
2061
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2062
                                                   constants.SSH_LOGIN_USER,
2063
                                                   destcmd)
2064

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

    
2068
  result = utils.RunCmd(["bash", "-c", command])
2069

    
2070
  if result.failed:
2071
    _Fail("Disk copy command '%s' returned error: %s"
2072
          " output: %s", command, result.fail_reason, result.output)
2073

    
2074

    
2075
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2076
  """Write a file to the filesystem.
2077

2078
  This allows the master to overwrite(!) a file. It will only perform
2079
  the operation if the file belongs to a list of configuration files.
2080

2081
  @type file_name: str
2082
  @param file_name: the target file name
2083
  @type data: str
2084
  @param data: the new contents of the file
2085
  @type mode: int
2086
  @param mode: the mode to give the file (can be None)
2087
  @type uid: string
2088
  @param uid: the owner of the file
2089
  @type gid: string
2090
  @param gid: the group of the file
2091
  @type atime: float
2092
  @param atime: the atime to set on the file (can be None)
2093
  @type mtime: float
2094
  @param mtime: the mtime to set on the file (can be None)
2095
  @rtype: None
2096

2097
  """
2098
  file_name = vcluster.LocalizeVirtualPath(file_name)
2099

    
2100
  if not os.path.isabs(file_name):
2101
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2102

    
2103
  if file_name not in _ALLOWED_UPLOAD_FILES:
2104
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2105
          file_name)
2106

    
2107
  raw_data = _Decompress(data)
2108

    
2109
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2110
    _Fail("Invalid username/groupname type")
2111

    
2112
  getents = runtime.GetEnts()
2113
  uid = getents.LookupUser(uid)
2114
  gid = getents.LookupGroup(gid)
2115

    
2116
  utils.SafeWriteFile(file_name, None,
2117
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2118
                      atime=atime, mtime=mtime)
2119

    
2120

    
2121
def RunOob(oob_program, command, node, timeout):
2122
  """Executes oob_program with given command on given node.
2123

2124
  @param oob_program: The path to the executable oob_program
2125
  @param command: The command to invoke on oob_program
2126
  @param node: The node given as an argument to the program
2127
  @param timeout: Timeout after which we kill the oob program
2128

2129
  @return: stdout
2130
  @raise RPCFail: If execution fails for some reason
2131

2132
  """
2133
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2134

    
2135
  if result.failed:
2136
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2137
          result.fail_reason, result.output)
2138

    
2139
  return result.stdout
2140

    
2141

    
2142
def _OSOndiskAPIVersion(os_dir):
2143
  """Compute and return the API version of a given OS.
2144

2145
  This function will try to read the API version of the OS residing in
2146
  the 'os_dir' directory.
2147

2148
  @type os_dir: str
2149
  @param os_dir: the directory in which we should look for the OS
2150
  @rtype: tuple
2151
  @return: tuple (status, data) with status denoting the validity and
2152
      data holding either the vaid versions or an error message
2153

2154
  """
2155
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2156

    
2157
  try:
2158
    st = os.stat(api_file)
2159
  except EnvironmentError, err:
2160
    return False, ("Required file '%s' not found under path %s: %s" %
2161
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2162

    
2163
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2164
    return False, ("File '%s' in %s is not a regular file" %
2165
                   (constants.OS_API_FILE, os_dir))
2166

    
2167
  try:
2168
    api_versions = utils.ReadFile(api_file).splitlines()
2169
  except EnvironmentError, err:
2170
    return False, ("Error while reading the API version file at %s: %s" %
2171
                   (api_file, utils.ErrnoOrStr(err)))
2172

    
2173
  try:
2174
    api_versions = [int(version.strip()) for version in api_versions]
2175
  except (TypeError, ValueError), err:
2176
    return False, ("API version(s) can't be converted to integer: %s" %
2177
                   str(err))
2178

    
2179
  return True, api_versions
2180

    
2181

    
2182
def DiagnoseOS(top_dirs=None):
2183
  """Compute the validity for all OSes.
2184

2185
  @type top_dirs: list
2186
  @param top_dirs: the list of directories in which to
2187
      search (if not given defaults to
2188
      L{pathutils.OS_SEARCH_PATH})
2189
  @rtype: list of L{objects.OS}
2190
  @return: a list of tuples (name, path, status, diagnose, variants,
2191
      parameters, api_version) for all (potential) OSes under all
2192
      search paths, where:
2193
          - name is the (potential) OS name
2194
          - path is the full path to the OS
2195
          - status True/False is the validity of the OS
2196
          - diagnose is the error message for an invalid OS, otherwise empty
2197
          - variants is a list of supported OS variants, if any
2198
          - parameters is a list of (name, help) parameters, if any
2199
          - api_version is a list of support OS API versions
2200

2201
  """
2202
  if top_dirs is None:
2203
    top_dirs = pathutils.OS_SEARCH_PATH
2204

    
2205
  result = []
2206
  for dir_name in top_dirs:
2207
    if os.path.isdir(dir_name):
2208
      try:
2209
        f_names = utils.ListVisibleFiles(dir_name)
2210
      except EnvironmentError, err:
2211
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2212
        break
2213
      for name in f_names:
2214
        os_path = utils.PathJoin(dir_name, name)
2215
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2216
        if status:
2217
          diagnose = ""
2218
          variants = os_inst.supported_variants
2219
          parameters = os_inst.supported_parameters
2220
          api_versions = os_inst.api_versions
2221
        else:
2222
          diagnose = os_inst
2223
          variants = parameters = api_versions = []
2224
        result.append((name, os_path, status, diagnose, variants,
2225
                       parameters, api_versions))
2226

    
2227
  return result
2228

    
2229

    
2230
def _TryOSFromDisk(name, base_dir=None):
2231
  """Create an OS instance from disk.
2232

2233
  This function will return an OS instance if the given name is a
2234
  valid OS name.
2235

2236
  @type base_dir: string
2237
  @keyword base_dir: Base directory containing OS installations.
2238
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2239
  @rtype: tuple
2240
  @return: success and either the OS instance if we find a valid one,
2241
      or error message
2242

2243
  """
2244
  if base_dir is None:
2245
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2246
  else:
2247
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2248

    
2249
  if os_dir is None:
2250
    return False, "Directory for OS %s not found in search path" % name
2251

    
2252
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2253
  if not status:
2254
    # push the error up
2255
    return status, api_versions
2256

    
2257
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2258
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2259
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2260

    
2261
  # OS Files dictionary, we will populate it with the absolute path
2262
  # names; if the value is True, then it is a required file, otherwise
2263
  # an optional one
2264
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2265

    
2266
  if max(api_versions) >= constants.OS_API_V15:
2267
    os_files[constants.OS_VARIANTS_FILE] = False
2268

    
2269
  if max(api_versions) >= constants.OS_API_V20:
2270
    os_files[constants.OS_PARAMETERS_FILE] = True
2271
  else:
2272
    del os_files[constants.OS_SCRIPT_VERIFY]
2273

    
2274
  for (filename, required) in os_files.items():
2275
    os_files[filename] = utils.PathJoin(os_dir, filename)
2276

    
2277
    try:
2278
      st = os.stat(os_files[filename])
2279
    except EnvironmentError, err:
2280
      if err.errno == errno.ENOENT and not required:
2281
        del os_files[filename]
2282
        continue
2283
      return False, ("File '%s' under path '%s' is missing (%s)" %
2284
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2285

    
2286
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2287
      return False, ("File '%s' under path '%s' is not a regular file" %
2288
                     (filename, os_dir))
2289

    
2290
    if filename in constants.OS_SCRIPTS:
2291
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2292
        return False, ("File '%s' under path '%s' is not executable" %
2293
                       (filename, os_dir))
2294

    
2295
  variants = []
2296
  if constants.OS_VARIANTS_FILE in os_files:
2297
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2298
    try:
2299
      variants = \
2300
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2301
    except EnvironmentError, err:
2302
      # we accept missing files, but not other errors
2303
      if err.errno != errno.ENOENT:
2304
        return False, ("Error while reading the OS variants file at %s: %s" %
2305
                       (variants_file, utils.ErrnoOrStr(err)))
2306

    
2307
  parameters = []
2308
  if constants.OS_PARAMETERS_FILE in os_files:
2309
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2310
    try:
2311
      parameters = utils.ReadFile(parameters_file).splitlines()
2312
    except EnvironmentError, err:
2313
      return False, ("Error while reading the OS parameters file at %s: %s" %
2314
                     (parameters_file, utils.ErrnoOrStr(err)))
2315
    parameters = [v.split(None, 1) for v in parameters]
2316

    
2317
  os_obj = objects.OS(name=name, path=os_dir,
2318
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2319
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2320
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2321
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2322
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2323
                                                 None),
2324
                      supported_variants=variants,
2325
                      supported_parameters=parameters,
2326
                      api_versions=api_versions)
2327
  return True, os_obj
2328

    
2329

    
2330
def OSFromDisk(name, base_dir=None):
2331
  """Create an OS instance from disk.
2332

2333
  This function will return an OS instance if the given name is a
2334
  valid OS name. Otherwise, it will raise an appropriate
2335
  L{RPCFail} exception, detailing why this is not a valid OS.
2336

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

2340
  @type base_dir: string
2341
  @keyword base_dir: Base directory containing OS installations.
2342
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2343
  @rtype: L{objects.OS}
2344
  @return: the OS instance if we find a valid one
2345
  @raise RPCFail: if we don't find a valid OS
2346

2347
  """
2348
  name_only = objects.OS.GetName(name)
2349
  status, payload = _TryOSFromDisk(name_only, base_dir)
2350

    
2351
  if not status:
2352
    _Fail(payload)
2353

    
2354
  return payload
2355

    
2356

    
2357
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2358
  """Calculate the basic environment for an os script.
2359

2360
  @type os_name: str
2361
  @param os_name: full operating system name (including variant)
2362
  @type inst_os: L{objects.OS}
2363
  @param inst_os: operating system for which the environment is being built
2364
  @type os_params: dict
2365
  @param os_params: the OS parameters
2366
  @type debug: integer
2367
  @param debug: debug level (0 or 1, for OS Api 10)
2368
  @rtype: dict
2369
  @return: dict of environment variables
2370
  @raise errors.BlockDeviceError: if the block device
2371
      cannot be found
2372

2373
  """
2374
  result = {}
2375
  api_version = \
2376
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2377
  result["OS_API_VERSION"] = "%d" % api_version
2378
  result["OS_NAME"] = inst_os.name
2379
  result["DEBUG_LEVEL"] = "%d" % debug
2380

    
2381
  # OS variants
2382
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2383
    variant = objects.OS.GetVariant(os_name)
2384
    if not variant:
2385
      variant = inst_os.supported_variants[0]
2386
  else:
2387
    variant = ""
2388
  result["OS_VARIANT"] = variant
2389

    
2390
  # OS params
2391
  for pname, pvalue in os_params.items():
2392
    result["OSP_%s" % pname.upper()] = pvalue
2393

    
2394
  # Set a default path otherwise programs called by OS scripts (or
2395
  # even hooks called from OS scripts) might break, and we don't want
2396
  # to have each script require setting a PATH variable
2397
  result["PATH"] = constants.HOOKS_PATH
2398

    
2399
  return result
2400

    
2401

    
2402
def OSEnvironment(instance, inst_os, debug=0):
2403
  """Calculate the environment for an os script.
2404

2405
  @type instance: L{objects.Instance}
2406
  @param instance: target instance for the os script run
2407
  @type inst_os: L{objects.OS}
2408
  @param inst_os: operating system for which the environment is being built
2409
  @type debug: integer
2410
  @param debug: debug level (0 or 1, for OS Api 10)
2411
  @rtype: dict
2412
  @return: dict of environment variables
2413
  @raise errors.BlockDeviceError: if the block device
2414
      cannot be found
2415

2416
  """
2417
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2418

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

    
2422
  result["HYPERVISOR"] = instance.hypervisor
2423
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2424
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2425
  result["INSTANCE_SECONDARY_NODES"] = \
2426
      ("%s" % " ".join(instance.secondary_nodes))
2427

    
2428
  # Disks
2429
  for idx, disk in enumerate(instance.disks):
2430
    real_disk = _OpenRealBD(disk)
2431
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2432
    result["DISK_%d_ACCESS" % idx] = disk.mode
2433
    if constants.HV_DISK_TYPE in instance.hvparams:
2434
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2435
        instance.hvparams[constants.HV_DISK_TYPE]
2436
    if disk.dev_type in constants.LDS_BLOCK:
2437
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2438
    elif disk.dev_type == constants.LD_FILE:
2439
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2440
        "file:%s" % disk.physical_id[0]
2441

    
2442
  # NICs
2443
  for idx, nic in enumerate(instance.nics):
2444
    result["NIC_%d_MAC" % idx] = nic.mac
2445
    if nic.ip:
2446
      result["NIC_%d_IP" % idx] = nic.ip
2447
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2448
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2449
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2450
    if nic.nicparams[constants.NIC_LINK]:
2451
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2452
    if constants.HV_NIC_TYPE in instance.hvparams:
2453
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2454
        instance.hvparams[constants.HV_NIC_TYPE]
2455

    
2456
  # HV/BE params
2457
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2458
    for key, value in source.items():
2459
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2460

    
2461
  return result
2462

    
2463

    
2464
def BlockdevGrow(disk, amount, dryrun, backingstore):
2465
  """Grow a stack of block devices.
2466

2467
  This function is called recursively, with the childrens being the
2468
  first ones to resize.
2469

2470
  @type disk: L{objects.Disk}
2471
  @param disk: the disk to be grown
2472
  @type amount: integer
2473
  @param amount: the amount (in mebibytes) to grow with
2474
  @type dryrun: boolean
2475
  @param dryrun: whether to execute the operation in simulation mode
2476
      only, without actually increasing the size
2477
  @param backingstore: whether to execute the operation on backing storage
2478
      only, or on "logical" storage only; e.g. DRBD is logical storage,
2479
      whereas LVM, file, RBD are backing storage
2480
  @rtype: (status, result)
2481
  @return: a tuple with the status of the operation (True/False), and
2482
      the errors message if status is False
2483

2484
  """
2485
  r_dev = _RecursiveFindBD(disk)
2486
  if r_dev is None:
2487
    _Fail("Cannot find block device %s", disk)
2488

    
2489
  try:
2490
    r_dev.Grow(amount, dryrun, backingstore)
2491
  except errors.BlockDeviceError, err:
2492
    _Fail("Failed to grow block device: %s", err, exc=True)
2493

    
2494

    
2495
def BlockdevSnapshot(disk):
2496
  """Create a snapshot copy of a block device.
2497

2498
  This function is called recursively, and the snapshot is actually created
2499
  just for the leaf lvm backend device.
2500

2501
  @type disk: L{objects.Disk}
2502
  @param disk: the disk to be snapshotted
2503
  @rtype: string
2504
  @return: snapshot disk ID as (vg, lv)
2505

2506
  """
2507
  if disk.dev_type == constants.LD_DRBD8:
2508
    if not disk.children:
2509
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2510
            disk.unique_id)
2511
    return BlockdevSnapshot(disk.children[0])
2512
  elif disk.dev_type == constants.LD_LV:
2513
    r_dev = _RecursiveFindBD(disk)
2514
    if r_dev is not None:
2515
      # FIXME: choose a saner value for the snapshot size
2516
      # let's stay on the safe side and ask for the full size, for now
2517
      return r_dev.Snapshot(disk.size)
2518
    else:
2519
      _Fail("Cannot find block device %s", disk)
2520
  else:
2521
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2522
          disk.unique_id, disk.dev_type)
2523

    
2524

    
2525
def BlockdevSetInfo(disk, info):
2526
  """Sets 'metadata' information on block devices.
2527

2528
  This function sets 'info' metadata on block devices. Initial
2529
  information is set at device creation; this function should be used
2530
  for example after renames.
2531

2532
  @type disk: L{objects.Disk}
2533
  @param disk: the disk to be grown
2534
  @type info: string
2535
  @param info: new 'info' metadata
2536
  @rtype: (status, result)
2537
  @return: a tuple with the status of the operation (True/False), and
2538
      the errors message if status is False
2539

2540
  """
2541
  r_dev = _RecursiveFindBD(disk)
2542
  if r_dev is None:
2543
    _Fail("Cannot find block device %s", disk)
2544

    
2545
  try:
2546
    r_dev.SetInfo(info)
2547
  except errors.BlockDeviceError, err:
2548
    _Fail("Failed to set information on block device: %s", err, exc=True)
2549

    
2550

    
2551
def FinalizeExport(instance, snap_disks):
2552
  """Write out the export configuration information.
2553

2554
  @type instance: L{objects.Instance}
2555
  @param instance: the instance which we export, used for
2556
      saving configuration
2557
  @type snap_disks: list of L{objects.Disk}
2558
  @param snap_disks: list of snapshot block devices, which
2559
      will be used to get the actual name of the dump file
2560

2561
  @rtype: None
2562

2563
  """
2564
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
2565
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
2566

    
2567
  config = objects.SerializableConfigParser()
2568

    
2569
  config.add_section(constants.INISECT_EXP)
2570
  config.set(constants.INISECT_EXP, "version", "0")
2571
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2572
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2573
  config.set(constants.INISECT_EXP, "os", instance.os)
2574
  config.set(constants.INISECT_EXP, "compression", "none")
2575

    
2576
  config.add_section(constants.INISECT_INS)
2577
  config.set(constants.INISECT_INS, "name", instance.name)
2578
  config.set(constants.INISECT_INS, "maxmem", "%d" %
2579
             instance.beparams[constants.BE_MAXMEM])
2580
  config.set(constants.INISECT_INS, "minmem", "%d" %
2581
             instance.beparams[constants.BE_MINMEM])
2582
  # "memory" is deprecated, but useful for exporting to old ganeti versions
2583
  config.set(constants.INISECT_INS, "memory", "%d" %
2584
             instance.beparams[constants.BE_MAXMEM])
2585
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2586
             instance.beparams[constants.BE_VCPUS])
2587
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2588
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2589
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2590

    
2591
  nic_total = 0
2592
  for nic_count, nic in enumerate(instance.nics):
2593
    nic_total += 1
2594
    config.set(constants.INISECT_INS, "nic%d_mac" %
2595
               nic_count, "%s" % nic.mac)
2596
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2597
    for param in constants.NICS_PARAMETER_TYPES:
2598
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2599
                 "%s" % nic.nicparams.get(param, None))
2600
  # TODO: redundant: on load can read nics until it doesn't exist
2601
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2602

    
2603
  disk_total = 0
2604
  for disk_count, disk in enumerate(snap_disks):
2605
    if disk:
2606
      disk_total += 1
2607
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2608
                 ("%s" % disk.iv_name))
2609
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2610
                 ("%s" % disk.physical_id[1]))
2611
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2612
                 ("%d" % disk.size))
2613

    
2614
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2615

    
2616
  # New-style hypervisor/backend parameters
2617

    
2618
  config.add_section(constants.INISECT_HYP)
2619
  for name, value in instance.hvparams.items():
2620
    if name not in constants.HVC_GLOBALS:
2621
      config.set(constants.INISECT_HYP, name, str(value))
2622

    
2623
  config.add_section(constants.INISECT_BEP)
2624
  for name, value in instance.beparams.items():
2625
    config.set(constants.INISECT_BEP, name, str(value))
2626

    
2627
  config.add_section(constants.INISECT_OSP)
2628
  for name, value in instance.osparams.items():
2629
    config.set(constants.INISECT_OSP, name, str(value))
2630

    
2631
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2632
                  data=config.Dumps())
2633
  shutil.rmtree(finaldestdir, ignore_errors=True)
2634
  shutil.move(destdir, finaldestdir)
2635

    
2636

    
2637
def ExportInfo(dest):
2638
  """Get export configuration information.
2639

2640
  @type dest: str
2641
  @param dest: directory containing the export
2642

2643
  @rtype: L{objects.SerializableConfigParser}
2644
  @return: a serializable config file containing the
2645
      export info
2646

2647
  """
2648
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2649

    
2650
  config = objects.SerializableConfigParser()
2651
  config.read(cff)
2652

    
2653
  if (not config.has_section(constants.INISECT_EXP) or
2654
      not config.has_section(constants.INISECT_INS)):
2655
    _Fail("Export info file doesn't have the required fields")
2656

    
2657
  return config.Dumps()
2658

    
2659

    
2660
def ListExports():
2661
  """Return a list of exports currently available on this machine.
2662

2663
  @rtype: list
2664
  @return: list of the exports
2665

2666
  """
2667
  if os.path.isdir(pathutils.EXPORT_DIR):
2668
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
2669
  else:
2670
    _Fail("No exports directory")
2671

    
2672

    
2673
def RemoveExport(export):
2674
  """Remove an existing export from the node.
2675

2676
  @type export: str
2677
  @param export: the name of the export to remove
2678
  @rtype: None
2679

2680
  """
2681
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
2682

    
2683
  try:
2684
    shutil.rmtree(target)
2685
  except EnvironmentError, err:
2686
    _Fail("Error while removing the export: %s", err, exc=True)
2687

    
2688

    
2689
def BlockdevRename(devlist):
2690
  """Rename a list of block devices.
2691

2692
  @type devlist: list of tuples
2693
  @param devlist: list of tuples of the form  (disk,
2694
      new_logical_id, new_physical_id); disk is an
2695
      L{objects.Disk} object describing the current disk,
2696
      and new logical_id/physical_id is the name we
2697
      rename it to
2698
  @rtype: boolean
2699
  @return: True if all renames succeeded, False otherwise
2700

2701
  """
2702
  msgs = []
2703
  result = True
2704
  for disk, unique_id in devlist:
2705
    dev = _RecursiveFindBD(disk)
2706
    if dev is None:
2707
      msgs.append("Can't find device %s in rename" % str(disk))
2708
      result = False
2709
      continue
2710
    try:
2711
      old_rpath = dev.dev_path
2712
      dev.Rename(unique_id)
2713
      new_rpath = dev.dev_path
2714
      if old_rpath != new_rpath:
2715
        DevCacheManager.RemoveCache(old_rpath)
2716
        # FIXME: we should add the new cache information here, like:
2717
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2718
        # but we don't have the owner here - maybe parse from existing
2719
        # cache? for now, we only lose lvm data when we rename, which
2720
        # is less critical than DRBD or MD
2721
    except errors.BlockDeviceError, err:
2722
      msgs.append("Can't rename device '%s' to '%s': %s" %
2723
                  (dev, unique_id, err))
2724
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2725
      result = False
2726
  if not result:
2727
    _Fail("; ".join(msgs))
2728

    
2729

    
2730
def _TransformFileStorageDir(fs_dir):
2731
  """Checks whether given file_storage_dir is valid.
2732

2733
  Checks wheter the given fs_dir is within the cluster-wide default
2734
  file_storage_dir or the shared_file_storage_dir, which are stored in
2735
  SimpleStore. Only paths under those directories are allowed.
2736

2737
  @type fs_dir: str
2738
  @param fs_dir: the path to check
2739

2740
  @return: the normalized path if valid, None otherwise
2741

2742
  """
2743
  if not (constants.ENABLE_FILE_STORAGE or
2744
          constants.ENABLE_SHARED_FILE_STORAGE):
2745
    _Fail("File storage disabled at configure time")
2746
  cfg = _GetConfig()
2747
  fs_dir = os.path.normpath(fs_dir)
2748
  base_fstore = cfg.GetFileStorageDir()
2749
  base_shared = cfg.GetSharedFileStorageDir()
2750
  if not (utils.IsBelowDir(base_fstore, fs_dir) or
2751
          utils.IsBelowDir(base_shared, fs_dir)):
2752
    _Fail("File storage directory '%s' is not under base file"
2753
          " storage directory '%s' or shared storage directory '%s'",
2754
          fs_dir, base_fstore, base_shared)
2755
  return fs_dir
2756

    
2757

    
2758
def CreateFileStorageDir(file_storage_dir):
2759
  """Create file storage directory.
2760

2761
  @type file_storage_dir: str
2762
  @param file_storage_dir: directory to create
2763

2764
  @rtype: tuple
2765
  @return: tuple with first element a boolean indicating wheter dir
2766
      creation was successful or not
2767

2768
  """
2769
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2770
  if os.path.exists(file_storage_dir):
2771
    if not os.path.isdir(file_storage_dir):
2772
      _Fail("Specified storage dir '%s' is not a directory",
2773
            file_storage_dir)
2774
  else:
2775
    try:
2776
      os.makedirs(file_storage_dir, 0750)
2777
    except OSError, err:
2778
      _Fail("Cannot create file storage directory '%s': %s",
2779
            file_storage_dir, err, exc=True)
2780

    
2781

    
2782
def RemoveFileStorageDir(file_storage_dir):
2783
  """Remove file storage directory.
2784

2785
  Remove it only if it's empty. If not log an error and return.
2786

2787
  @type file_storage_dir: str
2788
  @param file_storage_dir: the directory we should cleanup
2789
  @rtype: tuple (success,)
2790
  @return: tuple of one element, C{success}, denoting
2791
      whether the operation was successful
2792

2793
  """
2794
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2795
  if os.path.exists(file_storage_dir):
2796
    if not os.path.isdir(file_storage_dir):
2797
      _Fail("Specified Storage directory '%s' is not a directory",
2798
            file_storage_dir)
2799
    # deletes dir only if empty, otherwise we want to fail the rpc call
2800
    try:
2801
      os.rmdir(file_storage_dir)
2802
    except OSError, err:
2803
      _Fail("Cannot remove file storage directory '%s': %s",
2804
            file_storage_dir, err)
2805

    
2806

    
2807
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2808
  """Rename the file storage directory.
2809

2810
  @type old_file_storage_dir: str
2811
  @param old_file_storage_dir: the current path
2812
  @type new_file_storage_dir: str
2813
  @param new_file_storage_dir: the name we should rename to
2814
  @rtype: tuple (success,)
2815
  @return: tuple of one element, C{success}, denoting
2816
      whether the operation was successful
2817

2818
  """
2819
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2820
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2821
  if not os.path.exists(new_file_storage_dir):
2822
    if os.path.isdir(old_file_storage_dir):
2823
      try:
2824
        os.rename(old_file_storage_dir, new_file_storage_dir)
2825
      except OSError, err:
2826
        _Fail("Cannot rename '%s' to '%s': %s",
2827
              old_file_storage_dir, new_file_storage_dir, err)
2828
    else:
2829
      _Fail("Specified storage dir '%s' is not a directory",
2830
            old_file_storage_dir)
2831
  else:
2832
    if os.path.exists(old_file_storage_dir):
2833
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2834
            old_file_storage_dir, new_file_storage_dir)
2835

    
2836

    
2837
def _EnsureJobQueueFile(file_name):
2838
  """Checks whether the given filename is in the queue directory.
2839

2840
  @type file_name: str
2841
  @param file_name: the file name we should check
2842
  @rtype: None
2843
  @raises RPCFail: if the file is not valid
2844

2845
  """
2846
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
2847
    _Fail("Passed job queue file '%s' does not belong to"
2848
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
2849

    
2850

    
2851
def JobQueueUpdate(file_name, content):
2852
  """Updates a file in the queue directory.
2853

2854
  This is just a wrapper over L{utils.io.WriteFile}, with proper
2855
  checking.
2856

2857
  @type file_name: str
2858
  @param file_name: the job file name
2859
  @type content: str
2860
  @param content: the new job contents
2861
  @rtype: boolean
2862
  @return: the success of the operation
2863

2864
  """
2865
  file_name = vcluster.LocalizeVirtualPath(file_name)
2866

    
2867
  _EnsureJobQueueFile(file_name)
2868
  getents = runtime.GetEnts()
2869

    
2870
  # Write and replace the file atomically
2871
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
2872
                  gid=getents.masterd_gid)
2873

    
2874

    
2875
def JobQueueRename(old, new):
2876
  """Renames a job queue file.
2877

2878
  This is just a wrapper over os.rename with proper checking.
2879

2880
  @type old: str
2881
  @param old: the old (actual) file name
2882
  @type new: str
2883
  @param new: the desired file name
2884
  @rtype: tuple
2885
  @return: the success of the operation and payload
2886

2887
  """
2888
  old = vcluster.LocalizeVirtualPath(old)
2889
  new = vcluster.LocalizeVirtualPath(new)
2890

    
2891
  _EnsureJobQueueFile(old)
2892
  _EnsureJobQueueFile(new)
2893

    
2894
  getents = runtime.GetEnts()
2895

    
2896
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0700,
2897
                   dir_uid=getents.masterd_uid, dir_gid=getents.masterd_gid)
2898

    
2899

    
2900
def BlockdevClose(instance_name, disks):
2901
  """Closes the given block devices.
2902

2903
  This means they will be switched to secondary mode (in case of
2904
  DRBD).
2905

2906
  @param instance_name: if the argument is not empty, the symlinks
2907
      of this instance will be removed
2908
  @type disks: list of L{objects.Disk}
2909
  @param disks: the list of disks to be closed
2910
  @rtype: tuple (success, message)
2911
  @return: a tuple of success and message, where success
2912
      indicates the succes of the operation, and message
2913
      which will contain the error details in case we
2914
      failed
2915

2916
  """
2917
  bdevs = []
2918
  for cf in disks:
2919
    rd = _RecursiveFindBD(cf)
2920
    if rd is None:
2921
      _Fail("Can't find device %s", cf)
2922
    bdevs.append(rd)
2923

    
2924
  msg = []
2925
  for rd in bdevs:
2926
    try:
2927
      rd.Close()
2928
    except errors.BlockDeviceError, err:
2929
      msg.append(str(err))
2930
  if msg:
2931
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2932
  else:
2933
    if instance_name:
2934
      _RemoveBlockDevLinks(instance_name, disks)
2935

    
2936

    
2937
def ValidateHVParams(hvname, hvparams):
2938
  """Validates the given hypervisor parameters.
2939

2940
  @type hvname: string
2941
  @param hvname: the hypervisor name
2942
  @type hvparams: dict
2943
  @param hvparams: the hypervisor parameters to be validated
2944
  @rtype: None
2945

2946
  """
2947
  try:
2948
    hv_type = hypervisor.GetHypervisor(hvname)
2949
    hv_type.ValidateParameters(hvparams)
2950
  except errors.HypervisorError, err:
2951
    _Fail(str(err), log=False)
2952

    
2953

    
2954
def _CheckOSPList(os_obj, parameters):
2955
  """Check whether a list of parameters is supported by the OS.
2956

2957
  @type os_obj: L{objects.OS}
2958
  @param os_obj: OS object to check
2959
  @type parameters: list
2960
  @param parameters: the list of parameters to check
2961

2962
  """
2963
  supported = [v[0] for v in os_obj.supported_parameters]
2964
  delta = frozenset(parameters).difference(supported)
2965
  if delta:
2966
    _Fail("The following parameters are not supported"
2967
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
2968

    
2969

    
2970
def ValidateOS(required, osname, checks, osparams):
2971
  """Validate the given OS' parameters.
2972

2973
  @type required: boolean
2974
  @param required: whether absence of the OS should translate into
2975
      failure or not
2976
  @type osname: string
2977
  @param osname: the OS to be validated
2978
  @type checks: list
2979
  @param checks: list of the checks to run (currently only 'parameters')
2980
  @type osparams: dict
2981
  @param osparams: dictionary with OS parameters
2982
  @rtype: boolean
2983
  @return: True if the validation passed, or False if the OS was not
2984
      found and L{required} was false
2985

2986
  """
2987
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
2988
    _Fail("Unknown checks required for OS %s: %s", osname,
2989
          set(checks).difference(constants.OS_VALIDATE_CALLS))
2990

    
2991
  name_only = objects.OS.GetName(osname)
2992
  status, tbv = _TryOSFromDisk(name_only, None)
2993

    
2994
  if not status:
2995
    if required:
2996
      _Fail(tbv)
2997
    else:
2998
      return False
2999

    
3000
  if max(tbv.api_versions) < constants.OS_API_V20:
3001
    return True
3002

    
3003
  if constants.OS_VALIDATE_PARAMETERS in checks:
3004
    _CheckOSPList(tbv, osparams.keys())
3005

    
3006
  validate_env = OSCoreEnv(osname, tbv, osparams)
3007
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3008
                        cwd=tbv.path, reset_env=True)
3009
  if result.failed:
3010
    logging.error("os validate command '%s' returned error: %s output: %s",
3011
                  result.cmd, result.fail_reason, result.output)
3012
    _Fail("OS validation script failed (%s), output: %s",
3013
          result.fail_reason, result.output, log=False)
3014

    
3015
  return True
3016

    
3017

    
3018
def DemoteFromMC():
3019
  """Demotes the current node from master candidate role.
3020

3021
  """
3022
  # try to ensure we're not the master by mistake
3023
  master, myself = ssconf.GetMasterAndMyself()
3024
  if master == myself:
3025
    _Fail("ssconf status shows I'm the master node, will not demote")
3026

    
3027
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3028
  if not result.failed:
3029
    _Fail("The master daemon is running, will not demote")
3030

    
3031
  try:
3032
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3033
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3034
  except EnvironmentError, err:
3035
    if err.errno != errno.ENOENT:
3036
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3037

    
3038
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3039

    
3040

    
3041
def _GetX509Filenames(cryptodir, name):
3042
  """Returns the full paths for the private key and certificate.
3043

3044
  """
3045
  return (utils.PathJoin(cryptodir, name),
3046
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3047
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3048

    
3049

    
3050
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3051
  """Creates a new X509 certificate for SSL/TLS.
3052

3053
  @type validity: int
3054
  @param validity: Validity in seconds
3055
  @rtype: tuple; (string, string)
3056
  @return: Certificate name and public part
3057

3058
  """
3059
  (key_pem, cert_pem) = \
3060
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3061
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3062

    
3063
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3064
                              prefix="x509-%s-" % utils.TimestampForFilename())
3065
  try:
3066
    name = os.path.basename(cert_dir)
3067
    assert len(name) > 5
3068

    
3069
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3070

    
3071
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3072
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3073

    
3074
    # Never return private key as it shouldn't leave the node
3075
    return (name, cert_pem)
3076
  except Exception:
3077
    shutil.rmtree(cert_dir, ignore_errors=True)
3078
    raise
3079

    
3080

    
3081
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3082
  """Removes a X509 certificate.
3083

3084
  @type name: string
3085
  @param name: Certificate name
3086

3087
  """
3088
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3089

    
3090
  utils.RemoveFile(key_file)
3091
  utils.RemoveFile(cert_file)
3092

    
3093
  try:
3094
    os.rmdir(cert_dir)
3095
  except EnvironmentError, err:
3096
    _Fail("Cannot remove certificate directory '%s': %s",
3097
          cert_dir, err)
3098

    
3099

    
3100
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3101
  """Returns the command for the requested input/output.
3102

3103
  @type instance: L{objects.Instance}
3104
  @param instance: The instance object
3105
  @param mode: Import/export mode
3106
  @param ieio: Input/output type
3107
  @param ieargs: Input/output arguments
3108

3109
  """
3110
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3111

    
3112
  env = None
3113
  prefix = None
3114
  suffix = None
3115
  exp_size = None
3116

    
3117
  if ieio == constants.IEIO_FILE:
3118
    (filename, ) = ieargs
3119

    
3120
    if not utils.IsNormAbsPath(filename):
3121
      _Fail("Path '%s' is not normalized or absolute", filename)
3122

    
3123
    real_filename = os.path.realpath(filename)
3124
    directory = os.path.dirname(real_filename)
3125

    
3126
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3127
      _Fail("File '%s' is not under exports directory '%s': %s",
3128
            filename, pathutils.EXPORT_DIR, real_filename)
3129

    
3130
    # Create directory
3131
    utils.Makedirs(directory, mode=0750)
3132

    
3133
    quoted_filename = utils.ShellQuote(filename)
3134

    
3135
    if mode == constants.IEM_IMPORT:
3136
      suffix = "> %s" % quoted_filename
3137
    elif mode == constants.IEM_EXPORT:
3138
      suffix = "< %s" % quoted_filename
3139

    
3140
      # Retrieve file size
3141
      try:
3142
        st = os.stat(filename)
3143
      except EnvironmentError, err:
3144
        logging.error("Can't stat(2) %s: %s", filename, err)
3145
      else:
3146
        exp_size = utils.BytesToMebibyte(st.st_size)
3147

    
3148
  elif ieio == constants.IEIO_RAW_DISK:
3149
    (disk, ) = ieargs
3150

    
3151
    real_disk = _OpenRealBD(disk)
3152

    
3153
    if mode == constants.IEM_IMPORT:
3154
      # we set here a smaller block size as, due to transport buffering, more
3155
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3156
      # is not already there or we pass a wrong path; we use notrunc to no
3157
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3158
      # much memory; this means that at best, we flush every 64k, which will
3159
      # not be very fast
3160
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3161
                                    " bs=%s oflag=dsync"),
3162
                                    real_disk.dev_path,
3163
                                    str(64 * 1024))
3164

    
3165
    elif mode == constants.IEM_EXPORT:
3166
      # the block size on the read dd is 1MiB to match our units
3167
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3168
                                   real_disk.dev_path,
3169
                                   str(1024 * 1024), # 1 MB
3170
                                   str(disk.size))
3171
      exp_size = disk.size
3172

    
3173
  elif ieio == constants.IEIO_SCRIPT:
3174
    (disk, disk_index, ) = ieargs
3175

    
3176
    assert isinstance(disk_index, (int, long))
3177

    
3178
    real_disk = _OpenRealBD(disk)
3179

    
3180
    inst_os = OSFromDisk(instance.os)
3181
    env = OSEnvironment(instance, inst_os)
3182

    
3183
    if mode == constants.IEM_IMPORT:
3184
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3185
      env["IMPORT_INDEX"] = str(disk_index)
3186
      script = inst_os.import_script
3187

    
3188
    elif mode == constants.IEM_EXPORT:
3189
      env["EXPORT_DEVICE"] = real_disk.dev_path
3190
      env["EXPORT_INDEX"] = str(disk_index)
3191
      script = inst_os.export_script
3192

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

    
3196
    if mode == constants.IEM_IMPORT:
3197
      suffix = "| %s" % script_cmd
3198

    
3199
    elif mode == constants.IEM_EXPORT:
3200
      prefix = "%s |" % script_cmd
3201

    
3202
    # Let script predict size
3203
    exp_size = constants.IE_CUSTOM_SIZE
3204

    
3205
  else:
3206
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3207

    
3208
  return (env, prefix, suffix, exp_size)
3209

    
3210

    
3211
def _CreateImportExportStatusDir(prefix):
3212
  """Creates status directory for import/export.
3213

3214
  """
3215
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3216
                          prefix=("%s-%s-" %
3217
                                  (prefix, utils.TimestampForFilename())))
3218

    
3219

    
3220
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3221
                            ieio, ieioargs):
3222
  """Starts an import or export daemon.
3223

3224
  @param mode: Import/output mode
3225
  @type opts: L{objects.ImportExportOptions}
3226
  @param opts: Daemon options
3227
  @type host: string
3228
  @param host: Remote host for export (None for import)
3229
  @type port: int
3230
  @param port: Remote port for export (None for import)
3231
  @type instance: L{objects.Instance}
3232
  @param instance: Instance object
3233
  @type component: string
3234
  @param component: which part of the instance is transferred now,
3235
      e.g. 'disk/0'
3236
  @param ieio: Input/output type
3237
  @param ieioargs: Input/output arguments
3238

3239
  """
3240
  if mode == constants.IEM_IMPORT:
3241
    prefix = "import"
3242

    
3243
    if not (host is None and port is None):
3244
      _Fail("Can not specify host or port on import")
3245

    
3246
  elif mode == constants.IEM_EXPORT:
3247
    prefix = "export"
3248

    
3249
    if host is None or port is None:
3250
      _Fail("Host and port must be specified for an export")
3251

    
3252
  else:
3253
    _Fail("Invalid mode %r", mode)
3254

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

    
3258
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3259
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3260

    
3261
  if opts.key_name is None:
3262
    # Use server.pem
3263
    key_path = pathutils.NODED_CERT_FILE
3264
    cert_path = pathutils.NODED_CERT_FILE
3265
    assert opts.ca_pem is None
3266
  else:
3267
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3268
                                                 opts.key_name)
3269
    assert opts.ca_pem is not None
3270

    
3271
  for i in [key_path, cert_path]:
3272
    if not os.path.exists(i):
3273
      _Fail("File '%s' does not exist" % i)
3274

    
3275
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3276
  try:
3277
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3278
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3279
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3280

    
3281
    if opts.ca_pem is None:
3282
      # Use server.pem
3283
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3284
    else:
3285
      ca = opts.ca_pem
3286

    
3287
    # Write CA file
3288
    utils.WriteFile(ca_file, data=ca, mode=0400)
3289

    
3290
    cmd = [
3291
      pathutils.IMPORT_EXPORT_DAEMON,
3292
      status_file, mode,
3293
      "--key=%s" % key_path,
3294
      "--cert=%s" % cert_path,
3295
      "--ca=%s" % ca_file,
3296
      ]
3297

    
3298
    if host:
3299
      cmd.append("--host=%s" % host)
3300

    
3301
    if port:
3302
      cmd.append("--port=%s" % port)
3303

    
3304
    if opts.ipv6:
3305
      cmd.append("--ipv6")
3306
    else:
3307
      cmd.append("--ipv4")
3308

    
3309
    if opts.compress:
3310
      cmd.append("--compress=%s" % opts.compress)
3311

    
3312
    if opts.magic:
3313
      cmd.append("--magic=%s" % opts.magic)
3314

    
3315
    if exp_size is not None:
3316
      cmd.append("--expected-size=%s" % exp_size)
3317

    
3318
    if cmd_prefix:
3319
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3320

    
3321
    if cmd_suffix:
3322
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3323

    
3324
    if mode == constants.IEM_EXPORT:
3325
      # Retry connection a few times when connecting to remote peer
3326
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3327
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3328
    elif opts.connect_timeout is not None:
3329
      assert mode == constants.IEM_IMPORT
3330
      # Overall timeout for establishing connection while listening
3331
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3332

    
3333
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3334

    
3335
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3336
    # support for receiving a file descriptor for output
3337
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3338
                      output=logfile)
3339

    
3340
    # The import/export name is simply the status directory name
3341
    return os.path.basename(status_dir)
3342

    
3343
  except Exception:
3344
    shutil.rmtree(status_dir, ignore_errors=True)
3345
    raise
3346

    
3347

    
3348
def GetImportExportStatus(names):
3349
  """Returns import/export daemon status.
3350

3351
  @type names: sequence
3352
  @param names: List of names
3353
  @rtype: List of dicts
3354
  @return: Returns a list of the state of each named import/export or None if a
3355
           status couldn't be read
3356

3357
  """
3358
  result = []
3359

    
3360
  for name in names:
3361
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3362
                                 _IES_STATUS_FILE)
3363

    
3364
    try:
3365
      data = utils.ReadFile(status_file)
3366
    except EnvironmentError, err:
3367
      if err.errno != errno.ENOENT:
3368
        raise
3369
      data = None
3370

    
3371
    if not data:
3372
      result.append(None)
3373
      continue
3374

    
3375
    result.append(serializer.LoadJson(data))
3376

    
3377
  return result
3378

    
3379

    
3380
def AbortImportExport(name):
3381
  """Sends SIGTERM to a running import/export daemon.
3382

3383
  """
3384
  logging.info("Abort import/export %s", name)
3385

    
3386
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3387
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3388

    
3389
  if pid:
3390
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3391
                 name, pid)
3392
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3393

    
3394

    
3395
def CleanupImportExport(name):
3396
  """Cleanup after an import or export.
3397

3398
  If the import/export daemon is still running it's killed. Afterwards the
3399
  whole status directory is removed.
3400

3401
  """
3402
  logging.info("Finalizing import/export %s", name)
3403

    
3404
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3405

    
3406
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3407

    
3408
  if pid:
3409
    logging.info("Import/export %s is still running with PID %s",
3410
                 name, pid)
3411
    utils.KillProcess(pid, waitpid=False)
3412

    
3413
  shutil.rmtree(status_dir, ignore_errors=True)
3414

    
3415

    
3416
def _FindDisks(nodes_ip, disks):
3417
  """Sets the physical ID on disks and returns the block devices.
3418

3419
  """
3420
  # set the correct physical ID
3421
  my_name = netutils.Hostname.GetSysName()
3422
  for cf in disks:
3423
    cf.SetPhysicalID(my_name, nodes_ip)
3424

    
3425
  bdevs = []
3426

    
3427
  for cf in disks:
3428
    rd = _RecursiveFindBD(cf)
3429
    if rd is None:
3430
      _Fail("Can't find device %s", cf)
3431
    bdevs.append(rd)
3432
  return bdevs
3433

    
3434

    
3435
def DrbdDisconnectNet(nodes_ip, disks):
3436
  """Disconnects the network on a list of drbd devices.
3437

3438
  """
3439
  bdevs = _FindDisks(nodes_ip, disks)
3440

    
3441
  # disconnect disks
3442
  for rd in bdevs:
3443
    try:
3444
      rd.DisconnectNet()
3445
    except errors.BlockDeviceError, err:
3446
      _Fail("Can't change network configuration to standalone mode: %s",
3447
            err, exc=True)
3448

    
3449

    
3450
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3451
  """Attaches the network on a list of drbd devices.
3452

3453
  """
3454
  bdevs = _FindDisks(nodes_ip, disks)
3455

    
3456
  if multimaster:
3457
    for idx, rd in enumerate(bdevs):
3458
      try:
3459
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3460
      except EnvironmentError, err:
3461
        _Fail("Can't create symlink: %s", err)
3462
  # reconnect disks, switch to new master configuration and if
3463
  # needed primary mode
3464
  for rd in bdevs:
3465
    try:
3466
      rd.AttachNet(multimaster)
3467
    except errors.BlockDeviceError, err:
3468
      _Fail("Can't change network configuration: %s", err)
3469

    
3470
  # wait until the disks are connected; we need to retry the re-attach
3471
  # if the device becomes standalone, as this might happen if the one
3472
  # node disconnects and reconnects in a different mode before the
3473
  # other node reconnects; in this case, one or both of the nodes will
3474
  # decide it has wrong configuration and switch to standalone
3475

    
3476
  def _Attach():
3477
    all_connected = True
3478

    
3479
    for rd in bdevs:
3480
      stats = rd.GetProcStatus()
3481

    
3482
      all_connected = (all_connected and
3483
                       (stats.is_connected or stats.is_in_resync))
3484

    
3485
      if stats.is_standalone:
3486
        # peer had different config info and this node became
3487
        # standalone, even though this should not happen with the
3488
        # new staged way of changing disk configs
3489
        try:
3490
          rd.AttachNet(multimaster)
3491
        except errors.BlockDeviceError, err:
3492
          _Fail("Can't change network configuration: %s", err)
3493

    
3494
    if not all_connected:
3495
      raise utils.RetryAgain()
3496

    
3497
  try:
3498
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3499
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3500
  except utils.RetryTimeout:
3501
    _Fail("Timeout in disk reconnecting")
3502

    
3503
  if multimaster:
3504
    # change to primary mode
3505
    for rd in bdevs:
3506
      try:
3507
        rd.Open()
3508
      except errors.BlockDeviceError, err:
3509
        _Fail("Can't change to primary mode: %s", err)
3510

    
3511

    
3512
def DrbdWaitSync(nodes_ip, disks):
3513
  """Wait until DRBDs have synchronized.
3514

3515
  """
3516
  def _helper(rd):
3517
    stats = rd.GetProcStatus()
3518
    if not (stats.is_connected or stats.is_in_resync):
3519
      raise utils.RetryAgain()
3520
    return stats
3521

    
3522
  bdevs = _FindDisks(nodes_ip, disks)
3523

    
3524
  min_resync = 100
3525
  alldone = True
3526
  for rd in bdevs:
3527
    try:
3528
      # poll each second for 15 seconds
3529
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3530
    except utils.RetryTimeout:
3531
      stats = rd.GetProcStatus()
3532
      # last check
3533
      if not (stats.is_connected or stats.is_in_resync):
3534
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3535
    alldone = alldone and (not stats.is_in_resync)
3536
    if stats.sync_percent is not None:
3537
      min_resync = min(min_resync, stats.sync_percent)
3538

    
3539
  return (alldone, min_resync)
3540

    
3541

    
3542
def GetDrbdUsermodeHelper():
3543
  """Returns DRBD usermode helper currently configured.
3544

3545
  """
3546
  try:
3547
    return bdev.BaseDRBD.GetUsermodeHelper()
3548
  except errors.BlockDeviceError, err:
3549
    _Fail(str(err))
3550

    
3551

    
3552
def PowercycleNode(hypervisor_type):
3553
  """Hard-powercycle the node.
3554

3555
  Because we need to return first, and schedule the powercycle in the
3556
  background, we won't be able to report failures nicely.
3557

3558
  """
3559
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3560
  try:
3561
    pid = os.fork()
3562
  except OSError:
3563
    # if we can't fork, we'll pretend that we're in the child process
3564
    pid = 0
3565
  if pid > 0:
3566
    return "Reboot scheduled in 5 seconds"
3567
  # ensure the child is running on ram
3568
  try:
3569
    utils.Mlockall()
3570
  except Exception: # pylint: disable=W0703
3571
    pass
3572
  time.sleep(5)
3573
  hyper.PowercycleNode()
3574

    
3575

    
3576
class HooksRunner(object):
3577
  """Hook runner.
3578

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

3582
  """
3583
  def __init__(self, hooks_base_dir=None):
3584
    """Constructor for hooks runner.
3585

3586
    @type hooks_base_dir: str or None
3587
    @param hooks_base_dir: if not None, this overrides the
3588
        L{pathutils.HOOKS_BASE_DIR} (useful for unittests)
3589

3590
    """
3591
    if hooks_base_dir is None:
3592
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
3593
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3594
    # constant
3595
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
3596

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

3600
    """
3601
    assert len(node_list) == 1
3602
    node = node_list[0]
3603
    _, myself = ssconf.GetMasterAndMyself()
3604
    assert node == myself
3605

    
3606
    results = self.RunHooks(hpath, phase, env)
3607

    
3608
    # Return values in the form expected by HooksMaster
3609
    return {node: (None, False, results)}
3610

    
3611
  def RunHooks(self, hpath, phase, env):
3612
    """Run the scripts in the hooks directory.
3613

3614
    @type hpath: str
3615
    @param hpath: the path to the hooks directory which
3616
        holds the scripts
3617
    @type phase: str
3618
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
3619
        L{constants.HOOKS_PHASE_POST}
3620
    @type env: dict
3621
    @param env: dictionary with the environment for the hook
3622
    @rtype: list
3623
    @return: list of 3-element tuples:
3624
      - script path
3625
      - script result, either L{constants.HKR_SUCCESS} or
3626
        L{constants.HKR_FAIL}
3627
      - output of the script
3628

3629
    @raise errors.ProgrammerError: for invalid input
3630
        parameters
3631

3632
    """
3633
    if phase == constants.HOOKS_PHASE_PRE:
3634
      suffix = "pre"
3635
    elif phase == constants.HOOKS_PHASE_POST:
3636
      suffix = "post"
3637
    else:
3638
      _Fail("Unknown hooks phase '%s'", phase)
3639

    
3640
    subdir = "%s-%s.d" % (hpath, suffix)
3641
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3642

    
3643
    results = []
3644

    
3645
    if not os.path.isdir(dir_name):
3646
      # for non-existing/non-dirs, we simply exit instead of logging a
3647
      # warning at every operation
3648
      return results
3649

    
3650
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3651

    
3652
    for (relname, relstatus, runresult) in runparts_results:
3653
      if relstatus == constants.RUNPARTS_SKIP:
3654
        rrval = constants.HKR_SKIP
3655
        output = ""
3656
      elif relstatus == constants.RUNPARTS_ERR:
3657
        rrval = constants.HKR_FAIL
3658
        output = "Hook script execution error: %s" % runresult
3659
      elif relstatus == constants.RUNPARTS_RUN:
3660
        if runresult.failed:
3661
          rrval = constants.HKR_FAIL
3662
        else:
3663
          rrval = constants.HKR_SUCCESS
3664
        output = utils.SafeEncode(runresult.output.strip())
3665
      results.append(("%s/%s" % (subdir, relname), rrval, output))
3666

    
3667
    return results
3668

    
3669

    
3670
class IAllocatorRunner(object):
3671
  """IAllocator runner.
3672

3673
  This class is instantiated on the node side (ganeti-noded) and not on
3674
  the master side.
3675

3676
  """
3677
  @staticmethod
3678
  def Run(name, idata):
3679
    """Run an iallocator script.
3680

3681
    @type name: str
3682
    @param name: the iallocator script name
3683
    @type idata: str
3684
    @param idata: the allocator input data
3685

3686
    @rtype: tuple
3687
    @return: two element tuple of:
3688
       - status
3689
       - either error message or stdout of allocator (for success)
3690

3691
    """
3692
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
3693
                                  os.path.isfile)
3694
    if alloc_script is None:
3695
      _Fail("iallocator module '%s' not found in the search path", name)
3696

    
3697
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
3698
    try:
3699
      os.write(fd, idata)
3700
      os.close(fd)
3701
      result = utils.RunCmd([alloc_script, fin_name])
3702
      if result.failed:
3703
        _Fail("iallocator module '%s' failed: %s, output '%s'",
3704
              name, result.fail_reason, result.output)
3705
    finally:
3706
      os.unlink(fin_name)
3707

    
3708
    return result.stdout
3709

    
3710

    
3711
class DevCacheManager(object):
3712
  """Simple class for managing a cache of block device information.
3713

3714
  """
3715
  _DEV_PREFIX = "/dev/"
3716
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
3717

    
3718
  @classmethod
3719
  def _ConvertPath(cls, dev_path):
3720
    """Converts a /dev/name path to the cache file name.
3721

3722
    This replaces slashes with underscores and strips the /dev
3723
    prefix. It then returns the full path to the cache file.
3724

3725
    @type dev_path: str
3726
    @param dev_path: the C{/dev/} path name
3727
    @rtype: str
3728
    @return: the converted path name
3729

3730
    """
3731
    if dev_path.startswith(cls._DEV_PREFIX):
3732
      dev_path = dev_path[len(cls._DEV_PREFIX):]
3733
    dev_path = dev_path.replace("/", "_")
3734
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
3735
    return fpath
3736

    
3737
  @classmethod
3738
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
3739
    """Updates the cache information for a given device.
3740

3741
    @type dev_path: str
3742
    @param dev_path: the pathname of the device
3743
    @type owner: str
3744
    @param owner: the owner (instance name) of the device
3745
    @type on_primary: bool
3746
    @param on_primary: whether this is the primary
3747
        node nor not
3748
    @type iv_name: str
3749
    @param iv_name: the instance-visible name of the
3750
        device, as in objects.Disk.iv_name
3751

3752
    @rtype: None
3753

3754
    """
3755
    if dev_path is None:
3756
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
3757
      return
3758
    fpath = cls._ConvertPath(dev_path)
3759
    if on_primary:
3760
      state = "primary"
3761
    else:
3762
      state = "secondary"
3763
    if iv_name is None:
3764
      iv_name = "not_visible"
3765
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
3766
    try:
3767
      utils.WriteFile(fpath, data=fdata)
3768
    except EnvironmentError, err:
3769
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
3770

    
3771
  @classmethod
3772
  def RemoveCache(cls, dev_path):
3773
    """Remove data for a dev_path.
3774

3775
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
3776
    path name and logging.
3777

3778
    @type dev_path: str
3779
    @param dev_path: the pathname of the device
3780

3781
    @rtype: None
3782

3783
    """
3784
    if dev_path is None:
3785
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
3786
      return
3787
    fpath = cls._ConvertPath(dev_path)
3788
    try:
3789
      utils.RemoveFile(fpath)
3790
    except EnvironmentError, err:
3791
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)