Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ bbc4783a

History | View | Annotate | Download (123.5 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
from ganeti import ht
68

    
69

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

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

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

    
91
#: Maximum file permissions for remote command directory and executables
92
_RCMD_MAX_MODE = (stat.S_IRWXU |
93
                  stat.S_IRGRP | stat.S_IXGRP |
94
                  stat.S_IROTH | stat.S_IXOTH)
95

    
96
#: Delay before returning an error for remote commands
97
_RCMD_INVALID_DELAY = 10
98

    
99
#: How long to wait to acquire lock for remote commands (shorter than
100
#: L{_RCMD_INVALID_DELAY}) to reduce blockage of noded forks when many
101
#: command requests arrive
102
_RCMD_LOCK_TIMEOUT = _RCMD_INVALID_DELAY * 0.8
103

    
104

    
105
class RPCFail(Exception):
106
  """Class denoting RPC failure.
107

108
  Its argument is the error message.
109

110
  """
111

    
112

    
113
def _Fail(msg, *args, **kwargs):
114
  """Log an error and the raise an RPCFail exception.
115

116
  This exception is then handled specially in the ganeti daemon and
117
  turned into a 'failed' return type. As such, this function is a
118
  useful shortcut for logging the error and returning it to the master
119
  daemon.
120

121
  @type msg: string
122
  @param msg: the text of the exception
123
  @raise RPCFail
124

125
  """
126
  if args:
127
    msg = msg % args
128
  if "log" not in kwargs or kwargs["log"]: # if we should log this error
129
    if "exc" in kwargs and kwargs["exc"]:
130
      logging.exception(msg)
131
    else:
132
      logging.error(msg)
133
  raise RPCFail(msg)
134

    
135

    
136
def _GetConfig():
137
  """Simple wrapper to return a SimpleStore.
138

139
  @rtype: L{ssconf.SimpleStore}
140
  @return: a SimpleStore instance
141

142
  """
143
  return ssconf.SimpleStore()
144

    
145

    
146
def _GetSshRunner(cluster_name):
147
  """Simple wrapper to return an SshRunner.
148

149
  @type cluster_name: str
150
  @param cluster_name: the cluster name, which is needed
151
      by the SshRunner constructor
152
  @rtype: L{ssh.SshRunner}
153
  @return: an SshRunner instance
154

155
  """
156
  return ssh.SshRunner(cluster_name)
157

    
158

    
159
def _Decompress(data):
160
  """Unpacks data compressed by the RPC client.
161

162
  @type data: list or tuple
163
  @param data: Data sent by RPC client
164
  @rtype: str
165
  @return: Decompressed data
166

167
  """
168
  assert isinstance(data, (list, tuple))
169
  assert len(data) == 2
170
  (encoding, content) = data
171
  if encoding == constants.RPC_ENCODING_NONE:
172
    return content
173
  elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
174
    return zlib.decompress(base64.b64decode(content))
175
  else:
176
    raise AssertionError("Unknown data encoding")
177

    
178

    
179
def _CleanDirectory(path, exclude=None):
180
  """Removes all regular files in a directory.
181

182
  @type path: str
183
  @param path: the directory to clean
184
  @type exclude: list
185
  @param exclude: list of files to be excluded, defaults
186
      to the empty list
187

188
  """
189
  if path not in _ALLOWED_CLEAN_DIRS:
190
    _Fail("Path passed to _CleanDirectory not in allowed clean targets: '%s'",
191
          path)
192

    
193
  if not os.path.isdir(path):
194
    return
195
  if exclude is None:
196
    exclude = []
197
  else:
198
    # Normalize excluded paths
199
    exclude = [os.path.normpath(i) for i in exclude]
200

    
201
  for rel_name in utils.ListVisibleFiles(path):
202
    full_name = utils.PathJoin(path, rel_name)
203
    if full_name in exclude:
204
      continue
205
    if os.path.isfile(full_name) and not os.path.islink(full_name):
206
      utils.RemoveFile(full_name)
207

    
208

    
209
def _BuildUploadFileList():
210
  """Build the list of allowed upload files.
211

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

214
  """
215
  allowed_files = set([
216
    pathutils.CLUSTER_CONF_FILE,
217
    pathutils.ETC_HOSTS,
218
    pathutils.SSH_KNOWN_HOSTS_FILE,
219
    pathutils.VNC_PASSWORD_FILE,
220
    pathutils.RAPI_CERT_FILE,
221
    pathutils.SPICE_CERT_FILE,
222
    pathutils.SPICE_CACERT_FILE,
223
    pathutils.RAPI_USERS_FILE,
224
    pathutils.CONFD_HMAC_KEY,
225
    pathutils.CLUSTER_DOMAIN_SECRET_FILE,
226
    ])
227

    
228
  for hv_name in constants.HYPER_TYPES:
229
    hv_class = hypervisor.GetHypervisorClass(hv_name)
230
    allowed_files.update(hv_class.GetAncillaryFiles()[0])
231

    
232
  assert pathutils.FILE_STORAGE_PATHS_FILE not in allowed_files, \
233
    "Allowed file storage paths should never be uploaded via RPC"
234

    
235
  return frozenset(allowed_files)
236

    
237

    
238
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
239

    
240

    
241
def JobQueuePurge():
242
  """Removes job queue files and archived jobs.
243

244
  @rtype: tuple
245
  @return: True, None
246

247
  """
248
  _CleanDirectory(pathutils.QUEUE_DIR, exclude=[pathutils.JOB_QUEUE_LOCK_FILE])
249
  _CleanDirectory(pathutils.JOB_QUEUE_ARCHIVE_DIR)
250

    
251

    
252
def GetMasterInfo():
253
  """Returns master information.
254

255
  This is an utility function to compute master information, either
256
  for consumption here or from the node daemon.
257

258
  @rtype: tuple
259
  @return: master_netdev, master_ip, master_name, primary_ip_family,
260
    master_netmask
261
  @raise RPCFail: in case of errors
262

263
  """
264
  try:
265
    cfg = _GetConfig()
266
    master_netdev = cfg.GetMasterNetdev()
267
    master_ip = cfg.GetMasterIP()
268
    master_netmask = cfg.GetMasterNetmask()
269
    master_node = cfg.GetMasterNode()
270
    primary_ip_family = cfg.GetPrimaryIPFamily()
271
  except errors.ConfigurationError, err:
272
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
273
  return (master_netdev, master_ip, master_node, primary_ip_family,
274
          master_netmask)
275

    
276

    
277
def RunLocalHooks(hook_opcode, hooks_path, env_builder_fn):
278
  """Decorator that runs hooks before and after the decorated function.
279

280
  @type hook_opcode: string
281
  @param hook_opcode: opcode of the hook
282
  @type hooks_path: string
283
  @param hooks_path: path of the hooks
284
  @type env_builder_fn: function
285
  @param env_builder_fn: function that returns a dictionary containing the
286
    environment variables for the hooks. Will get all the parameters of the
287
    decorated function.
288
  @raise RPCFail: in case of pre-hook failure
289

290
  """
291
  def decorator(fn):
292
    def wrapper(*args, **kwargs):
293
      _, myself = ssconf.GetMasterAndMyself()
294
      nodes = ([myself], [myself])  # these hooks run locally
295

    
296
      env_fn = compat.partial(env_builder_fn, *args, **kwargs)
297

    
298
      cfg = _GetConfig()
299
      hr = HooksRunner()
300
      hm = mcpu.HooksMaster(hook_opcode, hooks_path, nodes, hr.RunLocalHooks,
301
                            None, env_fn, logging.warning, cfg.GetClusterName(),
302
                            cfg.GetMasterNode())
303

    
304
      hm.RunPhase(constants.HOOKS_PHASE_PRE)
305
      result = fn(*args, **kwargs)
306
      hm.RunPhase(constants.HOOKS_PHASE_POST)
307

    
308
      return result
309
    return wrapper
310
  return decorator
311

    
312

    
313
def _BuildMasterIpEnv(master_params, use_external_mip_script=None):
314
  """Builds environment variables for master IP hooks.
315

316
  @type master_params: L{objects.MasterNetworkParameters}
317
  @param master_params: network parameters of the master
318
  @type use_external_mip_script: boolean
319
  @param use_external_mip_script: whether to use an external master IP
320
    address setup script (unused, but necessary per the implementation of the
321
    _RunLocalHooks decorator)
322

323
  """
324
  # pylint: disable=W0613
325
  ver = netutils.IPAddress.GetVersionFromAddressFamily(master_params.ip_family)
326
  env = {
327
    "MASTER_NETDEV": master_params.netdev,
328
    "MASTER_IP": master_params.ip,
329
    "MASTER_NETMASK": str(master_params.netmask),
330
    "CLUSTER_IP_VERSION": str(ver),
331
  }
332

    
333
  return env
334

    
335

    
336
def _RunMasterSetupScript(master_params, action, use_external_mip_script):
337
  """Execute the master IP address setup script.
338

339
  @type master_params: L{objects.MasterNetworkParameters}
340
  @param master_params: network parameters of the master
341
  @type action: string
342
  @param action: action to pass to the script. Must be one of
343
    L{backend._MASTER_START} or L{backend._MASTER_STOP}
344
  @type use_external_mip_script: boolean
345
  @param use_external_mip_script: whether to use an external master IP
346
    address setup script
347
  @raise backend.RPCFail: if there are errors during the execution of the
348
    script
349

350
  """
351
  env = _BuildMasterIpEnv(master_params)
352

    
353
  if use_external_mip_script:
354
    setup_script = pathutils.EXTERNAL_MASTER_SETUP_SCRIPT
355
  else:
356
    setup_script = pathutils.DEFAULT_MASTER_SETUP_SCRIPT
357

    
358
  result = utils.RunCmd([setup_script, action], env=env, reset_env=True)
359

    
360
  if result.failed:
361
    _Fail("Failed to %s the master IP. Script return value: %s, output: '%s'" %
362
          (action, result.exit_code, result.output), log=True)
363

    
364

    
365
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNUP, "master-ip-turnup",
366
               _BuildMasterIpEnv)
367
def ActivateMasterIp(master_params, use_external_mip_script):
368
  """Activate the IP address of the master daemon.
369

370
  @type master_params: L{objects.MasterNetworkParameters}
371
  @param master_params: network parameters of the master
372
  @type use_external_mip_script: boolean
373
  @param use_external_mip_script: whether to use an external master IP
374
    address setup script
375
  @raise RPCFail: in case of errors during the IP startup
376

377
  """
378
  _RunMasterSetupScript(master_params, _MASTER_START,
379
                        use_external_mip_script)
380

    
381

    
382
def StartMasterDaemons(no_voting):
383
  """Activate local node as master node.
384

385
  The function will start the master daemons (ganeti-masterd and ganeti-rapi).
386

387
  @type no_voting: boolean
388
  @param no_voting: whether to start ganeti-masterd without a node vote
389
      but still non-interactively
390
  @rtype: None
391

392
  """
393

    
394
  if no_voting:
395
    masterd_args = "--no-voting --yes-do-it"
396
  else:
397
    masterd_args = ""
398

    
399
  env = {
400
    "EXTRA_MASTERD_ARGS": masterd_args,
401
    }
402

    
403
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "start-master"], env=env)
404
  if result.failed:
405
    msg = "Can't start Ganeti master: %s" % result.output
406
    logging.error(msg)
407
    _Fail(msg)
408

    
409

    
410
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNDOWN, "master-ip-turndown",
411
               _BuildMasterIpEnv)
412
def DeactivateMasterIp(master_params, use_external_mip_script):
413
  """Deactivate the master IP on this node.
414

415
  @type master_params: L{objects.MasterNetworkParameters}
416
  @param master_params: network parameters of the master
417
  @type use_external_mip_script: boolean
418
  @param use_external_mip_script: whether to use an external master IP
419
    address setup script
420
  @raise RPCFail: in case of errors during the IP turndown
421

422
  """
423
  _RunMasterSetupScript(master_params, _MASTER_STOP,
424
                        use_external_mip_script)
425

    
426

    
427
def StopMasterDaemons():
428
  """Stop the master daemons on this node.
429

430
  Stop the master daemons (ganeti-masterd and ganeti-rapi) on this node.
431

432
  @rtype: None
433

434
  """
435
  # TODO: log and report back to the caller the error failures; we
436
  # need to decide in which case we fail the RPC for this
437

    
438
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop-master"])
439
  if result.failed:
440
    logging.error("Could not stop Ganeti master, command %s had exitcode %s"
441
                  " and error %s",
442
                  result.cmd, result.exit_code, result.output)
443

    
444

    
445
def ChangeMasterNetmask(old_netmask, netmask, master_ip, master_netdev):
446
  """Change the netmask of the master IP.
447

448
  @param old_netmask: the old value of the netmask
449
  @param netmask: the new value of the netmask
450
  @param master_ip: the master IP
451
  @param master_netdev: the master network device
452

453
  """
454
  if old_netmask == netmask:
455
    return
456

    
457
  if not netutils.IPAddress.Own(master_ip):
458
    _Fail("The master IP address is not up, not attempting to change its"
459
          " netmask")
460

    
461
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
462
                         "%s/%s" % (master_ip, netmask),
463
                         "dev", master_netdev, "label",
464
                         "%s:0" % master_netdev])
465
  if result.failed:
466
    _Fail("Could not set the new netmask on the master IP address")
467

    
468
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
469
                         "%s/%s" % (master_ip, old_netmask),
470
                         "dev", master_netdev, "label",
471
                         "%s:0" % master_netdev])
472
  if result.failed:
473
    _Fail("Could not bring down the master IP address with the old netmask")
474

    
475

    
476
def EtcHostsModify(mode, host, ip):
477
  """Modify a host entry in /etc/hosts.
478

479
  @param mode: The mode to operate. Either add or remove entry
480
  @param host: The host to operate on
481
  @param ip: The ip associated with the entry
482

483
  """
484
  if mode == constants.ETC_HOSTS_ADD:
485
    if not ip:
486
      RPCFail("Mode 'add' needs 'ip' parameter, but parameter not"
487
              " present")
488
    utils.AddHostToEtcHosts(host, ip)
489
  elif mode == constants.ETC_HOSTS_REMOVE:
490
    if ip:
491
      RPCFail("Mode 'remove' does not allow 'ip' parameter, but"
492
              " parameter is present")
493
    utils.RemoveHostFromEtcHosts(host)
494
  else:
495
    RPCFail("Mode not supported")
496

    
497

    
498
def LeaveCluster(modify_ssh_setup):
499
  """Cleans up and remove the current node.
500

501
  This function cleans up and prepares the current node to be removed
502
  from the cluster.
503

504
  If processing is successful, then it raises an
505
  L{errors.QuitGanetiException} which is used as a special case to
506
  shutdown the node daemon.
507

508
  @param modify_ssh_setup: boolean
509

510
  """
511
  _CleanDirectory(pathutils.DATA_DIR)
512
  _CleanDirectory(pathutils.CRYPTO_KEYS_DIR)
513
  JobQueuePurge()
514

    
515
  if modify_ssh_setup:
516
    try:
517
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.SSH_LOGIN_USER)
518

    
519
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
520

    
521
      utils.RemoveFile(priv_key)
522
      utils.RemoveFile(pub_key)
523
    except errors.OpExecError:
524
      logging.exception("Error while processing ssh files")
525

    
526
  try:
527
    utils.RemoveFile(pathutils.CONFD_HMAC_KEY)
528
    utils.RemoveFile(pathutils.RAPI_CERT_FILE)
529
    utils.RemoveFile(pathutils.SPICE_CERT_FILE)
530
    utils.RemoveFile(pathutils.SPICE_CACERT_FILE)
531
    utils.RemoveFile(pathutils.NODED_CERT_FILE)
532
  except: # pylint: disable=W0702
533
    logging.exception("Error while removing cluster secrets")
534

    
535
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop", constants.CONFD])
536
  if result.failed:
537
    logging.error("Command %s failed with exitcode %s and error %s",
538
                  result.cmd, result.exit_code, result.output)
539

    
540
  # Raise a custom exception (handled in ganeti-noded)
541
  raise errors.QuitGanetiException(True, "Shutdown scheduled")
542

    
543

    
544
def _GetVgInfo(name, excl_stor):
545
  """Retrieves information about a LVM volume group.
546

547
  """
548
  # TODO: GetVGInfo supports returning information for multiple VGs at once
549
  vginfo = bdev.LogicalVolume.GetVGInfo([name], excl_stor)
550
  if vginfo:
551
    vg_free = int(round(vginfo[0][0], 0))
552
    vg_size = int(round(vginfo[0][1], 0))
553
  else:
554
    vg_free = None
555
    vg_size = None
556

    
557
  return {
558
    "name": name,
559
    "vg_free": vg_free,
560
    "vg_size": vg_size,
561
    }
562

    
563

    
564
def _GetHvInfo(name):
565
  """Retrieves node information from a hypervisor.
566

567
  The information returned depends on the hypervisor. Common items:
568

569
    - vg_size is the size of the configured volume group in MiB
570
    - vg_free is the free size of the volume group in MiB
571
    - memory_dom0 is the memory allocated for domain0 in MiB
572
    - memory_free is the currently available (free) ram in MiB
573
    - memory_total is the total number of ram in MiB
574
    - hv_version: the hypervisor version, if available
575

576
  """
577
  return hypervisor.GetHypervisor(name).GetNodeInfo()
578

    
579

    
580
def _GetNamedNodeInfo(names, fn):
581
  """Calls C{fn} for all names in C{names} and returns a dictionary.
582

583
  @rtype: None or dict
584

585
  """
586
  if names is None:
587
    return None
588
  else:
589
    return map(fn, names)
590

    
591

    
592
def GetNodeInfo(vg_names, hv_names, excl_stor):
593
  """Gives back a hash with different information about the node.
594

595
  @type vg_names: list of string
596
  @param vg_names: Names of the volume groups to ask for disk space information
597
  @type hv_names: list of string
598
  @param hv_names: Names of the hypervisors to ask for node information
599
  @type excl_stor: boolean
600
  @param excl_stor: Whether exclusive_storage is active
601
  @rtype: tuple; (string, None/dict, None/dict)
602
  @return: Tuple containing boot ID, volume group information and hypervisor
603
    information
604

605
  """
606
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
607
  vg_info = _GetNamedNodeInfo(vg_names, (lambda vg: _GetVgInfo(vg, excl_stor)))
608
  hv_info = _GetNamedNodeInfo(hv_names, _GetHvInfo)
609

    
610
  return (bootid, vg_info, hv_info)
611

    
612

    
613
def VerifyNode(what, cluster_name):
614
  """Verify the status of the local node.
615

616
  Based on the input L{what} parameter, various checks are done on the
617
  local node.
618

619
  If the I{filelist} key is present, this list of
620
  files is checksummed and the file/checksum pairs are returned.
621

622
  If the I{nodelist} key is present, we check that we have
623
  connectivity via ssh with the target nodes (and check the hostname
624
  report).
625

626
  If the I{node-net-test} key is present, we check that we have
627
  connectivity to the given nodes via both primary IP and, if
628
  applicable, secondary IPs.
629

630
  @type what: C{dict}
631
  @param what: a dictionary of things to check:
632
      - filelist: list of files for which to compute checksums
633
      - nodelist: list of nodes we should check ssh communication with
634
      - node-net-test: list of nodes we should check node daemon port
635
        connectivity with
636
      - hypervisor: list with hypervisors to run the verify for
637
  @rtype: dict
638
  @return: a dictionary with the same keys as the input dict, and
639
      values representing the result of the checks
640

641
  """
642
  result = {}
643
  my_name = netutils.Hostname.GetSysName()
644
  port = netutils.GetDaemonPort(constants.NODED)
645
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
646

    
647
  if constants.NV_HYPERVISOR in what and vm_capable:
648
    result[constants.NV_HYPERVISOR] = tmp = {}
649
    for hv_name in what[constants.NV_HYPERVISOR]:
650
      try:
651
        val = hypervisor.GetHypervisor(hv_name).Verify()
652
      except errors.HypervisorError, err:
653
        val = "Error while checking hypervisor: %s" % str(err)
654
      tmp[hv_name] = val
655

    
656
  if constants.NV_HVPARAMS in what and vm_capable:
657
    result[constants.NV_HVPARAMS] = tmp = []
658
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
659
      try:
660
        logging.info("Validating hv %s, %s", hv_name, hvparms)
661
        hypervisor.GetHypervisor(hv_name).ValidateParameters(hvparms)
662
      except errors.HypervisorError, err:
663
        tmp.append((source, hv_name, str(err)))
664

    
665
  if constants.NV_FILELIST in what:
666
    fingerprints = utils.FingerprintFiles(map(vcluster.LocalizeVirtualPath,
667
                                              what[constants.NV_FILELIST]))
668
    result[constants.NV_FILELIST] = \
669
      dict((vcluster.MakeVirtualPath(key), value)
670
           for (key, value) in fingerprints.items())
671

    
672
  if constants.NV_NODELIST in what:
673
    (nodes, bynode) = what[constants.NV_NODELIST]
674

    
675
    # Add nodes from other groups (different for each node)
676
    try:
677
      nodes.extend(bynode[my_name])
678
    except KeyError:
679
      pass
680

    
681
    # Use a random order
682
    random.shuffle(nodes)
683

    
684
    # Try to contact all nodes
685
    val = {}
686
    for node in nodes:
687
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
688
      if not success:
689
        val[node] = message
690

    
691
    result[constants.NV_NODELIST] = val
692

    
693
  if constants.NV_NODENETTEST in what:
694
    result[constants.NV_NODENETTEST] = tmp = {}
695
    my_pip = my_sip = None
696
    for name, pip, sip in what[constants.NV_NODENETTEST]:
697
      if name == my_name:
698
        my_pip = pip
699
        my_sip = sip
700
        break
701
    if not my_pip:
702
      tmp[my_name] = ("Can't find my own primary/secondary IP"
703
                      " in the node list")
704
    else:
705
      for name, pip, sip in what[constants.NV_NODENETTEST]:
706
        fail = []
707
        if not netutils.TcpPing(pip, port, source=my_pip):
708
          fail.append("primary")
709
        if sip != pip:
710
          if not netutils.TcpPing(sip, port, source=my_sip):
711
            fail.append("secondary")
712
        if fail:
713
          tmp[name] = ("failure using the %s interface(s)" %
714
                       " and ".join(fail))
715

    
716
  if constants.NV_MASTERIP in what:
717
    # FIXME: add checks on incoming data structures (here and in the
718
    # rest of the function)
719
    master_name, master_ip = what[constants.NV_MASTERIP]
720
    if master_name == my_name:
721
      source = constants.IP4_ADDRESS_LOCALHOST
722
    else:
723
      source = None
724
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
725
                                                     source=source)
726

    
727
  if constants.NV_USERSCRIPTS in what:
728
    result[constants.NV_USERSCRIPTS] = \
729
      [script for script in what[constants.NV_USERSCRIPTS]
730
       if not utils.IsExecutable(script)]
731

    
732
  if constants.NV_OOB_PATHS in what:
733
    result[constants.NV_OOB_PATHS] = tmp = []
734
    for path in what[constants.NV_OOB_PATHS]:
735
      try:
736
        st = os.stat(path)
737
      except OSError, err:
738
        tmp.append("error stating out of band helper: %s" % err)
739
      else:
740
        if stat.S_ISREG(st.st_mode):
741
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
742
            tmp.append(None)
743
          else:
744
            tmp.append("out of band helper %s is not executable" % path)
745
        else:
746
          tmp.append("out of band helper %s is not a file" % path)
747

    
748
  if constants.NV_LVLIST in what and vm_capable:
749
    try:
750
      val = GetVolumeList(utils.ListVolumeGroups().keys())
751
    except RPCFail, err:
752
      val = str(err)
753
    result[constants.NV_LVLIST] = val
754

    
755
  if constants.NV_INSTANCELIST in what and vm_capable:
756
    # GetInstanceList can fail
757
    try:
758
      val = GetInstanceList(what[constants.NV_INSTANCELIST])
759
    except RPCFail, err:
760
      val = str(err)
761
    result[constants.NV_INSTANCELIST] = val
762

    
763
  if constants.NV_VGLIST in what and vm_capable:
764
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
765

    
766
  if constants.NV_PVLIST in what and vm_capable:
767
    val = bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
768
                                       filter_allocatable=False)
769
    result[constants.NV_PVLIST] = map(objects.LvmPvInfo.ToDict, val)
770

    
771
  if constants.NV_VERSION in what:
772
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
773
                                    constants.RELEASE_VERSION)
774

    
775
  if constants.NV_HVINFO in what and vm_capable:
776
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
777
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
778

    
779
  if constants.NV_DRBDLIST in what and vm_capable:
780
    try:
781
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
782
    except errors.BlockDeviceError, err:
783
      logging.warning("Can't get used minors list", exc_info=True)
784
      used_minors = str(err)
785
    result[constants.NV_DRBDLIST] = used_minors
786

    
787
  if constants.NV_DRBDHELPER in what and vm_capable:
788
    status = True
789
    try:
790
      payload = bdev.BaseDRBD.GetUsermodeHelper()
791
    except errors.BlockDeviceError, err:
792
      logging.error("Can't get DRBD usermode helper: %s", str(err))
793
      status = False
794
      payload = str(err)
795
    result[constants.NV_DRBDHELPER] = (status, payload)
796

    
797
  if constants.NV_NODESETUP in what:
798
    result[constants.NV_NODESETUP] = tmpr = []
799
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
800
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
801
                  " under /sys, missing required directories /sys/block"
802
                  " and /sys/class/net")
803
    if (not os.path.isdir("/proc/sys") or
804
        not os.path.isfile("/proc/sysrq-trigger")):
805
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
806
                  " under /proc, missing required directory /proc/sys and"
807
                  " the file /proc/sysrq-trigger")
808

    
809
  if constants.NV_TIME in what:
810
    result[constants.NV_TIME] = utils.SplitTime(time.time())
811

    
812
  if constants.NV_OSLIST in what and vm_capable:
813
    result[constants.NV_OSLIST] = DiagnoseOS()
814

    
815
  if constants.NV_BRIDGES in what and vm_capable:
816
    result[constants.NV_BRIDGES] = [bridge
817
                                    for bridge in what[constants.NV_BRIDGES]
818
                                    if not utils.BridgeExists(bridge)]
819

    
820
  if what.get(constants.NV_FILE_STORAGE_PATHS) == my_name:
821
    result[constants.NV_FILE_STORAGE_PATHS] = \
822
      bdev.ComputeWrongFileStoragePaths()
823

    
824
  return result
825

    
826

    
827
def GetBlockDevSizes(devices):
828
  """Return the size of the given block devices
829

830
  @type devices: list
831
  @param devices: list of block device nodes to query
832
  @rtype: dict
833
  @return:
834
    dictionary of all block devices under /dev (key). The value is their
835
    size in MiB.
836

837
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
838

839
  """
840
  DEV_PREFIX = "/dev/"
841
  blockdevs = {}
842

    
843
  for devpath in devices:
844
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
845
      continue
846

    
847
    try:
848
      st = os.stat(devpath)
849
    except EnvironmentError, err:
850
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
851
      continue
852

    
853
    if stat.S_ISBLK(st.st_mode):
854
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
855
      if result.failed:
856
        # We don't want to fail, just do not list this device as available
857
        logging.warning("Cannot get size for block device %s", devpath)
858
        continue
859

    
860
      size = int(result.stdout) / (1024 * 1024)
861
      blockdevs[devpath] = size
862
  return blockdevs
863

    
864

    
865
def GetVolumeList(vg_names):
866
  """Compute list of logical volumes and their size.
867

868
  @type vg_names: list
869
  @param vg_names: the volume groups whose LVs we should list, or
870
      empty for all volume groups
871
  @rtype: dict
872
  @return:
873
      dictionary of all partions (key) with value being a tuple of
874
      their size (in MiB), inactive and online status::
875

876
        {'xenvg/test1': ('20.06', True, True)}
877

878
      in case of errors, a string is returned with the error
879
      details.
880

881
  """
882
  lvs = {}
883
  sep = "|"
884
  if not vg_names:
885
    vg_names = []
886
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
887
                         "--separator=%s" % sep,
888
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
889
  if result.failed:
890
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
891

    
892
  for line in result.stdout.splitlines():
893
    line = line.strip()
894
    match = _LVSLINE_REGEX.match(line)
895
    if not match:
896
      logging.error("Invalid line returned from lvs output: '%s'", line)
897
      continue
898
    vg_name, name, size, attr = match.groups()
899
    inactive = attr[4] == "-"
900
    online = attr[5] == "o"
901
    virtual = attr[0] == "v"
902
    if virtual:
903
      # we don't want to report such volumes as existing, since they
904
      # don't really hold data
905
      continue
906
    lvs[vg_name + "/" + name] = (size, inactive, online)
907

    
908
  return lvs
909

    
910

    
911
def ListVolumeGroups():
912
  """List the volume groups and their size.
913

914
  @rtype: dict
915
  @return: dictionary with keys volume name and values the
916
      size of the volume
917

918
  """
919
  return utils.ListVolumeGroups()
920

    
921

    
922
def NodeVolumes():
923
  """List all volumes on this node.
924

925
  @rtype: list
926
  @return:
927
    A list of dictionaries, each having four keys:
928
      - name: the logical volume name,
929
      - size: the size of the logical volume
930
      - dev: the physical device on which the LV lives
931
      - vg: the volume group to which it belongs
932

933
    In case of errors, we return an empty list and log the
934
    error.
935

936
    Note that since a logical volume can live on multiple physical
937
    volumes, the resulting list might include a logical volume
938
    multiple times.
939

940
  """
941
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
942
                         "--separator=|",
943
                         "--options=lv_name,lv_size,devices,vg_name"])
944
  if result.failed:
945
    _Fail("Failed to list logical volumes, lvs output: %s",
946
          result.output)
947

    
948
  def parse_dev(dev):
949
    return dev.split("(")[0]
950

    
951
  def handle_dev(dev):
952
    return [parse_dev(x) for x in dev.split(",")]
953

    
954
  def map_line(line):
955
    line = [v.strip() for v in line]
956
    return [{"name": line[0], "size": line[1],
957
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
958

    
959
  all_devs = []
960
  for line in result.stdout.splitlines():
961
    if line.count("|") >= 3:
962
      all_devs.extend(map_line(line.split("|")))
963
    else:
964
      logging.warning("Strange line in the output from lvs: '%s'", line)
965
  return all_devs
966

    
967

    
968
def BridgesExist(bridges_list):
969
  """Check if a list of bridges exist on the current node.
970

971
  @rtype: boolean
972
  @return: C{True} if all of them exist, C{False} otherwise
973

974
  """
975
  missing = []
976
  for bridge in bridges_list:
977
    if not utils.BridgeExists(bridge):
978
      missing.append(bridge)
979

    
980
  if missing:
981
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
982

    
983

    
984
def GetInstanceList(hypervisor_list):
985
  """Provides a list of instances.
986

987
  @type hypervisor_list: list
988
  @param hypervisor_list: the list of hypervisors to query information
989

990
  @rtype: list
991
  @return: a list of all running instances on the current node
992
    - instance1.example.com
993
    - instance2.example.com
994

995
  """
996
  results = []
997
  for hname in hypervisor_list:
998
    try:
999
      names = hypervisor.GetHypervisor(hname).ListInstances()
1000
      results.extend(names)
1001
    except errors.HypervisorError, err:
1002
      _Fail("Error enumerating instances (hypervisor %s): %s",
1003
            hname, err, exc=True)
1004

    
1005
  return results
1006

    
1007

    
1008
def GetInstanceInfo(instance, hname):
1009
  """Gives back the information about an instance as a dictionary.
1010

1011
  @type instance: string
1012
  @param instance: the instance name
1013
  @type hname: string
1014
  @param hname: the hypervisor type of the instance
1015

1016
  @rtype: dict
1017
  @return: dictionary with the following keys:
1018
      - memory: memory size of instance (int)
1019
      - state: xen state of instance (string)
1020
      - time: cpu time of instance (float)
1021
      - vcpus: the number of vcpus (int)
1022

1023
  """
1024
  output = {}
1025

    
1026
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
1027
  if iinfo is not None:
1028
    output["memory"] = iinfo[2]
1029
    output["vcpus"] = iinfo[3]
1030
    output["state"] = iinfo[4]
1031
    output["time"] = iinfo[5]
1032

    
1033
  return output
1034

    
1035

    
1036
def GetInstanceMigratable(instance):
1037
  """Gives whether an instance can be migrated.
1038

1039
  @type instance: L{objects.Instance}
1040
  @param instance: object representing the instance to be checked.
1041

1042
  @rtype: tuple
1043
  @return: tuple of (result, description) where:
1044
      - result: whether the instance can be migrated or not
1045
      - description: a description of the issue, if relevant
1046

1047
  """
1048
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1049
  iname = instance.name
1050
  if iname not in hyper.ListInstances():
1051
    _Fail("Instance %s is not running", iname)
1052

    
1053
  for idx in range(len(instance.disks)):
1054
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1055
    if not os.path.islink(link_name):
1056
      logging.warning("Instance %s is missing symlink %s for disk %d",
1057
                      iname, link_name, idx)
1058

    
1059

    
1060
def GetAllInstancesInfo(hypervisor_list):
1061
  """Gather data about all instances.
1062

1063
  This is the equivalent of L{GetInstanceInfo}, except that it
1064
  computes data for all instances at once, thus being faster if one
1065
  needs data about more than one instance.
1066

1067
  @type hypervisor_list: list
1068
  @param hypervisor_list: list of hypervisors to query for instance data
1069

1070
  @rtype: dict
1071
  @return: dictionary of instance: data, with data having the following keys:
1072
      - memory: memory size of instance (int)
1073
      - state: xen state of instance (string)
1074
      - time: cpu time of instance (float)
1075
      - vcpus: the number of vcpus
1076

1077
  """
1078
  output = {}
1079

    
1080
  for hname in hypervisor_list:
1081
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
1082
    if iinfo:
1083
      for name, _, memory, vcpus, state, times in iinfo:
1084
        value = {
1085
          "memory": memory,
1086
          "vcpus": vcpus,
1087
          "state": state,
1088
          "time": times,
1089
          }
1090
        if name in output:
1091
          # we only check static parameters, like memory and vcpus,
1092
          # and not state and time which can change between the
1093
          # invocations of the different hypervisors
1094
          for key in "memory", "vcpus":
1095
            if value[key] != output[name][key]:
1096
              _Fail("Instance %s is running twice"
1097
                    " with different parameters", name)
1098
        output[name] = value
1099

    
1100
  return output
1101

    
1102

    
1103
def _InstanceLogName(kind, os_name, instance, component):
1104
  """Compute the OS log filename for a given instance and operation.
1105

1106
  The instance name and os name are passed in as strings since not all
1107
  operations have these as part of an instance object.
1108

1109
  @type kind: string
1110
  @param kind: the operation type (e.g. add, import, etc.)
1111
  @type os_name: string
1112
  @param os_name: the os name
1113
  @type instance: string
1114
  @param instance: the name of the instance being imported/added/etc.
1115
  @type component: string or None
1116
  @param component: the name of the component of the instance being
1117
      transferred
1118

1119
  """
1120
  # TODO: Use tempfile.mkstemp to create unique filename
1121
  if component:
1122
    assert "/" not in component
1123
    c_msg = "-%s" % component
1124
  else:
1125
    c_msg = ""
1126
  base = ("%s-%s-%s%s-%s.log" %
1127
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1128
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1129

    
1130

    
1131
def InstanceOsAdd(instance, reinstall, debug):
1132
  """Add an OS to an instance.
1133

1134
  @type instance: L{objects.Instance}
1135
  @param instance: Instance whose OS is to be installed
1136
  @type reinstall: boolean
1137
  @param reinstall: whether this is an instance reinstall
1138
  @type debug: integer
1139
  @param debug: debug level, passed to the OS scripts
1140
  @rtype: None
1141

1142
  """
1143
  inst_os = OSFromDisk(instance.os)
1144

    
1145
  create_env = OSEnvironment(instance, inst_os, debug)
1146
  if reinstall:
1147
    create_env["INSTANCE_REINSTALL"] = "1"
1148

    
1149
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1150

    
1151
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1152
                        cwd=inst_os.path, output=logfile, reset_env=True)
1153
  if result.failed:
1154
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1155
                  " output: %s", result.cmd, result.fail_reason, logfile,
1156
                  result.output)
1157
    lines = [utils.SafeEncode(val)
1158
             for val in utils.TailFile(logfile, lines=20)]
1159
    _Fail("OS create script failed (%s), last lines in the"
1160
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1161

    
1162

    
1163
def RunRenameInstance(instance, old_name, debug):
1164
  """Run the OS rename script for an instance.
1165

1166
  @type instance: L{objects.Instance}
1167
  @param instance: Instance whose OS is to be installed
1168
  @type old_name: string
1169
  @param old_name: previous instance name
1170
  @type debug: integer
1171
  @param debug: debug level, passed to the OS scripts
1172
  @rtype: boolean
1173
  @return: the success of the operation
1174

1175
  """
1176
  inst_os = OSFromDisk(instance.os)
1177

    
1178
  rename_env = OSEnvironment(instance, inst_os, debug)
1179
  rename_env["OLD_INSTANCE_NAME"] = old_name
1180

    
1181
  logfile = _InstanceLogName("rename", instance.os,
1182
                             "%s-%s" % (old_name, instance.name), None)
1183

    
1184
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1185
                        cwd=inst_os.path, output=logfile, reset_env=True)
1186

    
1187
  if result.failed:
1188
    logging.error("os create command '%s' returned error: %s output: %s",
1189
                  result.cmd, result.fail_reason, result.output)
1190
    lines = [utils.SafeEncode(val)
1191
             for val in utils.TailFile(logfile, lines=20)]
1192
    _Fail("OS rename script failed (%s), last lines in the"
1193
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1194

    
1195

    
1196
def _GetBlockDevSymlinkPath(instance_name, idx):
1197
  return utils.PathJoin(pathutils.DISK_LINKS_DIR, "%s%s%d" %
1198
                        (instance_name, constants.DISK_SEPARATOR, idx))
1199

    
1200

    
1201
def _SymlinkBlockDev(instance_name, device_path, idx):
1202
  """Set up symlinks to a instance's block device.
1203

1204
  This is an auxiliary function run when an instance is start (on the primary
1205
  node) or when an instance is migrated (on the target node).
1206

1207

1208
  @param instance_name: the name of the target instance
1209
  @param device_path: path of the physical block device, on the node
1210
  @param idx: the disk index
1211
  @return: absolute path to the disk's symlink
1212

1213
  """
1214
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1215
  try:
1216
    os.symlink(device_path, link_name)
1217
  except OSError, err:
1218
    if err.errno == errno.EEXIST:
1219
      if (not os.path.islink(link_name) or
1220
          os.readlink(link_name) != device_path):
1221
        os.remove(link_name)
1222
        os.symlink(device_path, link_name)
1223
    else:
1224
      raise
1225

    
1226
  return link_name
1227

    
1228

    
1229
def _RemoveBlockDevLinks(instance_name, disks):
1230
  """Remove the block device symlinks belonging to the given instance.
1231

1232
  """
1233
  for idx, _ in enumerate(disks):
1234
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1235
    if os.path.islink(link_name):
1236
      try:
1237
        os.remove(link_name)
1238
      except OSError:
1239
        logging.exception("Can't remove symlink '%s'", link_name)
1240

    
1241

    
1242
def _GatherAndLinkBlockDevs(instance):
1243
  """Set up an instance's block device(s).
1244

1245
  This is run on the primary node at instance startup. The block
1246
  devices must be already assembled.
1247

1248
  @type instance: L{objects.Instance}
1249
  @param instance: the instance whose disks we shoul assemble
1250
  @rtype: list
1251
  @return: list of (disk_object, device_path)
1252

1253
  """
1254
  block_devices = []
1255
  for idx, disk in enumerate(instance.disks):
1256
    device = _RecursiveFindBD(disk)
1257
    if device is None:
1258
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1259
                                    str(disk))
1260
    device.Open()
1261
    try:
1262
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1263
    except OSError, e:
1264
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1265
                                    e.strerror)
1266

    
1267
    block_devices.append((disk, link_name))
1268

    
1269
  return block_devices
1270

    
1271

    
1272
def StartInstance(instance, startup_paused):
1273
  """Start an instance.
1274

1275
  @type instance: L{objects.Instance}
1276
  @param instance: the instance object
1277
  @type startup_paused: bool
1278
  @param instance: pause instance at startup?
1279
  @rtype: None
1280

1281
  """
1282
  running_instances = GetInstanceList([instance.hypervisor])
1283

    
1284
  if instance.name in running_instances:
1285
    logging.info("Instance %s already running, not starting", instance.name)
1286
    return
1287

    
1288
  try:
1289
    block_devices = _GatherAndLinkBlockDevs(instance)
1290
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1291
    hyper.StartInstance(instance, block_devices, startup_paused)
1292
  except errors.BlockDeviceError, err:
1293
    _Fail("Block device error: %s", err, exc=True)
1294
  except errors.HypervisorError, err:
1295
    _RemoveBlockDevLinks(instance.name, instance.disks)
1296
    _Fail("Hypervisor error: %s", err, exc=True)
1297

    
1298

    
1299
def InstanceShutdown(instance, timeout):
1300
  """Shut an instance down.
1301

1302
  @note: this functions uses polling with a hardcoded timeout.
1303

1304
  @type instance: L{objects.Instance}
1305
  @param instance: the instance object
1306
  @type timeout: integer
1307
  @param timeout: maximum timeout for soft shutdown
1308
  @rtype: None
1309

1310
  """
1311
  hv_name = instance.hypervisor
1312
  hyper = hypervisor.GetHypervisor(hv_name)
1313
  iname = instance.name
1314

    
1315
  if instance.name not in hyper.ListInstances():
1316
    logging.info("Instance %s not running, doing nothing", iname)
1317
    return
1318

    
1319
  class _TryShutdown:
1320
    def __init__(self):
1321
      self.tried_once = False
1322

    
1323
    def __call__(self):
1324
      if iname not in hyper.ListInstances():
1325
        return
1326

    
1327
      try:
1328
        hyper.StopInstance(instance, retry=self.tried_once)
1329
      except errors.HypervisorError, err:
1330
        if iname not in hyper.ListInstances():
1331
          # if the instance is no longer existing, consider this a
1332
          # success and go to cleanup
1333
          return
1334

    
1335
        _Fail("Failed to stop instance %s: %s", iname, err)
1336

    
1337
      self.tried_once = True
1338

    
1339
      raise utils.RetryAgain()
1340

    
1341
  try:
1342
    utils.Retry(_TryShutdown(), 5, timeout)
1343
  except utils.RetryTimeout:
1344
    # the shutdown did not succeed
1345
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1346

    
1347
    try:
1348
      hyper.StopInstance(instance, force=True)
1349
    except errors.HypervisorError, err:
1350
      if iname in hyper.ListInstances():
1351
        # only raise an error if the instance still exists, otherwise
1352
        # the error could simply be "instance ... unknown"!
1353
        _Fail("Failed to force stop instance %s: %s", iname, err)
1354

    
1355
    time.sleep(1)
1356

    
1357
    if iname in hyper.ListInstances():
1358
      _Fail("Could not shutdown instance %s even by destroy", iname)
1359

    
1360
  try:
1361
    hyper.CleanupInstance(instance.name)
1362
  except errors.HypervisorError, err:
1363
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1364

    
1365
  _RemoveBlockDevLinks(iname, instance.disks)
1366

    
1367

    
1368
def InstanceReboot(instance, reboot_type, shutdown_timeout):
1369
  """Reboot an instance.
1370

1371
  @type instance: L{objects.Instance}
1372
  @param instance: the instance object to reboot
1373
  @type reboot_type: str
1374
  @param reboot_type: the type of reboot, one the following
1375
    constants:
1376
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1377
        instance OS, do not recreate the VM
1378
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1379
        restart the VM (at the hypervisor level)
1380
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1381
        not accepted here, since that mode is handled differently, in
1382
        cmdlib, and translates into full stop and start of the
1383
        instance (instead of a call_instance_reboot RPC)
1384
  @type shutdown_timeout: integer
1385
  @param shutdown_timeout: maximum timeout for soft shutdown
1386
  @rtype: None
1387

1388
  """
1389
  running_instances = GetInstanceList([instance.hypervisor])
1390

    
1391
  if instance.name not in running_instances:
1392
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1393

    
1394
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1395
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1396
    try:
1397
      hyper.RebootInstance(instance)
1398
    except errors.HypervisorError, err:
1399
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1400
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1401
    try:
1402
      InstanceShutdown(instance, shutdown_timeout)
1403
      return StartInstance(instance, False)
1404
    except errors.HypervisorError, err:
1405
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1406
  else:
1407
    _Fail("Invalid reboot_type received: %s", reboot_type)
1408

    
1409

    
1410
def InstanceBalloonMemory(instance, memory):
1411
  """Resize an instance's memory.
1412

1413
  @type instance: L{objects.Instance}
1414
  @param instance: the instance object
1415
  @type memory: int
1416
  @param memory: new memory amount in MB
1417
  @rtype: None
1418

1419
  """
1420
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1421
  running = hyper.ListInstances()
1422
  if instance.name not in running:
1423
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1424
    return
1425
  try:
1426
    hyper.BalloonInstanceMemory(instance, memory)
1427
  except errors.HypervisorError, err:
1428
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1429

    
1430

    
1431
def MigrationInfo(instance):
1432
  """Gather information about an instance to be migrated.
1433

1434
  @type instance: L{objects.Instance}
1435
  @param instance: the instance definition
1436

1437
  """
1438
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1439
  try:
1440
    info = hyper.MigrationInfo(instance)
1441
  except errors.HypervisorError, err:
1442
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1443
  return info
1444

    
1445

    
1446
def AcceptInstance(instance, info, target):
1447
  """Prepare the node to accept an instance.
1448

1449
  @type instance: L{objects.Instance}
1450
  @param instance: the instance definition
1451
  @type info: string/data (opaque)
1452
  @param info: migration information, from the source node
1453
  @type target: string
1454
  @param target: target host (usually ip), on this node
1455

1456
  """
1457
  # TODO: why is this required only for DTS_EXT_MIRROR?
1458
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1459
    # Create the symlinks, as the disks are not active
1460
    # in any way
1461
    try:
1462
      _GatherAndLinkBlockDevs(instance)
1463
    except errors.BlockDeviceError, err:
1464
      _Fail("Block device error: %s", err, exc=True)
1465

    
1466
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1467
  try:
1468
    hyper.AcceptInstance(instance, info, target)
1469
  except errors.HypervisorError, err:
1470
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1471
      _RemoveBlockDevLinks(instance.name, instance.disks)
1472
    _Fail("Failed to accept instance: %s", err, exc=True)
1473

    
1474

    
1475
def FinalizeMigrationDst(instance, info, success):
1476
  """Finalize any preparation to accept an instance.
1477

1478
  @type instance: L{objects.Instance}
1479
  @param instance: the instance definition
1480
  @type info: string/data (opaque)
1481
  @param info: migration information, from the source node
1482
  @type success: boolean
1483
  @param success: whether the migration was a success or a failure
1484

1485
  """
1486
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1487
  try:
1488
    hyper.FinalizeMigrationDst(instance, info, success)
1489
  except errors.HypervisorError, err:
1490
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1491

    
1492

    
1493
def MigrateInstance(instance, target, live):
1494
  """Migrates an instance to another node.
1495

1496
  @type instance: L{objects.Instance}
1497
  @param instance: the instance definition
1498
  @type target: string
1499
  @param target: the target node name
1500
  @type live: boolean
1501
  @param live: whether the migration should be done live or not (the
1502
      interpretation of this parameter is left to the hypervisor)
1503
  @raise RPCFail: if migration fails for some reason
1504

1505
  """
1506
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1507

    
1508
  try:
1509
    hyper.MigrateInstance(instance, target, live)
1510
  except errors.HypervisorError, err:
1511
    _Fail("Failed to migrate instance: %s", err, exc=True)
1512

    
1513

    
1514
def FinalizeMigrationSource(instance, success, live):
1515
  """Finalize the instance migration on the source node.
1516

1517
  @type instance: L{objects.Instance}
1518
  @param instance: the instance definition of the migrated instance
1519
  @type success: bool
1520
  @param success: whether the migration succeeded or not
1521
  @type live: bool
1522
  @param live: whether the user requested a live migration or not
1523
  @raise RPCFail: If the execution fails for some reason
1524

1525
  """
1526
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1527

    
1528
  try:
1529
    hyper.FinalizeMigrationSource(instance, success, live)
1530
  except Exception, err:  # pylint: disable=W0703
1531
    _Fail("Failed to finalize the migration on the source node: %s", err,
1532
          exc=True)
1533

    
1534

    
1535
def GetMigrationStatus(instance):
1536
  """Get the migration status
1537

1538
  @type instance: L{objects.Instance}
1539
  @param instance: the instance that is being migrated
1540
  @rtype: L{objects.MigrationStatus}
1541
  @return: the status of the current migration (one of
1542
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1543
           progress info that can be retrieved from the hypervisor
1544
  @raise RPCFail: If the migration status cannot be retrieved
1545

1546
  """
1547
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1548
  try:
1549
    return hyper.GetMigrationStatus(instance)
1550
  except Exception, err:  # pylint: disable=W0703
1551
    _Fail("Failed to get migration status: %s", err, exc=True)
1552

    
1553
def HotAddDisk(instance, disk, dev_path, seq):
1554
  """Hot add a nic
1555

1556
  """
1557
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1558
  return hyper.HotAddDisk(instance, disk, dev_path, seq)
1559

    
1560
def HotDelDisk(instance, disk, seq):
1561
  """Hot add a nic
1562

1563
  """
1564
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1565
  return hyper.HotDelDisk(instance, disk, seq)
1566

    
1567
def HotAddNic(instance, nic, seq):
1568
  """Hot add a nic
1569

1570
  """
1571
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1572
  return hyper.HotAddNic(instance, nic, seq)
1573

    
1574
def HotDelNic(instance, nic, seq):
1575
  """Hot add a nic
1576

1577
  """
1578
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1579
  return hyper.HotDelNic(instance, nic, seq)
1580

    
1581

    
1582
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
1583
  """Creates a block device for an instance.
1584

1585
  @type disk: L{objects.Disk}
1586
  @param disk: the object describing the disk we should create
1587
  @type size: int
1588
  @param size: the size of the physical underlying device, in MiB
1589
  @type owner: str
1590
  @param owner: the name of the instance for which disk is created,
1591
      used for device cache data
1592
  @type on_primary: boolean
1593
  @param on_primary:  indicates if it is the primary node or not
1594
  @type info: string
1595
  @param info: string that will be sent to the physical device
1596
      creation, used for example to set (LVM) tags on LVs
1597
  @type excl_stor: boolean
1598
  @param excl_stor: Whether exclusive_storage is active
1599

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

1604
  """
1605
  # TODO: remove the obsolete "size" argument
1606
  # pylint: disable=W0613
1607
  clist = []
1608
  if disk.children:
1609
    for child in disk.children:
1610
      try:
1611
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1612
      except errors.BlockDeviceError, err:
1613
        _Fail("Can't assemble device %s: %s", child, err)
1614
      if on_primary or disk.AssembleOnSecondary():
1615
        # we need the children open in case the device itself has to
1616
        # be assembled
1617
        try:
1618
          # pylint: disable=E1103
1619
          crdev.Open()
1620
        except errors.BlockDeviceError, err:
1621
          _Fail("Can't make child '%s' read-write: %s", child, err)
1622
      clist.append(crdev)
1623

    
1624
  try:
1625
    device = bdev.Create(disk, clist, excl_stor)
1626
  except errors.BlockDeviceError, err:
1627
    _Fail("Can't create block device: %s", err)
1628

    
1629
  if on_primary or disk.AssembleOnSecondary():
1630
    try:
1631
      device.Assemble()
1632
    except errors.BlockDeviceError, err:
1633
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1634
    if on_primary or disk.OpenOnSecondary():
1635
      try:
1636
        device.Open(force=True)
1637
      except errors.BlockDeviceError, err:
1638
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1639
    DevCacheManager.UpdateCache(device.dev_path, owner,
1640
                                on_primary, disk.iv_name)
1641

    
1642
  device.SetInfo(info)
1643

    
1644
  return device.unique_id
1645

    
1646

    
1647
def _WipeDevice(path, offset, size):
1648
  """This function actually wipes the device.
1649

1650
  @param path: The path to the device to wipe
1651
  @param offset: The offset in MiB in the file
1652
  @param size: The size in MiB to write
1653

1654
  """
1655
  # Internal sizes are always in Mebibytes; if the following "dd" command
1656
  # should use a different block size the offset and size given to this
1657
  # function must be adjusted accordingly before being passed to "dd".
1658
  block_size = 1024 * 1024
1659

    
1660
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1661
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
1662
         "count=%d" % size]
1663
  result = utils.RunCmd(cmd)
1664

    
1665
  if result.failed:
1666
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1667
          result.fail_reason, result.output)
1668

    
1669

    
1670
def BlockdevWipe(disk, offset, size):
1671
  """Wipes a block device.
1672

1673
  @type disk: L{objects.Disk}
1674
  @param disk: the disk object we want to wipe
1675
  @type offset: int
1676
  @param offset: The offset in MiB in the file
1677
  @type size: int
1678
  @param size: The size in MiB to write
1679

1680
  """
1681
  try:
1682
    rdev = _RecursiveFindBD(disk)
1683
  except errors.BlockDeviceError:
1684
    rdev = None
1685

    
1686
  if not rdev:
1687
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1688

    
1689
  # Do cross verify some of the parameters
1690
  if offset < 0:
1691
    _Fail("Negative offset")
1692
  if size < 0:
1693
    _Fail("Negative size")
1694
  if offset > rdev.size:
1695
    _Fail("Offset is bigger than device size")
1696
  if (offset + size) > rdev.size:
1697
    _Fail("The provided offset and size to wipe is bigger than device size")
1698

    
1699
  _WipeDevice(rdev.dev_path, offset, size)
1700

    
1701

    
1702
def BlockdevPauseResumeSync(disks, pause):
1703
  """Pause or resume the sync of the block device.
1704

1705
  @type disks: list of L{objects.Disk}
1706
  @param disks: the disks object we want to pause/resume
1707
  @type pause: bool
1708
  @param pause: Wheater to pause or resume
1709

1710
  """
1711
  success = []
1712
  for disk in disks:
1713
    try:
1714
      rdev = _RecursiveFindBD(disk)
1715
    except errors.BlockDeviceError:
1716
      rdev = None
1717

    
1718
    if not rdev:
1719
      success.append((False, ("Cannot change sync for device %s:"
1720
                              " device not found" % disk.iv_name)))
1721
      continue
1722

    
1723
    result = rdev.PauseResumeSync(pause)
1724

    
1725
    if result:
1726
      success.append((result, None))
1727
    else:
1728
      if pause:
1729
        msg = "Pause"
1730
      else:
1731
        msg = "Resume"
1732
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1733

    
1734
  return success
1735

    
1736

    
1737
def BlockdevRemove(disk):
1738
  """Remove a block device.
1739

1740
  @note: This is intended to be called recursively.
1741

1742
  @type disk: L{objects.Disk}
1743
  @param disk: the disk object we should remove
1744
  @rtype: boolean
1745
  @return: the success of the operation
1746

1747
  """
1748
  msgs = []
1749
  try:
1750
    rdev = _RecursiveFindBD(disk)
1751
  except errors.BlockDeviceError, err:
1752
    # probably can't attach
1753
    logging.info("Can't attach to device %s in remove", disk)
1754
    rdev = None
1755
  if rdev is not None:
1756
    r_path = rdev.dev_path
1757
    try:
1758
      rdev.Remove()
1759
    except errors.BlockDeviceError, err:
1760
      msgs.append(str(err))
1761
    if not msgs:
1762
      DevCacheManager.RemoveCache(r_path)
1763

    
1764
  if disk.children:
1765
    for child in disk.children:
1766
      try:
1767
        BlockdevRemove(child)
1768
      except RPCFail, err:
1769
        msgs.append(str(err))
1770

    
1771
  if msgs:
1772
    _Fail("; ".join(msgs))
1773

    
1774

    
1775
def _RecursiveAssembleBD(disk, owner, as_primary):
1776
  """Activate a block device for an instance.
1777

1778
  This is run on the primary and secondary nodes for an instance.
1779

1780
  @note: this function is called recursively.
1781

1782
  @type disk: L{objects.Disk}
1783
  @param disk: the disk we try to assemble
1784
  @type owner: str
1785
  @param owner: the name of the instance which owns the disk
1786
  @type as_primary: boolean
1787
  @param as_primary: if we should make the block device
1788
      read/write
1789

1790
  @return: the assembled device or None (in case no device
1791
      was assembled)
1792
  @raise errors.BlockDeviceError: in case there is an error
1793
      during the activation of the children or the device
1794
      itself
1795

1796
  """
1797
  children = []
1798
  if disk.children:
1799
    mcn = disk.ChildrenNeeded()
1800
    if mcn == -1:
1801
      mcn = 0 # max number of Nones allowed
1802
    else:
1803
      mcn = len(disk.children) - mcn # max number of Nones
1804
    for chld_disk in disk.children:
1805
      try:
1806
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1807
      except errors.BlockDeviceError, err:
1808
        if children.count(None) >= mcn:
1809
          raise
1810
        cdev = None
1811
        logging.error("Error in child activation (but continuing): %s",
1812
                      str(err))
1813
      children.append(cdev)
1814

    
1815
  if as_primary or disk.AssembleOnSecondary():
1816
    r_dev = bdev.Assemble(disk, children)
1817
    result = r_dev
1818
    if as_primary or disk.OpenOnSecondary():
1819
      r_dev.Open()
1820
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1821
                                as_primary, disk.iv_name)
1822

    
1823
  else:
1824
    result = True
1825
  return result
1826

    
1827

    
1828
def BlockdevAssemble(disk, owner, as_primary, idx):
1829
  """Activate a block device for an instance.
1830

1831
  This is a wrapper over _RecursiveAssembleBD.
1832

1833
  @rtype: str or boolean
1834
  @return: a C{/dev/...} path for primary nodes, and
1835
      C{True} for secondary nodes
1836

1837
  """
1838
  try:
1839
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1840
    if isinstance(result, bdev.BlockDev):
1841
      # pylint: disable=E1103
1842
      result = result.dev_path
1843
      if as_primary:
1844
        _SymlinkBlockDev(owner, result, idx)
1845
  except errors.BlockDeviceError, err:
1846
    _Fail("Error while assembling disk: %s", err, exc=True)
1847
  except OSError, err:
1848
    _Fail("Error while symlinking disk: %s", err, exc=True)
1849

    
1850
  return result
1851

    
1852

    
1853
def BlockdevShutdown(disk):
1854
  """Shut down a block device.
1855

1856
  First, if the device is assembled (Attach() is successful), then
1857
  the device is shutdown. Then the children of the device are
1858
  shutdown.
1859

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

1864
  @type disk: L{objects.Disk}
1865
  @param disk: the description of the disk we should
1866
      shutdown
1867
  @rtype: None
1868

1869
  """
1870
  msgs = []
1871
  r_dev = _RecursiveFindBD(disk)
1872
  if r_dev is not None:
1873
    r_path = r_dev.dev_path
1874
    try:
1875
      r_dev.Shutdown()
1876
      DevCacheManager.RemoveCache(r_path)
1877
    except errors.BlockDeviceError, err:
1878
      msgs.append(str(err))
1879

    
1880
  if disk.children:
1881
    for child in disk.children:
1882
      try:
1883
        BlockdevShutdown(child)
1884
      except RPCFail, err:
1885
        msgs.append(str(err))
1886

    
1887
  if msgs:
1888
    _Fail("; ".join(msgs))
1889

    
1890

    
1891
def BlockdevAddchildren(parent_cdev, new_cdevs):
1892
  """Extend a mirrored block device.
1893

1894
  @type parent_cdev: L{objects.Disk}
1895
  @param parent_cdev: the disk to which we should add children
1896
  @type new_cdevs: list of L{objects.Disk}
1897
  @param new_cdevs: the list of children which we should add
1898
  @rtype: None
1899

1900
  """
1901
  parent_bdev = _RecursiveFindBD(parent_cdev)
1902
  if parent_bdev is None:
1903
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1904
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1905
  if new_bdevs.count(None) > 0:
1906
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1907
  parent_bdev.AddChildren(new_bdevs)
1908

    
1909

    
1910
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1911
  """Shrink a mirrored block device.
1912

1913
  @type parent_cdev: L{objects.Disk}
1914
  @param parent_cdev: the disk from which we should remove children
1915
  @type new_cdevs: list of L{objects.Disk}
1916
  @param new_cdevs: the list of children which we should remove
1917
  @rtype: None
1918

1919
  """
1920
  parent_bdev = _RecursiveFindBD(parent_cdev)
1921
  if parent_bdev is None:
1922
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1923
  devs = []
1924
  for disk in new_cdevs:
1925
    rpath = disk.StaticDevPath()
1926
    if rpath is None:
1927
      bd = _RecursiveFindBD(disk)
1928
      if bd is None:
1929
        _Fail("Can't find device %s while removing children", disk)
1930
      else:
1931
        devs.append(bd.dev_path)
1932
    else:
1933
      if not utils.IsNormAbsPath(rpath):
1934
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
1935
      devs.append(rpath)
1936
  parent_bdev.RemoveChildren(devs)
1937

    
1938

    
1939
def BlockdevGetmirrorstatus(disks):
1940
  """Get the mirroring status of a list of devices.
1941

1942
  @type disks: list of L{objects.Disk}
1943
  @param disks: the list of disks which we should query
1944
  @rtype: disk
1945
  @return: List of L{objects.BlockDevStatus}, one for each disk
1946
  @raise errors.BlockDeviceError: if any of the disks cannot be
1947
      found
1948

1949
  """
1950
  stats = []
1951
  for dsk in disks:
1952
    rbd = _RecursiveFindBD(dsk)
1953
    if rbd is None:
1954
      _Fail("Can't find device %s", dsk)
1955

    
1956
    stats.append(rbd.CombinedSyncStatus())
1957

    
1958
  return stats
1959

    
1960

    
1961
def BlockdevGetmirrorstatusMulti(disks):
1962
  """Get the mirroring status of a list of devices.
1963

1964
  @type disks: list of L{objects.Disk}
1965
  @param disks: the list of disks which we should query
1966
  @rtype: disk
1967
  @return: List of tuples, (bool, status), one for each disk; bool denotes
1968
    success/failure, status is L{objects.BlockDevStatus} on success, string
1969
    otherwise
1970

1971
  """
1972
  result = []
1973
  for disk in disks:
1974
    try:
1975
      rbd = _RecursiveFindBD(disk)
1976
      if rbd is None:
1977
        result.append((False, "Can't find device %s" % disk))
1978
        continue
1979

    
1980
      status = rbd.CombinedSyncStatus()
1981
    except errors.BlockDeviceError, err:
1982
      logging.exception("Error while getting disk status")
1983
      result.append((False, str(err)))
1984
    else:
1985
      result.append((True, status))
1986

    
1987
  assert len(disks) == len(result)
1988

    
1989
  return result
1990

    
1991

    
1992
def _RecursiveFindBD(disk):
1993
  """Check if a device is activated.
1994

1995
  If so, return information about the real device.
1996

1997
  @type disk: L{objects.Disk}
1998
  @param disk: the disk object we need to find
1999

2000
  @return: None if the device can't be found,
2001
      otherwise the device instance
2002

2003
  """
2004
  children = []
2005
  if disk.children:
2006
    for chdisk in disk.children:
2007
      children.append(_RecursiveFindBD(chdisk))
2008

    
2009
  return bdev.FindDevice(disk, children)
2010

    
2011

    
2012
def _OpenRealBD(disk):
2013
  """Opens the underlying block device of a disk.
2014

2015
  @type disk: L{objects.Disk}
2016
  @param disk: the disk object we want to open
2017

2018
  """
2019
  real_disk = _RecursiveFindBD(disk)
2020
  if real_disk is None:
2021
    _Fail("Block device '%s' is not set up", disk)
2022

    
2023
  real_disk.Open()
2024

    
2025
  return real_disk
2026

    
2027

    
2028
def BlockdevFind(disk):
2029
  """Check if a device is activated.
2030

2031
  If it is, return information about the real device.
2032

2033
  @type disk: L{objects.Disk}
2034
  @param disk: the disk to find
2035
  @rtype: None or objects.BlockDevStatus
2036
  @return: None if the disk cannot be found, otherwise a the current
2037
           information
2038

2039
  """
2040
  try:
2041
    rbd = _RecursiveFindBD(disk)
2042
  except errors.BlockDeviceError, err:
2043
    _Fail("Failed to find device: %s", err, exc=True)
2044

    
2045
  if rbd is None:
2046
    return None
2047

    
2048
  return rbd.GetSyncStatus()
2049

    
2050

    
2051
def BlockdevGetsize(disks):
2052
  """Computes the size of the given disks.
2053

2054
  If a disk is not found, returns None instead.
2055

2056
  @type disks: list of L{objects.Disk}
2057
  @param disks: the list of disk to compute the size for
2058
  @rtype: list
2059
  @return: list with elements None if the disk cannot be found,
2060
      otherwise the size
2061

2062
  """
2063
  result = []
2064
  for cf in disks:
2065
    try:
2066
      rbd = _RecursiveFindBD(cf)
2067
    except errors.BlockDeviceError:
2068
      result.append(None)
2069
      continue
2070
    if rbd is None:
2071
      result.append(None)
2072
    else:
2073
      result.append(rbd.GetActualSize())
2074
  return result
2075

    
2076

    
2077
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2078
  """Export a block device to a remote node.
2079

2080
  @type disk: L{objects.Disk}
2081
  @param disk: the description of the disk to export
2082
  @type dest_node: str
2083
  @param dest_node: the destination node to export to
2084
  @type dest_path: str
2085
  @param dest_path: the destination path on the target node
2086
  @type cluster_name: str
2087
  @param cluster_name: the cluster name, needed for SSH hostalias
2088
  @rtype: None
2089

2090
  """
2091
  real_disk = _OpenRealBD(disk)
2092

    
2093
  # the block size on the read dd is 1MiB to match our units
2094
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2095
                               "dd if=%s bs=1048576 count=%s",
2096
                               real_disk.dev_path, str(disk.size))
2097

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

    
2107
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2108
                                                   constants.SSH_LOGIN_USER,
2109
                                                   destcmd)
2110

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

    
2114
  result = utils.RunCmd(["bash", "-c", command])
2115

    
2116
  if result.failed:
2117
    _Fail("Disk copy command '%s' returned error: %s"
2118
          " output: %s", command, result.fail_reason, result.output)
2119

    
2120

    
2121
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2122
  """Write a file to the filesystem.
2123

2124
  This allows the master to overwrite(!) a file. It will only perform
2125
  the operation if the file belongs to a list of configuration files.
2126

2127
  @type file_name: str
2128
  @param file_name: the target file name
2129
  @type data: str
2130
  @param data: the new contents of the file
2131
  @type mode: int
2132
  @param mode: the mode to give the file (can be None)
2133
  @type uid: string
2134
  @param uid: the owner of the file
2135
  @type gid: string
2136
  @param gid: the group of the file
2137
  @type atime: float
2138
  @param atime: the atime to set on the file (can be None)
2139
  @type mtime: float
2140
  @param mtime: the mtime to set on the file (can be None)
2141
  @rtype: None
2142

2143
  """
2144
  file_name = vcluster.LocalizeVirtualPath(file_name)
2145

    
2146
  if not os.path.isabs(file_name):
2147
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2148

    
2149
  if file_name not in _ALLOWED_UPLOAD_FILES:
2150
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2151
          file_name)
2152

    
2153
  raw_data = _Decompress(data)
2154

    
2155
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2156
    _Fail("Invalid username/groupname type")
2157

    
2158
  getents = runtime.GetEnts()
2159
  uid = getents.LookupUser(uid)
2160
  gid = getents.LookupGroup(gid)
2161

    
2162
  utils.SafeWriteFile(file_name, None,
2163
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2164
                      atime=atime, mtime=mtime)
2165

    
2166

    
2167
def RunOob(oob_program, command, node, timeout):
2168
  """Executes oob_program with given command on given node.
2169

2170
  @param oob_program: The path to the executable oob_program
2171
  @param command: The command to invoke on oob_program
2172
  @param node: The node given as an argument to the program
2173
  @param timeout: Timeout after which we kill the oob program
2174

2175
  @return: stdout
2176
  @raise RPCFail: If execution fails for some reason
2177

2178
  """
2179
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2180

    
2181
  if result.failed:
2182
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2183
          result.fail_reason, result.output)
2184

    
2185
  return result.stdout
2186

    
2187

    
2188
def _OSOndiskAPIVersion(os_dir):
2189
  """Compute and return the API version of a given OS.
2190

2191
  This function will try to read the API version of the OS residing in
2192
  the 'os_dir' directory.
2193

2194
  @type os_dir: str
2195
  @param os_dir: the directory in which we should look for the OS
2196
  @rtype: tuple
2197
  @return: tuple (status, data) with status denoting the validity and
2198
      data holding either the vaid versions or an error message
2199

2200
  """
2201
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2202

    
2203
  try:
2204
    st = os.stat(api_file)
2205
  except EnvironmentError, err:
2206
    return False, ("Required file '%s' not found under path %s: %s" %
2207
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2208

    
2209
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2210
    return False, ("File '%s' in %s is not a regular file" %
2211
                   (constants.OS_API_FILE, os_dir))
2212

    
2213
  try:
2214
    api_versions = utils.ReadFile(api_file).splitlines()
2215
  except EnvironmentError, err:
2216
    return False, ("Error while reading the API version file at %s: %s" %
2217
                   (api_file, utils.ErrnoOrStr(err)))
2218

    
2219
  try:
2220
    api_versions = [int(version.strip()) for version in api_versions]
2221
  except (TypeError, ValueError), err:
2222
    return False, ("API version(s) can't be converted to integer: %s" %
2223
                   str(err))
2224

    
2225
  return True, api_versions
2226

    
2227

    
2228
def DiagnoseOS(top_dirs=None):
2229
  """Compute the validity for all OSes.
2230

2231
  @type top_dirs: list
2232
  @param top_dirs: the list of directories in which to
2233
      search (if not given defaults to
2234
      L{pathutils.OS_SEARCH_PATH})
2235
  @rtype: list of L{objects.OS}
2236
  @return: a list of tuples (name, path, status, diagnose, variants,
2237
      parameters, api_version) for all (potential) OSes under all
2238
      search paths, where:
2239
          - name is the (potential) OS name
2240
          - path is the full path to the OS
2241
          - status True/False is the validity of the OS
2242
          - diagnose is the error message for an invalid OS, otherwise empty
2243
          - variants is a list of supported OS variants, if any
2244
          - parameters is a list of (name, help) parameters, if any
2245
          - api_version is a list of support OS API versions
2246

2247
  """
2248
  if top_dirs is None:
2249
    top_dirs = pathutils.OS_SEARCH_PATH
2250

    
2251
  result = []
2252
  for dir_name in top_dirs:
2253
    if os.path.isdir(dir_name):
2254
      try:
2255
        f_names = utils.ListVisibleFiles(dir_name)
2256
      except EnvironmentError, err:
2257
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2258
        break
2259
      for name in f_names:
2260
        os_path = utils.PathJoin(dir_name, name)
2261
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2262
        if status:
2263
          diagnose = ""
2264
          variants = os_inst.supported_variants
2265
          parameters = os_inst.supported_parameters
2266
          api_versions = os_inst.api_versions
2267
        else:
2268
          diagnose = os_inst
2269
          variants = parameters = api_versions = []
2270
        result.append((name, os_path, status, diagnose, variants,
2271
                       parameters, api_versions))
2272

    
2273
  return result
2274

    
2275

    
2276
def _TryOSFromDisk(name, base_dir=None):
2277
  """Create an OS instance from disk.
2278

2279
  This function will return an OS instance if the given name is a
2280
  valid OS name.
2281

2282
  @type base_dir: string
2283
  @keyword base_dir: Base directory containing OS installations.
2284
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2285
  @rtype: tuple
2286
  @return: success and either the OS instance if we find a valid one,
2287
      or error message
2288

2289
  """
2290
  if base_dir is None:
2291
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2292
  else:
2293
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2294

    
2295
  if os_dir is None:
2296
    return False, "Directory for OS %s not found in search path" % name
2297

    
2298
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2299
  if not status:
2300
    # push the error up
2301
    return status, api_versions
2302

    
2303
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2304
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2305
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2306

    
2307
  # OS Files dictionary, we will populate it with the absolute path
2308
  # names; if the value is True, then it is a required file, otherwise
2309
  # an optional one
2310
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2311

    
2312
  if max(api_versions) >= constants.OS_API_V15:
2313
    os_files[constants.OS_VARIANTS_FILE] = False
2314

    
2315
  if max(api_versions) >= constants.OS_API_V20:
2316
    os_files[constants.OS_PARAMETERS_FILE] = True
2317
  else:
2318
    del os_files[constants.OS_SCRIPT_VERIFY]
2319

    
2320
  for (filename, required) in os_files.items():
2321
    os_files[filename] = utils.PathJoin(os_dir, filename)
2322

    
2323
    try:
2324
      st = os.stat(os_files[filename])
2325
    except EnvironmentError, err:
2326
      if err.errno == errno.ENOENT and not required:
2327
        del os_files[filename]
2328
        continue
2329
      return False, ("File '%s' under path '%s' is missing (%s)" %
2330
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2331

    
2332
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2333
      return False, ("File '%s' under path '%s' is not a regular file" %
2334
                     (filename, os_dir))
2335

    
2336
    if filename in constants.OS_SCRIPTS:
2337
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2338
        return False, ("File '%s' under path '%s' is not executable" %
2339
                       (filename, os_dir))
2340

    
2341
  variants = []
2342
  if constants.OS_VARIANTS_FILE in os_files:
2343
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2344
    try:
2345
      variants = \
2346
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2347
    except EnvironmentError, err:
2348
      # we accept missing files, but not other errors
2349
      if err.errno != errno.ENOENT:
2350
        return False, ("Error while reading the OS variants file at %s: %s" %
2351
                       (variants_file, utils.ErrnoOrStr(err)))
2352

    
2353
  parameters = []
2354
  if constants.OS_PARAMETERS_FILE in os_files:
2355
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2356
    try:
2357
      parameters = utils.ReadFile(parameters_file).splitlines()
2358
    except EnvironmentError, err:
2359
      return False, ("Error while reading the OS parameters file at %s: %s" %
2360
                     (parameters_file, utils.ErrnoOrStr(err)))
2361
    parameters = [v.split(None, 1) for v in parameters]
2362

    
2363
  os_obj = objects.OS(name=name, path=os_dir,
2364
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2365
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2366
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2367
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2368
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2369
                                                 None),
2370
                      supported_variants=variants,
2371
                      supported_parameters=parameters,
2372
                      api_versions=api_versions)
2373
  return True, os_obj
2374

    
2375

    
2376
def OSFromDisk(name, base_dir=None):
2377
  """Create an OS instance from disk.
2378

2379
  This function will return an OS instance if the given name is a
2380
  valid OS name. Otherwise, it will raise an appropriate
2381
  L{RPCFail} exception, detailing why this is not a valid OS.
2382

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

2386
  @type base_dir: string
2387
  @keyword base_dir: Base directory containing OS installations.
2388
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2389
  @rtype: L{objects.OS}
2390
  @return: the OS instance if we find a valid one
2391
  @raise RPCFail: if we don't find a valid OS
2392

2393
  """
2394
  name_only = objects.OS.GetName(name)
2395
  status, payload = _TryOSFromDisk(name_only, base_dir)
2396

    
2397
  if not status:
2398
    _Fail(payload)
2399

    
2400
  return payload
2401

    
2402

    
2403
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2404
  """Calculate the basic environment for an os script.
2405

2406
  @type os_name: str
2407
  @param os_name: full operating system name (including variant)
2408
  @type inst_os: L{objects.OS}
2409
  @param inst_os: operating system for which the environment is being built
2410
  @type os_params: dict
2411
  @param os_params: the OS parameters
2412
  @type debug: integer
2413
  @param debug: debug level (0 or 1, for OS Api 10)
2414
  @rtype: dict
2415
  @return: dict of environment variables
2416
  @raise errors.BlockDeviceError: if the block device
2417
      cannot be found
2418

2419
  """
2420
  result = {}
2421
  api_version = \
2422
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2423
  result["OS_API_VERSION"] = "%d" % api_version
2424
  result["OS_NAME"] = inst_os.name
2425
  result["DEBUG_LEVEL"] = "%d" % debug
2426

    
2427
  # OS variants
2428
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2429
    variant = objects.OS.GetVariant(os_name)
2430
    if not variant:
2431
      variant = inst_os.supported_variants[0]
2432
  else:
2433
    variant = ""
2434
  result["OS_VARIANT"] = variant
2435

    
2436
  # OS params
2437
  for pname, pvalue in os_params.items():
2438
    result["OSP_%s" % pname.upper()] = pvalue
2439

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

    
2445
  return result
2446

    
2447

    
2448
def OSEnvironment(instance, inst_os, debug=0):
2449
  """Calculate the environment for an os script.
2450

2451
  @type instance: L{objects.Instance}
2452
  @param instance: target instance for the os script run
2453
  @type inst_os: L{objects.OS}
2454
  @param inst_os: operating system for which the environment is being built
2455
  @type debug: integer
2456
  @param debug: debug level (0 or 1, for OS Api 10)
2457
  @rtype: dict
2458
  @return: dict of environment variables
2459
  @raise errors.BlockDeviceError: if the block device
2460
      cannot be found
2461

2462
  """
2463
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2464

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

    
2468
  result["HYPERVISOR"] = instance.hypervisor
2469
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2470
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2471
  result["INSTANCE_SECONDARY_NODES"] = \
2472
      ("%s" % " ".join(instance.secondary_nodes))
2473

    
2474
  # Disks
2475
  for idx, disk in enumerate(instance.disks):
2476
    real_disk = _OpenRealBD(disk)
2477
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2478
    result["DISK_%d_ACCESS" % idx] = disk.mode
2479
    if constants.HV_DISK_TYPE in instance.hvparams:
2480
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2481
        instance.hvparams[constants.HV_DISK_TYPE]
2482
    if disk.dev_type in constants.LDS_BLOCK:
2483
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2484
    elif disk.dev_type == constants.LD_FILE:
2485
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2486
        "file:%s" % disk.physical_id[0]
2487

    
2488
  # NICs
2489
  for idx, nic in enumerate(instance.nics):
2490
    result["NIC_%d_MAC" % idx] = nic.mac
2491
    if nic.ip:
2492
      result["NIC_%d_IP" % idx] = nic.ip
2493
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2494
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2495
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2496
    if nic.nicparams[constants.NIC_LINK]:
2497
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2498
    if nic.network:
2499
      result["NIC_%d_NETWORK" % idx] = nic.network
2500
    if constants.HV_NIC_TYPE in instance.hvparams:
2501
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2502
        instance.hvparams[constants.HV_NIC_TYPE]
2503

    
2504
  # HV/BE params
2505
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2506
    for key, value in source.items():
2507
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2508

    
2509
  return result
2510

    
2511

    
2512
def DiagnoseExtStorage(top_dirs=None):
2513
  """Compute the validity for all ExtStorage Providers.
2514

2515
  @type top_dirs: list
2516
  @param top_dirs: the list of directories in which to
2517
      search (if not given defaults to
2518
      L{pathutils.ES_SEARCH_PATH})
2519
  @rtype: list of L{objects.ExtStorage}
2520
  @return: a list of tuples (name, path, status, diagnose, parameters)
2521
      for all (potential) ExtStorage Providers under all
2522
      search paths, where:
2523
          - name is the (potential) ExtStorage Provider
2524
          - path is the full path to the ExtStorage Provider
2525
          - status True/False is the validity of the ExtStorage Provider
2526
          - diagnose is the error message for an invalid ExtStorage Provider,
2527
            otherwise empty
2528
          - parameters is a list of (name, help) parameters, if any
2529

2530
  """
2531
  if top_dirs is None:
2532
    top_dirs = pathutils.ES_SEARCH_PATH
2533

    
2534
  result = []
2535
  for dir_name in top_dirs:
2536
    if os.path.isdir(dir_name):
2537
      try:
2538
        f_names = utils.ListVisibleFiles(dir_name)
2539
      except EnvironmentError, err:
2540
        logging.exception("Can't list the ExtStorage directory %s: %s",
2541
                          dir_name, err)
2542
        break
2543
      for name in f_names:
2544
        es_path = utils.PathJoin(dir_name, name)
2545
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2546
        if status:
2547
          diagnose = ""
2548
          parameters = es_inst.supported_parameters
2549
        else:
2550
          diagnose = es_inst
2551
          parameters = []
2552
        result.append((name, es_path, status, diagnose, parameters))
2553

    
2554
  return result
2555

    
2556

    
2557
def BlockdevGrow(disk, amount, dryrun, backingstore):
2558
  """Grow a stack of block devices.
2559

2560
  This function is called recursively, with the childrens being the
2561
  first ones to resize.
2562

2563
  @type disk: L{objects.Disk}
2564
  @param disk: the disk to be grown
2565
  @type amount: integer
2566
  @param amount: the amount (in mebibytes) to grow with
2567
  @type dryrun: boolean
2568
  @param dryrun: whether to execute the operation in simulation mode
2569
      only, without actually increasing the size
2570
  @param backingstore: whether to execute the operation on backing storage
2571
      only, or on "logical" storage only; e.g. DRBD is logical storage,
2572
      whereas LVM, file, RBD are backing storage
2573
  @rtype: (status, result)
2574
  @return: a tuple with the status of the operation (True/False), and
2575
      the errors message if status is False
2576

2577
  """
2578
  r_dev = _RecursiveFindBD(disk)
2579
  if r_dev is None:
2580
    _Fail("Cannot find block device %s", disk)
2581

    
2582
  try:
2583
    r_dev.Grow(amount, dryrun, backingstore)
2584
  except errors.BlockDeviceError, err:
2585
    _Fail("Failed to grow block device: %s", err, exc=True)
2586

    
2587

    
2588
def BlockdevSnapshot(disk):
2589
  """Create a snapshot copy of a block device.
2590

2591
  This function is called recursively, and the snapshot is actually created
2592
  just for the leaf lvm backend device.
2593

2594
  @type disk: L{objects.Disk}
2595
  @param disk: the disk to be snapshotted
2596
  @rtype: string
2597
  @return: snapshot disk ID as (vg, lv)
2598

2599
  """
2600
  if disk.dev_type == constants.LD_DRBD8:
2601
    if not disk.children:
2602
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2603
            disk.unique_id)
2604
    return BlockdevSnapshot(disk.children[0])
2605
  elif disk.dev_type == constants.LD_LV:
2606
    r_dev = _RecursiveFindBD(disk)
2607
    if r_dev is not None:
2608
      # FIXME: choose a saner value for the snapshot size
2609
      # let's stay on the safe side and ask for the full size, for now
2610
      return r_dev.Snapshot(disk.size)
2611
    else:
2612
      _Fail("Cannot find block device %s", disk)
2613
  else:
2614
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2615
          disk.unique_id, disk.dev_type)
2616

    
2617

    
2618
def BlockdevSetInfo(disk, info):
2619
  """Sets 'metadata' information on block devices.
2620

2621
  This function sets 'info' metadata on block devices. Initial
2622
  information is set at device creation; this function should be used
2623
  for example after renames.
2624

2625
  @type disk: L{objects.Disk}
2626
  @param disk: the disk to be grown
2627
  @type info: string
2628
  @param info: new 'info' metadata
2629
  @rtype: (status, result)
2630
  @return: a tuple with the status of the operation (True/False), and
2631
      the errors message if status is False
2632

2633
  """
2634
  r_dev = _RecursiveFindBD(disk)
2635
  if r_dev is None:
2636
    _Fail("Cannot find block device %s", disk)
2637

    
2638
  try:
2639
    r_dev.SetInfo(info)
2640
  except errors.BlockDeviceError, err:
2641
    _Fail("Failed to set information on block device: %s", err, exc=True)
2642

    
2643

    
2644
def FinalizeExport(instance, snap_disks):
2645
  """Write out the export configuration information.
2646

2647
  @type instance: L{objects.Instance}
2648
  @param instance: the instance which we export, used for
2649
      saving configuration
2650
  @type snap_disks: list of L{objects.Disk}
2651
  @param snap_disks: list of snapshot block devices, which
2652
      will be used to get the actual name of the dump file
2653

2654
  @rtype: None
2655

2656
  """
2657
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
2658
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
2659

    
2660
  config = objects.SerializableConfigParser()
2661

    
2662
  config.add_section(constants.INISECT_EXP)
2663
  config.set(constants.INISECT_EXP, "version", "0")
2664
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2665
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2666
  config.set(constants.INISECT_EXP, "os", instance.os)
2667
  config.set(constants.INISECT_EXP, "compression", "none")
2668

    
2669
  config.add_section(constants.INISECT_INS)
2670
  config.set(constants.INISECT_INS, "name", instance.name)
2671
  config.set(constants.INISECT_INS, "maxmem", "%d" %
2672
             instance.beparams[constants.BE_MAXMEM])
2673
  config.set(constants.INISECT_INS, "minmem", "%d" %
2674
             instance.beparams[constants.BE_MINMEM])
2675
  # "memory" is deprecated, but useful for exporting to old ganeti versions
2676
  config.set(constants.INISECT_INS, "memory", "%d" %
2677
             instance.beparams[constants.BE_MAXMEM])
2678
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2679
             instance.beparams[constants.BE_VCPUS])
2680
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2681
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2682
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2683

    
2684
  nic_total = 0
2685
  for nic_count, nic in enumerate(instance.nics):
2686
    nic_total += 1
2687
    config.set(constants.INISECT_INS, "nic%d_mac" %
2688
               nic_count, "%s" % nic.mac)
2689
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2690
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
2691
               "%s" % nic.network)
2692
    for param in constants.NICS_PARAMETER_TYPES:
2693
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2694
                 "%s" % nic.nicparams.get(param, None))
2695
  # TODO: redundant: on load can read nics until it doesn't exist
2696
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2697

    
2698
  disk_total = 0
2699
  for disk_count, disk in enumerate(snap_disks):
2700
    if disk:
2701
      disk_total += 1
2702
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2703
                 ("%s" % disk.iv_name))
2704
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2705
                 ("%s" % disk.physical_id[1]))
2706
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2707
                 ("%d" % disk.size))
2708

    
2709
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2710

    
2711
  # New-style hypervisor/backend parameters
2712

    
2713
  config.add_section(constants.INISECT_HYP)
2714
  for name, value in instance.hvparams.items():
2715
    if name not in constants.HVC_GLOBALS:
2716
      config.set(constants.INISECT_HYP, name, str(value))
2717

    
2718
  config.add_section(constants.INISECT_BEP)
2719
  for name, value in instance.beparams.items():
2720
    config.set(constants.INISECT_BEP, name, str(value))
2721

    
2722
  config.add_section(constants.INISECT_OSP)
2723
  for name, value in instance.osparams.items():
2724
    config.set(constants.INISECT_OSP, name, str(value))
2725

    
2726
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2727
                  data=config.Dumps())
2728
  shutil.rmtree(finaldestdir, ignore_errors=True)
2729
  shutil.move(destdir, finaldestdir)
2730

    
2731

    
2732
def ExportInfo(dest):
2733
  """Get export configuration information.
2734

2735
  @type dest: str
2736
  @param dest: directory containing the export
2737

2738
  @rtype: L{objects.SerializableConfigParser}
2739
  @return: a serializable config file containing the
2740
      export info
2741

2742
  """
2743
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2744

    
2745
  config = objects.SerializableConfigParser()
2746
  config.read(cff)
2747

    
2748
  if (not config.has_section(constants.INISECT_EXP) or
2749
      not config.has_section(constants.INISECT_INS)):
2750
    _Fail("Export info file doesn't have the required fields")
2751

    
2752
  return config.Dumps()
2753

    
2754

    
2755
def ListExports():
2756
  """Return a list of exports currently available on this machine.
2757

2758
  @rtype: list
2759
  @return: list of the exports
2760

2761
  """
2762
  if os.path.isdir(pathutils.EXPORT_DIR):
2763
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
2764
  else:
2765
    _Fail("No exports directory")
2766

    
2767

    
2768
def RemoveExport(export):
2769
  """Remove an existing export from the node.
2770

2771
  @type export: str
2772
  @param export: the name of the export to remove
2773
  @rtype: None
2774

2775
  """
2776
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
2777

    
2778
  try:
2779
    shutil.rmtree(target)
2780
  except EnvironmentError, err:
2781
    _Fail("Error while removing the export: %s", err, exc=True)
2782

    
2783

    
2784
def BlockdevRename(devlist):
2785
  """Rename a list of block devices.
2786

2787
  @type devlist: list of tuples
2788
  @param devlist: list of tuples of the form  (disk,
2789
      new_logical_id, new_physical_id); disk is an
2790
      L{objects.Disk} object describing the current disk,
2791
      and new logical_id/physical_id is the name we
2792
      rename it to
2793
  @rtype: boolean
2794
  @return: True if all renames succeeded, False otherwise
2795

2796
  """
2797
  msgs = []
2798
  result = True
2799
  for disk, unique_id in devlist:
2800
    dev = _RecursiveFindBD(disk)
2801
    if dev is None:
2802
      msgs.append("Can't find device %s in rename" % str(disk))
2803
      result = False
2804
      continue
2805
    try:
2806
      old_rpath = dev.dev_path
2807
      dev.Rename(unique_id)
2808
      new_rpath = dev.dev_path
2809
      if old_rpath != new_rpath:
2810
        DevCacheManager.RemoveCache(old_rpath)
2811
        # FIXME: we should add the new cache information here, like:
2812
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2813
        # but we don't have the owner here - maybe parse from existing
2814
        # cache? for now, we only lose lvm data when we rename, which
2815
        # is less critical than DRBD or MD
2816
    except errors.BlockDeviceError, err:
2817
      msgs.append("Can't rename device '%s' to '%s': %s" %
2818
                  (dev, unique_id, err))
2819
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2820
      result = False
2821
  if not result:
2822
    _Fail("; ".join(msgs))
2823

    
2824

    
2825
def _TransformFileStorageDir(fs_dir):
2826
  """Checks whether given file_storage_dir is valid.
2827

2828
  Checks wheter the given fs_dir is within the cluster-wide default
2829
  file_storage_dir or the shared_file_storage_dir, which are stored in
2830
  SimpleStore. Only paths under those directories are allowed.
2831

2832
  @type fs_dir: str
2833
  @param fs_dir: the path to check
2834

2835
  @return: the normalized path if valid, None otherwise
2836

2837
  """
2838
  if not (constants.ENABLE_FILE_STORAGE or
2839
          constants.ENABLE_SHARED_FILE_STORAGE):
2840
    _Fail("File storage disabled at configure time")
2841

    
2842
  bdev.CheckFileStoragePath(fs_dir)
2843

    
2844
  return os.path.normpath(fs_dir)
2845

    
2846

    
2847
def CreateFileStorageDir(file_storage_dir):
2848
  """Create file storage directory.
2849

2850
  @type file_storage_dir: str
2851
  @param file_storage_dir: directory to create
2852

2853
  @rtype: tuple
2854
  @return: tuple with first element a boolean indicating wheter dir
2855
      creation was successful or not
2856

2857
  """
2858
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2859
  if os.path.exists(file_storage_dir):
2860
    if not os.path.isdir(file_storage_dir):
2861
      _Fail("Specified storage dir '%s' is not a directory",
2862
            file_storage_dir)
2863
  else:
2864
    try:
2865
      os.makedirs(file_storage_dir, 0750)
2866
    except OSError, err:
2867
      _Fail("Cannot create file storage directory '%s': %s",
2868
            file_storage_dir, err, exc=True)
2869

    
2870

    
2871
def RemoveFileStorageDir(file_storage_dir):
2872
  """Remove file storage directory.
2873

2874
  Remove it only if it's empty. If not log an error and return.
2875

2876
  @type file_storage_dir: str
2877
  @param file_storage_dir: the directory we should cleanup
2878
  @rtype: tuple (success,)
2879
  @return: tuple of one element, C{success}, denoting
2880
      whether the operation was successful
2881

2882
  """
2883
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2884
  if os.path.exists(file_storage_dir):
2885
    if not os.path.isdir(file_storage_dir):
2886
      _Fail("Specified Storage directory '%s' is not a directory",
2887
            file_storage_dir)
2888
    # deletes dir only if empty, otherwise we want to fail the rpc call
2889
    try:
2890
      os.rmdir(file_storage_dir)
2891
    except OSError, err:
2892
      _Fail("Cannot remove file storage directory '%s': %s",
2893
            file_storage_dir, err)
2894

    
2895

    
2896
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2897
  """Rename the file storage directory.
2898

2899
  @type old_file_storage_dir: str
2900
  @param old_file_storage_dir: the current path
2901
  @type new_file_storage_dir: str
2902
  @param new_file_storage_dir: the name we should rename to
2903
  @rtype: tuple (success,)
2904
  @return: tuple of one element, C{success}, denoting
2905
      whether the operation was successful
2906

2907
  """
2908
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2909
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2910
  if not os.path.exists(new_file_storage_dir):
2911
    if os.path.isdir(old_file_storage_dir):
2912
      try:
2913
        os.rename(old_file_storage_dir, new_file_storage_dir)
2914
      except OSError, err:
2915
        _Fail("Cannot rename '%s' to '%s': %s",
2916
              old_file_storage_dir, new_file_storage_dir, err)
2917
    else:
2918
      _Fail("Specified storage dir '%s' is not a directory",
2919
            old_file_storage_dir)
2920
  else:
2921
    if os.path.exists(old_file_storage_dir):
2922
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2923
            old_file_storage_dir, new_file_storage_dir)
2924

    
2925

    
2926
def _EnsureJobQueueFile(file_name):
2927
  """Checks whether the given filename is in the queue directory.
2928

2929
  @type file_name: str
2930
  @param file_name: the file name we should check
2931
  @rtype: None
2932
  @raises RPCFail: if the file is not valid
2933

2934
  """
2935
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
2936
    _Fail("Passed job queue file '%s' does not belong to"
2937
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
2938

    
2939

    
2940
def JobQueueUpdate(file_name, content):
2941
  """Updates a file in the queue directory.
2942

2943
  This is just a wrapper over L{utils.io.WriteFile}, with proper
2944
  checking.
2945

2946
  @type file_name: str
2947
  @param file_name: the job file name
2948
  @type content: str
2949
  @param content: the new job contents
2950
  @rtype: boolean
2951
  @return: the success of the operation
2952

2953
  """
2954
  file_name = vcluster.LocalizeVirtualPath(file_name)
2955

    
2956
  _EnsureJobQueueFile(file_name)
2957
  getents = runtime.GetEnts()
2958

    
2959
  # Write and replace the file atomically
2960
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
2961
                  gid=getents.masterd_gid)
2962

    
2963

    
2964
def JobQueueRename(old, new):
2965
  """Renames a job queue file.
2966

2967
  This is just a wrapper over os.rename with proper checking.
2968

2969
  @type old: str
2970
  @param old: the old (actual) file name
2971
  @type new: str
2972
  @param new: the desired file name
2973
  @rtype: tuple
2974
  @return: the success of the operation and payload
2975

2976
  """
2977
  old = vcluster.LocalizeVirtualPath(old)
2978
  new = vcluster.LocalizeVirtualPath(new)
2979

    
2980
  _EnsureJobQueueFile(old)
2981
  _EnsureJobQueueFile(new)
2982

    
2983
  getents = runtime.GetEnts()
2984

    
2985
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0700,
2986
                   dir_uid=getents.masterd_uid, dir_gid=getents.masterd_gid)
2987

    
2988

    
2989
def BlockdevClose(instance_name, disks):
2990
  """Closes the given block devices.
2991

2992
  This means they will be switched to secondary mode (in case of
2993
  DRBD).
2994

2995
  @param instance_name: if the argument is not empty, the symlinks
2996
      of this instance will be removed
2997
  @type disks: list of L{objects.Disk}
2998
  @param disks: the list of disks to be closed
2999
  @rtype: tuple (success, message)
3000
  @return: a tuple of success and message, where success
3001
      indicates the succes of the operation, and message
3002
      which will contain the error details in case we
3003
      failed
3004

3005
  """
3006
  bdevs = []
3007
  for cf in disks:
3008
    rd = _RecursiveFindBD(cf)
3009
    if rd is None:
3010
      _Fail("Can't find device %s", cf)
3011
    bdevs.append(rd)
3012

    
3013
  msg = []
3014
  for rd in bdevs:
3015
    try:
3016
      rd.Close()
3017
    except errors.BlockDeviceError, err:
3018
      msg.append(str(err))
3019
  if msg:
3020
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3021
  else:
3022
    if instance_name:
3023
      _RemoveBlockDevLinks(instance_name, disks)
3024

    
3025

    
3026
def ValidateHVParams(hvname, hvparams):
3027
  """Validates the given hypervisor parameters.
3028

3029
  @type hvname: string
3030
  @param hvname: the hypervisor name
3031
  @type hvparams: dict
3032
  @param hvparams: the hypervisor parameters to be validated
3033
  @rtype: None
3034

3035
  """
3036
  try:
3037
    hv_type = hypervisor.GetHypervisor(hvname)
3038
    hv_type.ValidateParameters(hvparams)
3039
  except errors.HypervisorError, err:
3040
    _Fail(str(err), log=False)
3041

    
3042

    
3043
def _CheckOSPList(os_obj, parameters):
3044
  """Check whether a list of parameters is supported by the OS.
3045

3046
  @type os_obj: L{objects.OS}
3047
  @param os_obj: OS object to check
3048
  @type parameters: list
3049
  @param parameters: the list of parameters to check
3050

3051
  """
3052
  supported = [v[0] for v in os_obj.supported_parameters]
3053
  delta = frozenset(parameters).difference(supported)
3054
  if delta:
3055
    _Fail("The following parameters are not supported"
3056
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3057

    
3058

    
3059
def ValidateOS(required, osname, checks, osparams):
3060
  """Validate the given OS' parameters.
3061

3062
  @type required: boolean
3063
  @param required: whether absence of the OS should translate into
3064
      failure or not
3065
  @type osname: string
3066
  @param osname: the OS to be validated
3067
  @type checks: list
3068
  @param checks: list of the checks to run (currently only 'parameters')
3069
  @type osparams: dict
3070
  @param osparams: dictionary with OS parameters
3071
  @rtype: boolean
3072
  @return: True if the validation passed, or False if the OS was not
3073
      found and L{required} was false
3074

3075
  """
3076
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3077
    _Fail("Unknown checks required for OS %s: %s", osname,
3078
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3079

    
3080
  name_only = objects.OS.GetName(osname)
3081
  status, tbv = _TryOSFromDisk(name_only, None)
3082

    
3083
  if not status:
3084
    if required:
3085
      _Fail(tbv)
3086
    else:
3087
      return False
3088

    
3089
  if max(tbv.api_versions) < constants.OS_API_V20:
3090
    return True
3091

    
3092
  if constants.OS_VALIDATE_PARAMETERS in checks:
3093
    _CheckOSPList(tbv, osparams.keys())
3094

    
3095
  validate_env = OSCoreEnv(osname, tbv, osparams)
3096
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3097
                        cwd=tbv.path, reset_env=True)
3098
  if result.failed:
3099
    logging.error("os validate command '%s' returned error: %s output: %s",
3100
                  result.cmd, result.fail_reason, result.output)
3101
    _Fail("OS validation script failed (%s), output: %s",
3102
          result.fail_reason, result.output, log=False)
3103

    
3104
  return True
3105

    
3106

    
3107
def DemoteFromMC():
3108
  """Demotes the current node from master candidate role.
3109

3110
  """
3111
  # try to ensure we're not the master by mistake
3112
  master, myself = ssconf.GetMasterAndMyself()
3113
  if master == myself:
3114
    _Fail("ssconf status shows I'm the master node, will not demote")
3115

    
3116
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3117
  if not result.failed:
3118
    _Fail("The master daemon is running, will not demote")
3119

    
3120
  try:
3121
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3122
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3123
  except EnvironmentError, err:
3124
    if err.errno != errno.ENOENT:
3125
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3126

    
3127
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3128

    
3129

    
3130
def _GetX509Filenames(cryptodir, name):
3131
  """Returns the full paths for the private key and certificate.
3132

3133
  """
3134
  return (utils.PathJoin(cryptodir, name),
3135
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3136
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3137

    
3138

    
3139
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3140
  """Creates a new X509 certificate for SSL/TLS.
3141

3142
  @type validity: int
3143
  @param validity: Validity in seconds
3144
  @rtype: tuple; (string, string)
3145
  @return: Certificate name and public part
3146

3147
  """
3148
  (key_pem, cert_pem) = \
3149
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3150
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3151

    
3152
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3153
                              prefix="x509-%s-" % utils.TimestampForFilename())
3154
  try:
3155
    name = os.path.basename(cert_dir)
3156
    assert len(name) > 5
3157

    
3158
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3159

    
3160
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3161
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3162

    
3163
    # Never return private key as it shouldn't leave the node
3164
    return (name, cert_pem)
3165
  except Exception:
3166
    shutil.rmtree(cert_dir, ignore_errors=True)
3167
    raise
3168

    
3169

    
3170
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3171
  """Removes a X509 certificate.
3172

3173
  @type name: string
3174
  @param name: Certificate name
3175

3176
  """
3177
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3178

    
3179
  utils.RemoveFile(key_file)
3180
  utils.RemoveFile(cert_file)
3181

    
3182
  try:
3183
    os.rmdir(cert_dir)
3184
  except EnvironmentError, err:
3185
    _Fail("Cannot remove certificate directory '%s': %s",
3186
          cert_dir, err)
3187

    
3188

    
3189
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3190
  """Returns the command for the requested input/output.
3191

3192
  @type instance: L{objects.Instance}
3193
  @param instance: The instance object
3194
  @param mode: Import/export mode
3195
  @param ieio: Input/output type
3196
  @param ieargs: Input/output arguments
3197

3198
  """
3199
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3200

    
3201
  env = None
3202
  prefix = None
3203
  suffix = None
3204
  exp_size = None
3205

    
3206
  if ieio == constants.IEIO_FILE:
3207
    (filename, ) = ieargs
3208

    
3209
    if not utils.IsNormAbsPath(filename):
3210
      _Fail("Path '%s' is not normalized or absolute", filename)
3211

    
3212
    real_filename = os.path.realpath(filename)
3213
    directory = os.path.dirname(real_filename)
3214

    
3215
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3216
      _Fail("File '%s' is not under exports directory '%s': %s",
3217
            filename, pathutils.EXPORT_DIR, real_filename)
3218

    
3219
    # Create directory
3220
    utils.Makedirs(directory, mode=0750)
3221

    
3222
    quoted_filename = utils.ShellQuote(filename)
3223

    
3224
    if mode == constants.IEM_IMPORT:
3225
      suffix = "> %s" % quoted_filename
3226
    elif mode == constants.IEM_EXPORT:
3227
      suffix = "< %s" % quoted_filename
3228

    
3229
      # Retrieve file size
3230
      try:
3231
        st = os.stat(filename)
3232
      except EnvironmentError, err:
3233
        logging.error("Can't stat(2) %s: %s", filename, err)
3234
      else:
3235
        exp_size = utils.BytesToMebibyte(st.st_size)
3236

    
3237
  elif ieio == constants.IEIO_RAW_DISK:
3238
    (disk, ) = ieargs
3239

    
3240
    real_disk = _OpenRealBD(disk)
3241

    
3242
    if mode == constants.IEM_IMPORT:
3243
      # we set here a smaller block size as, due to transport buffering, more
3244
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3245
      # is not already there or we pass a wrong path; we use notrunc to no
3246
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3247
      # much memory; this means that at best, we flush every 64k, which will
3248
      # not be very fast
3249
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3250
                                    " bs=%s oflag=dsync"),
3251
                                    real_disk.dev_path,
3252
                                    str(64 * 1024))
3253

    
3254
    elif mode == constants.IEM_EXPORT:
3255
      # the block size on the read dd is 1MiB to match our units
3256
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3257
                                   real_disk.dev_path,
3258
                                   str(1024 * 1024), # 1 MB
3259
                                   str(disk.size))
3260
      exp_size = disk.size
3261

    
3262
  elif ieio == constants.IEIO_SCRIPT:
3263
    (disk, disk_index, ) = ieargs
3264

    
3265
    assert isinstance(disk_index, (int, long))
3266

    
3267
    real_disk = _OpenRealBD(disk)
3268

    
3269
    inst_os = OSFromDisk(instance.os)
3270
    env = OSEnvironment(instance, inst_os)
3271

    
3272
    if mode == constants.IEM_IMPORT:
3273
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3274
      env["IMPORT_INDEX"] = str(disk_index)
3275
      script = inst_os.import_script
3276

    
3277
    elif mode == constants.IEM_EXPORT:
3278
      env["EXPORT_DEVICE"] = real_disk.dev_path
3279
      env["EXPORT_INDEX"] = str(disk_index)
3280
      script = inst_os.export_script
3281

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

    
3285
    if mode == constants.IEM_IMPORT:
3286
      suffix = "| %s" % script_cmd
3287

    
3288
    elif mode == constants.IEM_EXPORT:
3289
      prefix = "%s |" % script_cmd
3290

    
3291
    # Let script predict size
3292
    exp_size = constants.IE_CUSTOM_SIZE
3293

    
3294
  else:
3295
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3296

    
3297
  return (env, prefix, suffix, exp_size)
3298

    
3299

    
3300
def _CreateImportExportStatusDir(prefix):
3301
  """Creates status directory for import/export.
3302

3303
  """
3304
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3305
                          prefix=("%s-%s-" %
3306
                                  (prefix, utils.TimestampForFilename())))
3307

    
3308

    
3309
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3310
                            ieio, ieioargs):
3311
  """Starts an import or export daemon.
3312

3313
  @param mode: Import/output mode
3314
  @type opts: L{objects.ImportExportOptions}
3315
  @param opts: Daemon options
3316
  @type host: string
3317
  @param host: Remote host for export (None for import)
3318
  @type port: int
3319
  @param port: Remote port for export (None for import)
3320
  @type instance: L{objects.Instance}
3321
  @param instance: Instance object
3322
  @type component: string
3323
  @param component: which part of the instance is transferred now,
3324
      e.g. 'disk/0'
3325
  @param ieio: Input/output type
3326
  @param ieioargs: Input/output arguments
3327

3328
  """
3329
  if mode == constants.IEM_IMPORT:
3330
    prefix = "import"
3331

    
3332
    if not (host is None and port is None):
3333
      _Fail("Can not specify host or port on import")
3334

    
3335
  elif mode == constants.IEM_EXPORT:
3336
    prefix = "export"
3337

    
3338
    if host is None or port is None:
3339
      _Fail("Host and port must be specified for an export")
3340

    
3341
  else:
3342
    _Fail("Invalid mode %r", mode)
3343

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

    
3347
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3348
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3349

    
3350
  if opts.key_name is None:
3351
    # Use server.pem
3352
    key_path = pathutils.NODED_CERT_FILE
3353
    cert_path = pathutils.NODED_CERT_FILE
3354
    assert opts.ca_pem is None
3355
  else:
3356
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3357
                                                 opts.key_name)
3358
    assert opts.ca_pem is not None
3359

    
3360
  for i in [key_path, cert_path]:
3361
    if not os.path.exists(i):
3362
      _Fail("File '%s' does not exist" % i)
3363

    
3364
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3365
  try:
3366
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3367
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3368
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3369

    
3370
    if opts.ca_pem is None:
3371
      # Use server.pem
3372
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3373
    else:
3374
      ca = opts.ca_pem
3375

    
3376
    # Write CA file
3377
    utils.WriteFile(ca_file, data=ca, mode=0400)
3378

    
3379
    cmd = [
3380
      pathutils.IMPORT_EXPORT_DAEMON,
3381
      status_file, mode,
3382
      "--key=%s" % key_path,
3383
      "--cert=%s" % cert_path,
3384
      "--ca=%s" % ca_file,
3385
      ]
3386

    
3387
    if host:
3388
      cmd.append("--host=%s" % host)
3389

    
3390
    if port:
3391
      cmd.append("--port=%s" % port)
3392

    
3393
    if opts.ipv6:
3394
      cmd.append("--ipv6")
3395
    else:
3396
      cmd.append("--ipv4")
3397

    
3398
    if opts.compress:
3399
      cmd.append("--compress=%s" % opts.compress)
3400

    
3401
    if opts.magic:
3402
      cmd.append("--magic=%s" % opts.magic)
3403

    
3404
    if exp_size is not None:
3405
      cmd.append("--expected-size=%s" % exp_size)
3406

    
3407
    if cmd_prefix:
3408
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3409

    
3410
    if cmd_suffix:
3411
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3412

    
3413
    if mode == constants.IEM_EXPORT:
3414
      # Retry connection a few times when connecting to remote peer
3415
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3416
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3417
    elif opts.connect_timeout is not None:
3418
      assert mode == constants.IEM_IMPORT
3419
      # Overall timeout for establishing connection while listening
3420
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3421

    
3422
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3423

    
3424
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3425
    # support for receiving a file descriptor for output
3426
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3427
                      output=logfile)
3428

    
3429
    # The import/export name is simply the status directory name
3430
    return os.path.basename(status_dir)
3431

    
3432
  except Exception:
3433
    shutil.rmtree(status_dir, ignore_errors=True)
3434
    raise
3435

    
3436

    
3437
def GetImportExportStatus(names):
3438
  """Returns import/export daemon status.
3439

3440
  @type names: sequence
3441
  @param names: List of names
3442
  @rtype: List of dicts
3443
  @return: Returns a list of the state of each named import/export or None if a
3444
           status couldn't be read
3445

3446
  """
3447
  result = []
3448

    
3449
  for name in names:
3450
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3451
                                 _IES_STATUS_FILE)
3452

    
3453
    try:
3454
      data = utils.ReadFile(status_file)
3455
    except EnvironmentError, err:
3456
      if err.errno != errno.ENOENT:
3457
        raise
3458
      data = None
3459

    
3460
    if not data:
3461
      result.append(None)
3462
      continue
3463

    
3464
    result.append(serializer.LoadJson(data))
3465

    
3466
  return result
3467

    
3468

    
3469
def AbortImportExport(name):
3470
  """Sends SIGTERM to a running import/export daemon.
3471

3472
  """
3473
  logging.info("Abort import/export %s", name)
3474

    
3475
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3476
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3477

    
3478
  if pid:
3479
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3480
                 name, pid)
3481
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3482

    
3483

    
3484
def CleanupImportExport(name):
3485
  """Cleanup after an import or export.
3486

3487
  If the import/export daemon is still running it's killed. Afterwards the
3488
  whole status directory is removed.
3489

3490
  """
3491
  logging.info("Finalizing import/export %s", name)
3492

    
3493
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3494

    
3495
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3496

    
3497
  if pid:
3498
    logging.info("Import/export %s is still running with PID %s",
3499
                 name, pid)
3500
    utils.KillProcess(pid, waitpid=False)
3501

    
3502
  shutil.rmtree(status_dir, ignore_errors=True)
3503

    
3504

    
3505
def _FindDisks(nodes_ip, disks):
3506
  """Sets the physical ID on disks and returns the block devices.
3507

3508
  """
3509
  # set the correct physical ID
3510
  my_name = netutils.Hostname.GetSysName()
3511
  for cf in disks:
3512
    cf.SetPhysicalID(my_name, nodes_ip)
3513

    
3514
  bdevs = []
3515

    
3516
  for cf in disks:
3517
    rd = _RecursiveFindBD(cf)
3518
    if rd is None:
3519
      _Fail("Can't find device %s", cf)
3520
    bdevs.append(rd)
3521
  return bdevs
3522

    
3523

    
3524
def DrbdDisconnectNet(nodes_ip, disks):
3525
  """Disconnects the network on a list of drbd devices.
3526

3527
  """
3528
  bdevs = _FindDisks(nodes_ip, disks)
3529

    
3530
  # disconnect disks
3531
  for rd in bdevs:
3532
    try:
3533
      rd.DisconnectNet()
3534
    except errors.BlockDeviceError, err:
3535
      _Fail("Can't change network configuration to standalone mode: %s",
3536
            err, exc=True)
3537

    
3538

    
3539
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3540
  """Attaches the network on a list of drbd devices.
3541

3542
  """
3543
  bdevs = _FindDisks(nodes_ip, disks)
3544

    
3545
  if multimaster:
3546
    for idx, rd in enumerate(bdevs):
3547
      try:
3548
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3549
      except EnvironmentError, err:
3550
        _Fail("Can't create symlink: %s", err)
3551
  # reconnect disks, switch to new master configuration and if
3552
  # needed primary mode
3553
  for rd in bdevs:
3554
    try:
3555
      rd.AttachNet(multimaster)
3556
    except errors.BlockDeviceError, err:
3557
      _Fail("Can't change network configuration: %s", err)
3558

    
3559
  # wait until the disks are connected; we need to retry the re-attach
3560
  # if the device becomes standalone, as this might happen if the one
3561
  # node disconnects and reconnects in a different mode before the
3562
  # other node reconnects; in this case, one or both of the nodes will
3563
  # decide it has wrong configuration and switch to standalone
3564

    
3565
  def _Attach():
3566
    all_connected = True
3567

    
3568
    for rd in bdevs:
3569
      stats = rd.GetProcStatus()
3570

    
3571
      all_connected = (all_connected and
3572
                       (stats.is_connected or stats.is_in_resync))
3573

    
3574
      if stats.is_standalone:
3575
        # peer had different config info and this node became
3576
        # standalone, even though this should not happen with the
3577
        # new staged way of changing disk configs
3578
        try:
3579
          rd.AttachNet(multimaster)
3580
        except errors.BlockDeviceError, err:
3581
          _Fail("Can't change network configuration: %s", err)
3582

    
3583
    if not all_connected:
3584
      raise utils.RetryAgain()
3585

    
3586
  try:
3587
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3588
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3589
  except utils.RetryTimeout:
3590
    _Fail("Timeout in disk reconnecting")
3591

    
3592
  if multimaster:
3593
    # change to primary mode
3594
    for rd in bdevs:
3595
      try:
3596
        rd.Open()
3597
      except errors.BlockDeviceError, err:
3598
        _Fail("Can't change to primary mode: %s", err)
3599

    
3600

    
3601
def DrbdWaitSync(nodes_ip, disks):
3602
  """Wait until DRBDs have synchronized.
3603

3604
  """
3605
  def _helper(rd):
3606
    stats = rd.GetProcStatus()
3607
    if not (stats.is_connected or stats.is_in_resync):
3608
      raise utils.RetryAgain()
3609
    return stats
3610

    
3611
  bdevs = _FindDisks(nodes_ip, disks)
3612

    
3613
  min_resync = 100
3614
  alldone = True
3615
  for rd in bdevs:
3616
    try:
3617
      # poll each second for 15 seconds
3618
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3619
    except utils.RetryTimeout:
3620
      stats = rd.GetProcStatus()
3621
      # last check
3622
      if not (stats.is_connected or stats.is_in_resync):
3623
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3624
    alldone = alldone and (not stats.is_in_resync)
3625
    if stats.sync_percent is not None:
3626
      min_resync = min(min_resync, stats.sync_percent)
3627

    
3628
  return (alldone, min_resync)
3629

    
3630

    
3631
def GetDrbdUsermodeHelper():
3632
  """Returns DRBD usermode helper currently configured.
3633

3634
  """
3635
  try:
3636
    return bdev.BaseDRBD.GetUsermodeHelper()
3637
  except errors.BlockDeviceError, err:
3638
    _Fail(str(err))
3639

    
3640

    
3641
def PowercycleNode(hypervisor_type):
3642
  """Hard-powercycle the node.
3643

3644
  Because we need to return first, and schedule the powercycle in the
3645
  background, we won't be able to report failures nicely.
3646

3647
  """
3648
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3649
  try:
3650
    pid = os.fork()
3651
  except OSError:
3652
    # if we can't fork, we'll pretend that we're in the child process
3653
    pid = 0
3654
  if pid > 0:
3655
    return "Reboot scheduled in 5 seconds"
3656
  # ensure the child is running on ram
3657
  try:
3658
    utils.Mlockall()
3659
  except Exception: # pylint: disable=W0703
3660
    pass
3661
  time.sleep(5)
3662
  hyper.PowercycleNode()
3663

    
3664

    
3665
def _VerifyRestrictedCmdName(cmd):
3666
  """Verifies a remote command name.
3667

3668
  @type cmd: string
3669
  @param cmd: Command name
3670
  @rtype: tuple; (boolean, string or None)
3671
  @return: The tuple's first element is the status; if C{False}, the second
3672
    element is an error message string, otherwise it's C{None}
3673

3674
  """
3675
  if not cmd.strip():
3676
    return (False, "Missing command name")
3677

    
3678
  if os.path.basename(cmd) != cmd:
3679
    return (False, "Invalid command name")
3680

    
3681
  if not constants.EXT_PLUGIN_MASK.match(cmd):
3682
    return (False, "Command name contains forbidden characters")
3683

    
3684
  return (True, None)
3685

    
3686

    
3687
def _CommonRestrictedCmdCheck(path, owner):
3688
  """Common checks for remote command file system directories and files.
3689

3690
  @type path: string
3691
  @param path: Path to check
3692
  @param owner: C{None} or tuple containing UID and GID
3693
  @rtype: tuple; (boolean, string or C{os.stat} result)
3694
  @return: The tuple's first element is the status; if C{False}, the second
3695
    element is an error message string, otherwise it's the result of C{os.stat}
3696

3697
  """
3698
  if owner is None:
3699
    # Default to root as owner
3700
    owner = (0, 0)
3701

    
3702
  try:
3703
    st = os.stat(path)
3704
  except EnvironmentError, err:
3705
    return (False, "Can't stat(2) '%s': %s" % (path, err))
3706

    
3707
  if stat.S_IMODE(st.st_mode) & (~_RCMD_MAX_MODE):
3708
    return (False, "Permissions on '%s' are too permissive" % path)
3709

    
3710
  if (st.st_uid, st.st_gid) != owner:
3711
    (owner_uid, owner_gid) = owner
3712
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
3713

    
3714
  return (True, st)
3715

    
3716

    
3717
def _VerifyRestrictedCmdDirectory(path, _owner=None):
3718
  """Verifies remote command directory.
3719

3720
  @type path: string
3721
  @param path: Path to check
3722
  @rtype: tuple; (boolean, string or None)
3723
  @return: The tuple's first element is the status; if C{False}, the second
3724
    element is an error message string, otherwise it's C{None}
3725

3726
  """
3727
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
3728

    
3729
  if not status:
3730
    return (False, value)
3731

    
3732
  if not stat.S_ISDIR(value.st_mode):
3733
    return (False, "Path '%s' is not a directory" % path)
3734

    
3735
  return (True, None)
3736

    
3737

    
3738
def _VerifyRestrictedCmd(path, cmd, _owner=None):
3739
  """Verifies a whole remote command and returns its executable filename.
3740

3741
  @type path: string
3742
  @param path: Directory containing remote commands
3743
  @type cmd: string
3744
  @param cmd: Command name
3745
  @rtype: tuple; (boolean, string)
3746
  @return: The tuple's first element is the status; if C{False}, the second
3747
    element is an error message string, otherwise the second element is the
3748
    absolute path to the executable
3749

3750
  """
3751
  executable = utils.PathJoin(path, cmd)
3752

    
3753
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
3754

    
3755
  if not status:
3756
    return (False, msg)
3757

    
3758
  if not utils.IsExecutable(executable):
3759
    return (False, "access(2) thinks '%s' can't be executed" % executable)
3760

    
3761
  return (True, executable)
3762

    
3763

    
3764
def _PrepareRestrictedCmd(path, cmd,
3765
                          _verify_dir=_VerifyRestrictedCmdDirectory,
3766
                          _verify_name=_VerifyRestrictedCmdName,
3767
                          _verify_cmd=_VerifyRestrictedCmd):
3768
  """Performs a number of tests on a remote command.
3769

3770
  @type path: string
3771
  @param path: Directory containing remote commands
3772
  @type cmd: string
3773
  @param cmd: Command name
3774
  @return: Same as L{_VerifyRestrictedCmd}
3775

3776
  """
3777
  # Verify the directory first
3778
  (status, msg) = _verify_dir(path)
3779
  if status:
3780
    # Check command if everything was alright
3781
    (status, msg) = _verify_name(cmd)
3782

    
3783
  if not status:
3784
    return (False, msg)
3785

    
3786
  # Check actual executable
3787
  return _verify_cmd(path, cmd)
3788

    
3789

    
3790
def RunRestrictedCmd(cmd,
3791
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
3792
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
3793
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
3794
                     _sleep_fn=time.sleep,
3795
                     _prepare_fn=_PrepareRestrictedCmd,
3796
                     _runcmd_fn=utils.RunCmd,
3797
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
3798
  """Executes a remote command after performing strict tests.
3799

3800
  @type cmd: string
3801
  @param cmd: Command name
3802
  @rtype: string
3803
  @return: Command output
3804
  @raise RPCFail: In case of an error
3805

3806
  """
3807
  logging.info("Preparing to run remote command '%s'", cmd)
3808

    
3809
  if not _enabled:
3810
    _Fail("Remote commands disabled at configure time")
3811

    
3812
  lock = None
3813
  try:
3814
    cmdresult = None
3815
    try:
3816
      lock = utils.FileLock.Open(_lock_file)
3817
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
3818

    
3819
      (status, value) = _prepare_fn(_path, cmd)
3820

    
3821
      if status:
3822
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
3823
                               postfork_fn=lambda _: lock.Unlock())
3824
      else:
3825
        logging.error(value)
3826
    except Exception: # pylint: disable=W0703
3827
      # Keep original error in log
3828
      logging.exception("Caught exception")
3829

    
3830
    if cmdresult is None:
3831
      logging.info("Sleeping for %0.1f seconds before returning",
3832
                   _RCMD_INVALID_DELAY)
3833
      _sleep_fn(_RCMD_INVALID_DELAY)
3834

    
3835
      # Do not include original error message in returned error
3836
      _Fail("Executing command '%s' failed" % cmd)
3837
    elif cmdresult.failed or cmdresult.fail_reason:
3838
      _Fail("Remote command '%s' failed: %s; output: %s",
3839
            cmd, cmdresult.fail_reason, cmdresult.output)
3840
    else:
3841
      return cmdresult.output
3842
  finally:
3843
    if lock is not None:
3844
      # Release lock at last
3845
      lock.Close()
3846
      lock = None
3847

    
3848

    
3849
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
3850
  """Creates or removes the watcher pause file.
3851

3852
  @type until: None or number
3853
  @param until: Unix timestamp saying until when the watcher shouldn't run
3854

3855
  """
3856
  if until is None:
3857
    logging.info("Received request to no longer pause watcher")
3858
    utils.RemoveFile(_filename)
3859
  else:
3860
    logging.info("Received request to pause watcher until %s", until)
3861

    
3862
    if not ht.TNumber(until):
3863
      _Fail("Duration must be numeric")
3864

    
3865
    utils.WriteFile(_filename, data="%d\n" % (until, ), mode=0644)
3866

    
3867

    
3868
class HooksRunner(object):
3869
  """Hook runner.
3870

3871
  This class is instantiated on the node side (ganeti-noded) and not
3872
  on the master side.
3873

3874
  """
3875
  def __init__(self, hooks_base_dir=None):
3876
    """Constructor for hooks runner.
3877

3878
    @type hooks_base_dir: str or None
3879
    @param hooks_base_dir: if not None, this overrides the
3880
        L{pathutils.HOOKS_BASE_DIR} (useful for unittests)
3881

3882
    """
3883
    if hooks_base_dir is None:
3884
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
3885
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3886
    # constant
3887
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
3888

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

3892
    """
3893
    assert len(node_list) == 1
3894
    node = node_list[0]
3895
    _, myself = ssconf.GetMasterAndMyself()
3896
    assert node == myself
3897

    
3898
    results = self.RunHooks(hpath, phase, env)
3899

    
3900
    # Return values in the form expected by HooksMaster
3901
    return {node: (None, False, results)}
3902

    
3903
  def RunHooks(self, hpath, phase, env):
3904
    """Run the scripts in the hooks directory.
3905

3906
    @type hpath: str
3907
    @param hpath: the path to the hooks directory which
3908
        holds the scripts
3909
    @type phase: str
3910
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
3911
        L{constants.HOOKS_PHASE_POST}
3912
    @type env: dict
3913
    @param env: dictionary with the environment for the hook
3914
    @rtype: list
3915
    @return: list of 3-element tuples:
3916
      - script path
3917
      - script result, either L{constants.HKR_SUCCESS} or
3918
        L{constants.HKR_FAIL}
3919
      - output of the script
3920

3921
    @raise errors.ProgrammerError: for invalid input
3922
        parameters
3923

3924
    """
3925
    if phase == constants.HOOKS_PHASE_PRE:
3926
      suffix = "pre"
3927
    elif phase == constants.HOOKS_PHASE_POST:
3928
      suffix = "post"
3929
    else:
3930
      _Fail("Unknown hooks phase '%s'", phase)
3931

    
3932
    subdir = "%s-%s.d" % (hpath, suffix)
3933
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3934

    
3935
    results = []
3936

    
3937
    if not os.path.isdir(dir_name):
3938
      # for non-existing/non-dirs, we simply exit instead of logging a
3939
      # warning at every operation
3940
      return results
3941

    
3942
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3943

    
3944
    for (relname, relstatus, runresult) in runparts_results:
3945
      if relstatus == constants.RUNPARTS_SKIP:
3946
        rrval = constants.HKR_SKIP
3947
        output = ""
3948
      elif relstatus == constants.RUNPARTS_ERR:
3949
        rrval = constants.HKR_FAIL
3950
        output = "Hook script execution error: %s" % runresult
3951
      elif relstatus == constants.RUNPARTS_RUN:
3952
        if runresult.failed:
3953
          rrval = constants.HKR_FAIL
3954
        else:
3955
          rrval = constants.HKR_SUCCESS
3956
        output = utils.SafeEncode(runresult.output.strip())
3957
      results.append(("%s/%s" % (subdir, relname), rrval, output))
3958

    
3959
    return results
3960

    
3961

    
3962
class IAllocatorRunner(object):
3963
  """IAllocator runner.
3964

3965
  This class is instantiated on the node side (ganeti-noded) and not on
3966
  the master side.
3967

3968
  """
3969
  @staticmethod
3970
  def Run(name, idata):
3971
    """Run an iallocator script.
3972

3973
    @type name: str
3974
    @param name: the iallocator script name
3975
    @type idata: str
3976
    @param idata: the allocator input data
3977

3978
    @rtype: tuple
3979
    @return: two element tuple of:
3980
       - status
3981
       - either error message or stdout of allocator (for success)
3982

3983
    """
3984
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
3985
                                  os.path.isfile)
3986
    if alloc_script is None:
3987
      _Fail("iallocator module '%s' not found in the search path", name)
3988

    
3989
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
3990
    try:
3991
      os.write(fd, idata)
3992
      os.close(fd)
3993
      result = utils.RunCmd([alloc_script, fin_name])
3994
      if result.failed:
3995
        _Fail("iallocator module '%s' failed: %s, output '%s'",
3996
              name, result.fail_reason, result.output)
3997
    finally:
3998
      os.unlink(fin_name)
3999

    
4000
    return result.stdout
4001

    
4002

    
4003
class DevCacheManager(object):
4004
  """Simple class for managing a cache of block device information.
4005

4006
  """
4007
  _DEV_PREFIX = "/dev/"
4008
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4009

    
4010
  @classmethod
4011
  def _ConvertPath(cls, dev_path):
4012
    """Converts a /dev/name path to the cache file name.
4013

4014
    This replaces slashes with underscores and strips the /dev
4015
    prefix. It then returns the full path to the cache file.
4016

4017
    @type dev_path: str
4018
    @param dev_path: the C{/dev/} path name
4019
    @rtype: str
4020
    @return: the converted path name
4021

4022
    """
4023
    if dev_path.startswith(cls._DEV_PREFIX):
4024
      dev_path = dev_path[len(cls._DEV_PREFIX):]
4025
    dev_path = dev_path.replace("/", "_")
4026
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4027
    return fpath
4028

    
4029
  @classmethod
4030
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4031
    """Updates the cache information for a given device.
4032

4033
    @type dev_path: str
4034
    @param dev_path: the pathname of the device
4035
    @type owner: str
4036
    @param owner: the owner (instance name) of the device
4037
    @type on_primary: bool
4038
    @param on_primary: whether this is the primary
4039
        node nor not
4040
    @type iv_name: str
4041
    @param iv_name: the instance-visible name of the
4042
        device, as in objects.Disk.iv_name
4043

4044
    @rtype: None
4045

4046
    """
4047
    if dev_path is None:
4048
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
4049
      return
4050
    fpath = cls._ConvertPath(dev_path)
4051
    if on_primary:
4052
      state = "primary"
4053
    else:
4054
      state = "secondary"
4055
    if iv_name is None:
4056
      iv_name = "not_visible"
4057
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4058
    try:
4059
      utils.WriteFile(fpath, data=fdata)
4060
    except EnvironmentError, err:
4061
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4062

    
4063
  @classmethod
4064
  def RemoveCache(cls, dev_path):
4065
    """Remove data for a dev_path.
4066

4067
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
4068
    path name and logging.
4069

4070
    @type dev_path: str
4071
    @param dev_path: the pathname of the device
4072

4073
    @rtype: None
4074

4075
    """
4076
    if dev_path is None:
4077
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
4078
      return
4079
    fpath = cls._ConvertPath(dev_path)
4080
    try:
4081
      utils.RemoveFile(fpath)
4082
    except EnvironmentError, err:
4083
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)