Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 97e3cece

History | View | Annotate | Download (142.6 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Google Inc.
5
# All rights reserved.
6
#
7
# Redistribution and use in source and binary forms, with or without
8
# modification, are permitted provided that the following conditions are
9
# met:
10
#
11
# 1. Redistributions of source code must retain the above copyright notice,
12
# this list of conditions and the following disclaimer.
13
#
14
# 2. Redistributions in binary form must reproduce the above copyright
15
# notice, this list of conditions and the following disclaimer in the
16
# documentation and/or other materials provided with the distribution.
17
#
18
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
19
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
20
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
21
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
22
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
25
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
26
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
28
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29

    
30

    
31
"""Functions used by the node daemon
32

33
@var _ALLOWED_UPLOAD_FILES: denotes which files are accepted in
34
     the L{UploadFile} function
35
@var _ALLOWED_CLEAN_DIRS: denotes which directories are accepted
36
     in the L{_CleanDirectory} function
37

38
"""
39

    
40
# pylint: disable=E1103,C0302
41

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

    
46
# C0302: This module has become too big and should be split up
47

    
48

    
49
import os
50
import os.path
51
import shutil
52
import time
53
import stat
54
import errno
55
import re
56
import random
57
import logging
58
import tempfile
59
import zlib
60
import base64
61
import signal
62

    
63
from ganeti import errors
64
from ganeti import utils
65
from ganeti import ssh
66
from ganeti import hypervisor
67
from ganeti import constants
68
from ganeti.storage import bdev
69
from ganeti.storage import drbd
70
from ganeti.storage import extstorage
71
from ganeti.storage import filestorage
72
from ganeti import objects
73
from ganeti import ssconf
74
from ganeti import serializer
75
from ganeti import netutils
76
from ganeti import runtime
77
from ganeti import compat
78
from ganeti import pathutils
79
from ganeti import vcluster
80
from ganeti import ht
81
from ganeti.storage.base import BlockDev
82
from ganeti.storage.drbd import DRBD8
83
from ganeti import hooksmaster
84

    
85

    
86
_BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id"
87
_ALLOWED_CLEAN_DIRS = compat.UniqueFrozenset([
88
  pathutils.DATA_DIR,
89
  pathutils.JOB_QUEUE_ARCHIVE_DIR,
90
  pathutils.QUEUE_DIR,
91
  pathutils.CRYPTO_KEYS_DIR,
92
  ])
93
_MAX_SSL_CERT_VALIDITY = 7 * 24 * 60 * 60
94
_X509_KEY_FILE = "key"
95
_X509_CERT_FILE = "cert"
96
_IES_STATUS_FILE = "status"
97
_IES_PID_FILE = "pid"
98
_IES_CA_FILE = "ca"
99

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

    
103
# Actions for the master setup script
104
_MASTER_START = "start"
105
_MASTER_STOP = "stop"
106

    
107
#: Maximum file permissions for restricted command directory and executables
108
_RCMD_MAX_MODE = (stat.S_IRWXU |
109
                  stat.S_IRGRP | stat.S_IXGRP |
110
                  stat.S_IROTH | stat.S_IXOTH)
111

    
112
#: Delay before returning an error for restricted commands
113
_RCMD_INVALID_DELAY = 10
114

    
115
#: How long to wait to acquire lock for restricted commands (shorter than
116
#: L{_RCMD_INVALID_DELAY}) to reduce blockage of noded forks when many
117
#: command requests arrive
118
_RCMD_LOCK_TIMEOUT = _RCMD_INVALID_DELAY * 0.8
119

    
120

    
121
class RPCFail(Exception):
122
  """Class denoting RPC failure.
123

124
  Its argument is the error message.
125

126
  """
127

    
128

    
129
def _GetInstReasonFilename(instance_name):
130
  """Path of the file containing the reason of the instance status change.
131

132
  @type instance_name: string
133
  @param instance_name: The name of the instance
134
  @rtype: string
135
  @return: The path of the file
136

137
  """
138
  return utils.PathJoin(pathutils.INSTANCE_REASON_DIR, instance_name)
139

    
140

    
141
def _StoreInstReasonTrail(instance_name, trail):
142
  """Serialize a reason trail related to an instance change of state to file.
143

144
  The exact location of the file depends on the name of the instance and on
145
  the configuration of the Ganeti cluster defined at deploy time.
146

147
  @type instance_name: string
148
  @param instance_name: The name of the instance
149
  @rtype: None
150

151
  """
152
  json = serializer.DumpJson(trail)
153
  filename = _GetInstReasonFilename(instance_name)
154
  utils.WriteFile(filename, data=json)
155

    
156

    
157
def _Fail(msg, *args, **kwargs):
158
  """Log an error and the raise an RPCFail exception.
159

160
  This exception is then handled specially in the ganeti daemon and
161
  turned into a 'failed' return type. As such, this function is a
162
  useful shortcut for logging the error and returning it to the master
163
  daemon.
164

165
  @type msg: string
166
  @param msg: the text of the exception
167
  @raise RPCFail
168

169
  """
170
  if args:
171
    msg = msg % args
172
  if "log" not in kwargs or kwargs["log"]: # if we should log this error
173
    if "exc" in kwargs and kwargs["exc"]:
174
      logging.exception(msg)
175
    else:
176
      logging.error(msg)
177
  raise RPCFail(msg)
178

    
179

    
180
def _GetConfig():
181
  """Simple wrapper to return a SimpleStore.
182

183
  @rtype: L{ssconf.SimpleStore}
184
  @return: a SimpleStore instance
185

186
  """
187
  return ssconf.SimpleStore()
188

    
189

    
190
def _GetSshRunner(cluster_name):
191
  """Simple wrapper to return an SshRunner.
192

193
  @type cluster_name: str
194
  @param cluster_name: the cluster name, which is needed
195
      by the SshRunner constructor
196
  @rtype: L{ssh.SshRunner}
197
  @return: an SshRunner instance
198

199
  """
200
  return ssh.SshRunner(cluster_name)
201

    
202

    
203
def _Decompress(data):
204
  """Unpacks data compressed by the RPC client.
205

206
  @type data: list or tuple
207
  @param data: Data sent by RPC client
208
  @rtype: str
209
  @return: Decompressed data
210

211
  """
212
  assert isinstance(data, (list, tuple))
213
  assert len(data) == 2
214
  (encoding, content) = data
215
  if encoding == constants.RPC_ENCODING_NONE:
216
    return content
217
  elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
218
    return zlib.decompress(base64.b64decode(content))
219
  else:
220
    raise AssertionError("Unknown data encoding")
221

    
222

    
223
def _CleanDirectory(path, exclude=None):
224
  """Removes all regular files in a directory.
225

226
  @type path: str
227
  @param path: the directory to clean
228
  @type exclude: list
229
  @param exclude: list of files to be excluded, defaults
230
      to the empty list
231

232
  """
233
  if path not in _ALLOWED_CLEAN_DIRS:
234
    _Fail("Path passed to _CleanDirectory not in allowed clean targets: '%s'",
235
          path)
236

    
237
  if not os.path.isdir(path):
238
    return
239
  if exclude is None:
240
    exclude = []
241
  else:
242
    # Normalize excluded paths
243
    exclude = [os.path.normpath(i) for i in exclude]
244

    
245
  for rel_name in utils.ListVisibleFiles(path):
246
    full_name = utils.PathJoin(path, rel_name)
247
    if full_name in exclude:
248
      continue
249
    if os.path.isfile(full_name) and not os.path.islink(full_name):
250
      utils.RemoveFile(full_name)
251

    
252

    
253
def _BuildUploadFileList():
254
  """Build the list of allowed upload files.
255

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

258
  """
259
  allowed_files = set([
260
    pathutils.CLUSTER_CONF_FILE,
261
    pathutils.ETC_HOSTS,
262
    pathutils.SSH_KNOWN_HOSTS_FILE,
263
    pathutils.VNC_PASSWORD_FILE,
264
    pathutils.RAPI_CERT_FILE,
265
    pathutils.SPICE_CERT_FILE,
266
    pathutils.SPICE_CACERT_FILE,
267
    pathutils.RAPI_USERS_FILE,
268
    pathutils.CONFD_HMAC_KEY,
269
    pathutils.CLUSTER_DOMAIN_SECRET_FILE,
270
    ])
271

    
272
  for hv_name in constants.HYPER_TYPES:
273
    hv_class = hypervisor.GetHypervisorClass(hv_name)
274
    allowed_files.update(hv_class.GetAncillaryFiles()[0])
275

    
276
  assert pathutils.FILE_STORAGE_PATHS_FILE not in allowed_files, \
277
    "Allowed file storage paths should never be uploaded via RPC"
278

    
279
  return frozenset(allowed_files)
280

    
281

    
282
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
283

    
284

    
285
def JobQueuePurge():
286
  """Removes job queue files and archived jobs.
287

288
  @rtype: tuple
289
  @return: True, None
290

291
  """
292
  _CleanDirectory(pathutils.QUEUE_DIR, exclude=[pathutils.JOB_QUEUE_LOCK_FILE])
293
  _CleanDirectory(pathutils.JOB_QUEUE_ARCHIVE_DIR)
294

    
295

    
296
def GetMasterInfo():
297
  """Returns master information.
298

299
  This is an utility function to compute master information, either
300
  for consumption here or from the node daemon.
301

302
  @rtype: tuple
303
  @return: master_netdev, master_ip, master_name, primary_ip_family,
304
    master_netmask
305
  @raise RPCFail: in case of errors
306

307
  """
308
  try:
309
    cfg = _GetConfig()
310
    master_netdev = cfg.GetMasterNetdev()
311
    master_ip = cfg.GetMasterIP()
312
    master_netmask = cfg.GetMasterNetmask()
313
    master_node = cfg.GetMasterNode()
314
    primary_ip_family = cfg.GetPrimaryIPFamily()
315
  except errors.ConfigurationError, err:
316
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
317
  return (master_netdev, master_ip, master_node, primary_ip_family,
318
          master_netmask)
319

    
320

    
321
def RunLocalHooks(hook_opcode, hooks_path, env_builder_fn):
322
  """Decorator that runs hooks before and after the decorated function.
323

324
  @type hook_opcode: string
325
  @param hook_opcode: opcode of the hook
326
  @type hooks_path: string
327
  @param hooks_path: path of the hooks
328
  @type env_builder_fn: function
329
  @param env_builder_fn: function that returns a dictionary containing the
330
    environment variables for the hooks. Will get all the parameters of the
331
    decorated function.
332
  @raise RPCFail: in case of pre-hook failure
333

334
  """
335
  def decorator(fn):
336
    def wrapper(*args, **kwargs):
337
      _, myself = ssconf.GetMasterAndMyself()
338
      nodes = ([myself], [myself])  # these hooks run locally
339

    
340
      env_fn = compat.partial(env_builder_fn, *args, **kwargs)
341

    
342
      cfg = _GetConfig()
343
      hr = HooksRunner()
344
      hm = hooksmaster.HooksMaster(hook_opcode, hooks_path, nodes,
345
                                   hr.RunLocalHooks, None, env_fn, None,
346
                                   logging.warning, cfg.GetClusterName(),
347
                                   cfg.GetMasterNode())
348
      hm.RunPhase(constants.HOOKS_PHASE_PRE)
349
      result = fn(*args, **kwargs)
350
      hm.RunPhase(constants.HOOKS_PHASE_POST)
351

    
352
      return result
353
    return wrapper
354
  return decorator
355

    
356

    
357
def _BuildMasterIpEnv(master_params, use_external_mip_script=None):
358
  """Builds environment variables for master IP hooks.
359

360
  @type master_params: L{objects.MasterNetworkParameters}
361
  @param master_params: network parameters of the master
362
  @type use_external_mip_script: boolean
363
  @param use_external_mip_script: whether to use an external master IP
364
    address setup script (unused, but necessary per the implementation of the
365
    _RunLocalHooks decorator)
366

367
  """
368
  # pylint: disable=W0613
369
  ver = netutils.IPAddress.GetVersionFromAddressFamily(master_params.ip_family)
370
  env = {
371
    "MASTER_NETDEV": master_params.netdev,
372
    "MASTER_IP": master_params.ip,
373
    "MASTER_NETMASK": str(master_params.netmask),
374
    "CLUSTER_IP_VERSION": str(ver),
375
  }
376

    
377
  return env
378

    
379

    
380
def _RunMasterSetupScript(master_params, action, use_external_mip_script):
381
  """Execute the master IP address setup script.
382

383
  @type master_params: L{objects.MasterNetworkParameters}
384
  @param master_params: network parameters of the master
385
  @type action: string
386
  @param action: action to pass to the script. Must be one of
387
    L{backend._MASTER_START} or L{backend._MASTER_STOP}
388
  @type use_external_mip_script: boolean
389
  @param use_external_mip_script: whether to use an external master IP
390
    address setup script
391
  @raise backend.RPCFail: if there are errors during the execution of the
392
    script
393

394
  """
395
  env = _BuildMasterIpEnv(master_params)
396

    
397
  if use_external_mip_script:
398
    setup_script = pathutils.EXTERNAL_MASTER_SETUP_SCRIPT
399
  else:
400
    setup_script = pathutils.DEFAULT_MASTER_SETUP_SCRIPT
401

    
402
  result = utils.RunCmd([setup_script, action], env=env, reset_env=True)
403

    
404
  if result.failed:
405
    _Fail("Failed to %s the master IP. Script return value: %s, output: '%s'" %
406
          (action, result.exit_code, result.output), log=True)
407

    
408

    
409
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNUP, "master-ip-turnup",
410
               _BuildMasterIpEnv)
411
def ActivateMasterIp(master_params, use_external_mip_script):
412
  """Activate the IP address of the master daemon.
413

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

421
  """
422
  _RunMasterSetupScript(master_params, _MASTER_START,
423
                        use_external_mip_script)
424

    
425

    
426
def StartMasterDaemons(no_voting):
427
  """Activate local node as master node.
428

429
  The function will start the master daemons (ganeti-masterd and ganeti-rapi).
430

431
  @type no_voting: boolean
432
  @param no_voting: whether to start ganeti-masterd without a node vote
433
      but still non-interactively
434
  @rtype: None
435

436
  """
437

    
438
  if no_voting:
439
    masterd_args = "--no-voting --yes-do-it"
440
  else:
441
    masterd_args = ""
442

    
443
  env = {
444
    "EXTRA_MASTERD_ARGS": masterd_args,
445
    }
446

    
447
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "start-master"], env=env)
448
  if result.failed:
449
    msg = "Can't start Ganeti master: %s" % result.output
450
    logging.error(msg)
451
    _Fail(msg)
452

    
453

    
454
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNDOWN, "master-ip-turndown",
455
               _BuildMasterIpEnv)
456
def DeactivateMasterIp(master_params, use_external_mip_script):
457
  """Deactivate the master IP on this node.
458

459
  @type master_params: L{objects.MasterNetworkParameters}
460
  @param master_params: network parameters of the master
461
  @type use_external_mip_script: boolean
462
  @param use_external_mip_script: whether to use an external master IP
463
    address setup script
464
  @raise RPCFail: in case of errors during the IP turndown
465

466
  """
467
  _RunMasterSetupScript(master_params, _MASTER_STOP,
468
                        use_external_mip_script)
469

    
470

    
471
def StopMasterDaemons():
472
  """Stop the master daemons on this node.
473

474
  Stop the master daemons (ganeti-masterd and ganeti-rapi) on this node.
475

476
  @rtype: None
477

478
  """
479
  # TODO: log and report back to the caller the error failures; we
480
  # need to decide in which case we fail the RPC for this
481

    
482
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop-master"])
483
  if result.failed:
484
    logging.error("Could not stop Ganeti master, command %s had exitcode %s"
485
                  " and error %s",
486
                  result.cmd, result.exit_code, result.output)
487

    
488

    
489
def ChangeMasterNetmask(old_netmask, netmask, master_ip, master_netdev):
490
  """Change the netmask of the master IP.
491

492
  @param old_netmask: the old value of the netmask
493
  @param netmask: the new value of the netmask
494
  @param master_ip: the master IP
495
  @param master_netdev: the master network device
496

497
  """
498
  if old_netmask == netmask:
499
    return
500

    
501
  if not netutils.IPAddress.Own(master_ip):
502
    _Fail("The master IP address is not up, not attempting to change its"
503
          " netmask")
504

    
505
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
506
                         "%s/%s" % (master_ip, netmask),
507
                         "dev", master_netdev, "label",
508
                         "%s:0" % master_netdev])
509
  if result.failed:
510
    _Fail("Could not set the new netmask on the master IP address")
511

    
512
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
513
                         "%s/%s" % (master_ip, old_netmask),
514
                         "dev", master_netdev, "label",
515
                         "%s:0" % master_netdev])
516
  if result.failed:
517
    _Fail("Could not bring down the master IP address with the old netmask")
518

    
519

    
520
def EtcHostsModify(mode, host, ip):
521
  """Modify a host entry in /etc/hosts.
522

523
  @param mode: The mode to operate. Either add or remove entry
524
  @param host: The host to operate on
525
  @param ip: The ip associated with the entry
526

527
  """
528
  if mode == constants.ETC_HOSTS_ADD:
529
    if not ip:
530
      RPCFail("Mode 'add' needs 'ip' parameter, but parameter not"
531
              " present")
532
    utils.AddHostToEtcHosts(host, ip)
533
  elif mode == constants.ETC_HOSTS_REMOVE:
534
    if ip:
535
      RPCFail("Mode 'remove' does not allow 'ip' parameter, but"
536
              " parameter is present")
537
    utils.RemoveHostFromEtcHosts(host)
538
  else:
539
    RPCFail("Mode not supported")
540

    
541

    
542
def LeaveCluster(modify_ssh_setup):
543
  """Cleans up and remove the current node.
544

545
  This function cleans up and prepares the current node to be removed
546
  from the cluster.
547

548
  If processing is successful, then it raises an
549
  L{errors.QuitGanetiException} which is used as a special case to
550
  shutdown the node daemon.
551

552
  @param modify_ssh_setup: boolean
553

554
  """
555
  _CleanDirectory(pathutils.DATA_DIR)
556
  _CleanDirectory(pathutils.CRYPTO_KEYS_DIR)
557
  JobQueuePurge()
558

    
559
  if modify_ssh_setup:
560
    try:
561
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.SSH_LOGIN_USER)
562

    
563
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
564

    
565
      utils.RemoveFile(priv_key)
566
      utils.RemoveFile(pub_key)
567
    except errors.OpExecError:
568
      logging.exception("Error while processing ssh files")
569

    
570
  try:
571
    utils.RemoveFile(pathutils.CONFD_HMAC_KEY)
572
    utils.RemoveFile(pathutils.RAPI_CERT_FILE)
573
    utils.RemoveFile(pathutils.SPICE_CERT_FILE)
574
    utils.RemoveFile(pathutils.SPICE_CACERT_FILE)
575
    utils.RemoveFile(pathutils.NODED_CERT_FILE)
576
  except: # pylint: disable=W0702
577
    logging.exception("Error while removing cluster secrets")
578

    
579
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop", constants.CONFD])
580
  if result.failed:
581
    logging.error("Command %s failed with exitcode %s and error %s",
582
                  result.cmd, result.exit_code, result.output)
583

    
584
  # Raise a custom exception (handled in ganeti-noded)
585
  raise errors.QuitGanetiException(True, "Shutdown scheduled")
586

    
587

    
588
def _CheckStorageParams(params, num_params):
589
  """Performs sanity checks for storage parameters.
590

591
  @type params: list
592
  @param params: list of storage parameters
593
  @type num_params: int
594
  @param num_params: expected number of parameters
595

596
  """
597
  if params is None:
598
    raise errors.ProgrammerError("No storage parameters for storage"
599
                                 " reporting is provided.")
600
  if not isinstance(params, list):
601
    raise errors.ProgrammerError("The storage parameters are not of type"
602
                                 " list: '%s'" % params)
603
  if not len(params) == num_params:
604
    raise errors.ProgrammerError("Did not receive the expected number of"
605
                                 "storage parameters: expected %s,"
606
                                 " received '%s'" % (num_params, len(params)))
607

    
608

    
609
def _CheckLvmStorageParams(params):
610
  """Performs sanity check for the 'exclusive storage' flag.
611

612
  @see: C{_CheckStorageParams}
613

614
  """
615
  _CheckStorageParams(params, 1)
616
  excl_stor = params[0]
617
  if not isinstance(params[0], bool):
618
    raise errors.ProgrammerError("Exclusive storage parameter is not"
619
                                 " boolean: '%s'." % excl_stor)
620
  return excl_stor
621

    
622

    
623
def _GetLvmVgSpaceInfo(name, params):
624
  """Wrapper around C{_GetVgInfo} which checks the storage parameters.
625

626
  @type name: string
627
  @param name: name of the volume group
628
  @type params: list
629
  @param params: list of storage parameters, which in this case should be
630
    containing only one for exclusive storage
631

632
  """
633
  excl_stor = _CheckLvmStorageParams(params)
634
  return _GetVgInfo(name, excl_stor)
635

    
636

    
637
def _GetVgInfo(
638
    name, excl_stor, info_fn=bdev.LogicalVolume.GetVGInfo):
639
  """Retrieves information about a LVM volume group.
640

641
  """
642
  # TODO: GetVGInfo supports returning information for multiple VGs at once
643
  vginfo = info_fn([name], excl_stor)
644
  if vginfo:
645
    vg_free = int(round(vginfo[0][0], 0))
646
    vg_size = int(round(vginfo[0][1], 0))
647
  else:
648
    vg_free = None
649
    vg_size = None
650

    
651
  return {
652
    "type": constants.ST_LVM_VG,
653
    "name": name,
654
    "storage_free": vg_free,
655
    "storage_size": vg_size,
656
    }
657

    
658

    
659
def _GetLvmPvSpaceInfo(name, params):
660
  """Wrapper around C{_GetVgSpindlesInfo} with sanity checks.
661

662
  @see: C{_GetLvmVgSpaceInfo}
663

664
  """
665
  excl_stor = _CheckLvmStorageParams(params)
666
  return _GetVgSpindlesInfo(name, excl_stor)
667

    
668

    
669
def _GetVgSpindlesInfo(
670
    name, excl_stor, info_fn=bdev.LogicalVolume.GetVgSpindlesInfo):
671
  """Retrieves information about spindles in an LVM volume group.
672

673
  @type name: string
674
  @param name: VG name
675
  @type excl_stor: bool
676
  @param excl_stor: exclusive storage
677
  @rtype: dict
678
  @return: dictionary whose keys are "name", "vg_free", "vg_size" for VG name,
679
      free spindles, total spindles respectively
680

681
  """
682
  if excl_stor:
683
    (vg_free, vg_size) = info_fn(name)
684
  else:
685
    vg_free = 0
686
    vg_size = 0
687
  return {
688
    "type": constants.ST_LVM_PV,
689
    "name": name,
690
    "storage_free": vg_free,
691
    "storage_size": vg_size,
692
    }
693

    
694

    
695
def _GetHvInfo(name, hvparams, get_hv_fn=hypervisor.GetHypervisor):
696
  """Retrieves node information from a hypervisor.
697

698
  The information returned depends on the hypervisor. Common items:
699

700
    - vg_size is the size of the configured volume group in MiB
701
    - vg_free is the free size of the volume group in MiB
702
    - memory_dom0 is the memory allocated for domain0 in MiB
703
    - memory_free is the currently available (free) ram in MiB
704
    - memory_total is the total number of ram in MiB
705
    - hv_version: the hypervisor version, if available
706

707
  @type hvparams: dict of string
708
  @param hvparams: the hypervisor's hvparams
709

710
  """
711
  return get_hv_fn(name).GetNodeInfo(hvparams=hvparams)
712

    
713

    
714
def _GetHvInfoAll(hv_specs, get_hv_fn=hypervisor.GetHypervisor):
715
  """Retrieves node information for all hypervisors.
716

717
  See C{_GetHvInfo} for information on the output.
718

719
  @type hv_specs: list of pairs (string, dict of strings)
720
  @param hv_specs: list of pairs of a hypervisor's name and its hvparams
721

722
  """
723
  if hv_specs is None:
724
    return None
725

    
726
  result = []
727
  for hvname, hvparams in hv_specs:
728
    result.append(_GetHvInfo(hvname, hvparams, get_hv_fn))
729
  return result
730

    
731

    
732
def _GetNamedNodeInfo(names, fn):
733
  """Calls C{fn} for all names in C{names} and returns a dictionary.
734

735
  @rtype: None or dict
736

737
  """
738
  if names is None:
739
    return None
740
  else:
741
    return map(fn, names)
742

    
743

    
744
def GetNodeInfo(storage_units, hv_specs):
745
  """Gives back a hash with different information about the node.
746

747
  @type storage_units: list of tuples (string, string, list)
748
  @param storage_units: List of tuples (storage unit, identifier, parameters) to
749
    ask for disk space information. In case of lvm-vg, the identifier is
750
    the VG name. The parameters can contain additional, storage-type-specific
751
    parameters, for example exclusive storage for lvm storage.
752
  @type hv_specs: list of pairs (string, dict of strings)
753
  @param hv_specs: list of pairs of a hypervisor's name and its hvparams
754
  @rtype: tuple; (string, None/dict, None/dict)
755
  @return: Tuple containing boot ID, volume group information and hypervisor
756
    information
757

758
  """
759
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
760
  storage_info = _GetNamedNodeInfo(
761
    storage_units,
762
    (lambda (storage_type, storage_key, storage_params):
763
        _ApplyStorageInfoFunction(storage_type, storage_key, storage_params)))
764
  hv_info = _GetHvInfoAll(hv_specs)
765
  return (bootid, storage_info, hv_info)
766

    
767

    
768
def _GetFileStorageSpaceInfo(path, params):
769
  """Wrapper around filestorage.GetSpaceInfo.
770

771
  The purpose of this wrapper is to call filestorage.GetFileStorageSpaceInfo
772
  and ignore the *args parameter to not leak it into the filestorage
773
  module's code.
774

775
  @see: C{filestorage.GetFileStorageSpaceInfo} for description of the
776
    parameters.
777

778
  """
779
  _CheckStorageParams(params, 0)
780
  return filestorage.GetFileStorageSpaceInfo(path)
781

    
782

    
783
# FIXME: implement storage reporting for all missing storage types.
784
_STORAGE_TYPE_INFO_FN = {
785
  constants.ST_BLOCK: None,
786
  constants.ST_DISKLESS: None,
787
  constants.ST_EXT: None,
788
  constants.ST_FILE: _GetFileStorageSpaceInfo,
789
  constants.ST_LVM_PV: _GetLvmPvSpaceInfo,
790
  constants.ST_LVM_VG: _GetLvmVgSpaceInfo,
791
  constants.ST_RADOS: None,
792
}
793

    
794

    
795
def _ApplyStorageInfoFunction(storage_type, storage_key, *args):
796
  """Looks up and applies the correct function to calculate free and total
797
  storage for the given storage type.
798

799
  @type storage_type: string
800
  @param storage_type: the storage type for which the storage shall be reported.
801
  @type storage_key: string
802
  @param storage_key: identifier of a storage unit, e.g. the volume group name
803
    of an LVM storage unit
804
  @type args: any
805
  @param args: various parameters that can be used for storage reporting. These
806
    parameters and their semantics vary from storage type to storage type and
807
    are just propagated in this function.
808
  @return: the results of the application of the storage space function (see
809
    _STORAGE_TYPE_INFO_FN) if storage space reporting is implemented for that
810
    storage type
811
  @raises NotImplementedError: for storage types who don't support space
812
    reporting yet
813
  """
814
  fn = _STORAGE_TYPE_INFO_FN[storage_type]
815
  if fn is not None:
816
    return fn(storage_key, *args)
817
  else:
818
    raise NotImplementedError
819

    
820

    
821
def _CheckExclusivePvs(pvi_list):
822
  """Check that PVs are not shared among LVs
823

824
  @type pvi_list: list of L{objects.LvmPvInfo} objects
825
  @param pvi_list: information about the PVs
826

827
  @rtype: list of tuples (string, list of strings)
828
  @return: offending volumes, as tuples: (pv_name, [lv1_name, lv2_name...])
829

830
  """
831
  res = []
832
  for pvi in pvi_list:
833
    if len(pvi.lv_list) > 1:
834
      res.append((pvi.name, pvi.lv_list))
835
  return res
836

    
837

    
838
def _VerifyHypervisors(what, vm_capable, result, all_hvparams,
839
                       get_hv_fn=hypervisor.GetHypervisor):
840
  """Verifies the hypervisor. Appends the results to the 'results' list.
841

842
  @type what: C{dict}
843
  @param what: a dictionary of things to check
844
  @type vm_capable: boolean
845
  @param vm_capable: whether or not this node is vm capable
846
  @type result: dict
847
  @param result: dictionary of verification results; results of the
848
    verifications in this function will be added here
849
  @type all_hvparams: dict of dict of string
850
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
851
  @type get_hv_fn: function
852
  @param get_hv_fn: function to retrieve the hypervisor, to improve testability
853

854
  """
855
  if not vm_capable:
856
    return
857

    
858
  if constants.NV_HYPERVISOR in what:
859
    result[constants.NV_HYPERVISOR] = {}
860
    for hv_name in what[constants.NV_HYPERVISOR]:
861
      hvparams = all_hvparams[hv_name]
862
      try:
863
        val = get_hv_fn(hv_name).Verify(hvparams=hvparams)
864
      except errors.HypervisorError, err:
865
        val = "Error while checking hypervisor: %s" % str(err)
866
      result[constants.NV_HYPERVISOR][hv_name] = val
867

    
868

    
869
def _VerifyHvparams(what, vm_capable, result,
870
                    get_hv_fn=hypervisor.GetHypervisor):
871
  """Verifies the hvparams. Appends the results to the 'results' list.
872

873
  @type what: C{dict}
874
  @param what: a dictionary of things to check
875
  @type vm_capable: boolean
876
  @param vm_capable: whether or not this node is vm capable
877
  @type result: dict
878
  @param result: dictionary of verification results; results of the
879
    verifications in this function will be added here
880
  @type get_hv_fn: function
881
  @param get_hv_fn: function to retrieve the hypervisor, to improve testability
882

883
  """
884
  if not vm_capable:
885
    return
886

    
887
  if constants.NV_HVPARAMS in what:
888
    result[constants.NV_HVPARAMS] = []
889
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
890
      try:
891
        logging.info("Validating hv %s, %s", hv_name, hvparms)
892
        get_hv_fn(hv_name).ValidateParameters(hvparms)
893
      except errors.HypervisorError, err:
894
        result[constants.NV_HVPARAMS].append((source, hv_name, str(err)))
895

    
896

    
897
def _VerifyInstanceList(what, vm_capable, result, all_hvparams):
898
  """Verifies the instance list.
899

900
  @type what: C{dict}
901
  @param what: a dictionary of things to check
902
  @type vm_capable: boolean
903
  @param vm_capable: whether or not this node is vm capable
904
  @type result: dict
905
  @param result: dictionary of verification results; results of the
906
    verifications in this function will be added here
907
  @type all_hvparams: dict of dict of string
908
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
909

910
  """
911
  if constants.NV_INSTANCELIST in what and vm_capable:
912
    # GetInstanceList can fail
913
    try:
914
      val = GetInstanceList(what[constants.NV_INSTANCELIST],
915
                            all_hvparams=all_hvparams)
916
    except RPCFail, err:
917
      val = str(err)
918
    result[constants.NV_INSTANCELIST] = val
919

    
920

    
921
def _VerifyNodeInfo(what, vm_capable, result, all_hvparams):
922
  """Verifies the node info.
923

924
  @type what: C{dict}
925
  @param what: a dictionary of things to check
926
  @type vm_capable: boolean
927
  @param vm_capable: whether or not this node is vm capable
928
  @type result: dict
929
  @param result: dictionary of verification results; results of the
930
    verifications in this function will be added here
931
  @type all_hvparams: dict of dict of string
932
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
933

934
  """
935
  if constants.NV_HVINFO in what and vm_capable:
936
    hvname = what[constants.NV_HVINFO]
937
    hyper = hypervisor.GetHypervisor(hvname)
938
    hvparams = all_hvparams[hvname]
939
    result[constants.NV_HVINFO] = hyper.GetNodeInfo(hvparams=hvparams)
940

    
941

    
942
def VerifyNode(what, cluster_name, all_hvparams):
943
  """Verify the status of the local node.
944

945
  Based on the input L{what} parameter, various checks are done on the
946
  local node.
947

948
  If the I{filelist} key is present, this list of
949
  files is checksummed and the file/checksum pairs are returned.
950

951
  If the I{nodelist} key is present, we check that we have
952
  connectivity via ssh with the target nodes (and check the hostname
953
  report).
954

955
  If the I{node-net-test} key is present, we check that we have
956
  connectivity to the given nodes via both primary IP and, if
957
  applicable, secondary IPs.
958

959
  @type what: C{dict}
960
  @param what: a dictionary of things to check:
961
      - filelist: list of files for which to compute checksums
962
      - nodelist: list of nodes we should check ssh communication with
963
      - node-net-test: list of nodes we should check node daemon port
964
        connectivity with
965
      - hypervisor: list with hypervisors to run the verify for
966
  @type cluster_name: string
967
  @param cluster_name: the cluster's name
968
  @type all_hvparams: dict of dict of strings
969
  @param all_hvparams: a dictionary mapping hypervisor names to hvparams
970
  @rtype: dict
971
  @return: a dictionary with the same keys as the input dict, and
972
      values representing the result of the checks
973

974
  """
975
  result = {}
976
  my_name = netutils.Hostname.GetSysName()
977
  port = netutils.GetDaemonPort(constants.NODED)
978
  vm_capable = my_name not in what.get(constants.NV_NONVMNODES, [])
979

    
980
  _VerifyHypervisors(what, vm_capable, result, all_hvparams)
981
  _VerifyHvparams(what, vm_capable, result)
982

    
983
  if constants.NV_FILELIST in what:
984
    fingerprints = utils.FingerprintFiles(map(vcluster.LocalizeVirtualPath,
985
                                              what[constants.NV_FILELIST]))
986
    result[constants.NV_FILELIST] = \
987
      dict((vcluster.MakeVirtualPath(key), value)
988
           for (key, value) in fingerprints.items())
989

    
990
  if constants.NV_NODELIST in what:
991
    (nodes, bynode) = what[constants.NV_NODELIST]
992

    
993
    # Add nodes from other groups (different for each node)
994
    try:
995
      nodes.extend(bynode[my_name])
996
    except KeyError:
997
      pass
998

    
999
    # Use a random order
1000
    random.shuffle(nodes)
1001

    
1002
    # Try to contact all nodes
1003
    val = {}
1004
    for node in nodes:
1005
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
1006
      if not success:
1007
        val[node] = message
1008

    
1009
    result[constants.NV_NODELIST] = val
1010

    
1011
  if constants.NV_NODENETTEST in what:
1012
    result[constants.NV_NODENETTEST] = tmp = {}
1013
    my_pip = my_sip = None
1014
    for name, pip, sip in what[constants.NV_NODENETTEST]:
1015
      if name == my_name:
1016
        my_pip = pip
1017
        my_sip = sip
1018
        break
1019
    if not my_pip:
1020
      tmp[my_name] = ("Can't find my own primary/secondary IP"
1021
                      " in the node list")
1022
    else:
1023
      for name, pip, sip in what[constants.NV_NODENETTEST]:
1024
        fail = []
1025
        if not netutils.TcpPing(pip, port, source=my_pip):
1026
          fail.append("primary")
1027
        if sip != pip:
1028
          if not netutils.TcpPing(sip, port, source=my_sip):
1029
            fail.append("secondary")
1030
        if fail:
1031
          tmp[name] = ("failure using the %s interface(s)" %
1032
                       " and ".join(fail))
1033

    
1034
  if constants.NV_MASTERIP in what:
1035
    # FIXME: add checks on incoming data structures (here and in the
1036
    # rest of the function)
1037
    master_name, master_ip = what[constants.NV_MASTERIP]
1038
    if master_name == my_name:
1039
      source = constants.IP4_ADDRESS_LOCALHOST
1040
    else:
1041
      source = None
1042
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
1043
                                                     source=source)
1044

    
1045
  if constants.NV_USERSCRIPTS in what:
1046
    result[constants.NV_USERSCRIPTS] = \
1047
      [script for script in what[constants.NV_USERSCRIPTS]
1048
       if not utils.IsExecutable(script)]
1049

    
1050
  if constants.NV_OOB_PATHS in what:
1051
    result[constants.NV_OOB_PATHS] = tmp = []
1052
    for path in what[constants.NV_OOB_PATHS]:
1053
      try:
1054
        st = os.stat(path)
1055
      except OSError, err:
1056
        tmp.append("error stating out of band helper: %s" % err)
1057
      else:
1058
        if stat.S_ISREG(st.st_mode):
1059
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
1060
            tmp.append(None)
1061
          else:
1062
            tmp.append("out of band helper %s is not executable" % path)
1063
        else:
1064
          tmp.append("out of band helper %s is not a file" % path)
1065

    
1066
  if constants.NV_LVLIST in what and vm_capable:
1067
    try:
1068
      val = GetVolumeList([what[constants.NV_LVLIST]])
1069
    except RPCFail, err:
1070
      val = str(err)
1071
    result[constants.NV_LVLIST] = val
1072

    
1073
  _VerifyInstanceList(what, vm_capable, result, all_hvparams)
1074

    
1075
  if constants.NV_VGLIST in what and vm_capable:
1076
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
1077

    
1078
  if constants.NV_PVLIST in what and vm_capable:
1079
    check_exclusive_pvs = constants.NV_EXCLUSIVEPVS in what
1080
    val = bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
1081
                                       filter_allocatable=False,
1082
                                       include_lvs=check_exclusive_pvs)
1083
    if check_exclusive_pvs:
1084
      result[constants.NV_EXCLUSIVEPVS] = _CheckExclusivePvs(val)
1085
      for pvi in val:
1086
        # Avoid sending useless data on the wire
1087
        pvi.lv_list = []
1088
    result[constants.NV_PVLIST] = map(objects.LvmPvInfo.ToDict, val)
1089

    
1090
  if constants.NV_VERSION in what:
1091
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
1092
                                    constants.RELEASE_VERSION)
1093

    
1094
  _VerifyNodeInfo(what, vm_capable, result, all_hvparams)
1095

    
1096
  if constants.NV_DRBDVERSION in what and vm_capable:
1097
    try:
1098
      drbd_version = DRBD8.GetProcInfo().GetVersionString()
1099
    except errors.BlockDeviceError, err:
1100
      logging.warning("Can't get DRBD version", exc_info=True)
1101
      drbd_version = str(err)
1102
    result[constants.NV_DRBDVERSION] = drbd_version
1103

    
1104
  if constants.NV_DRBDLIST in what and vm_capable:
1105
    try:
1106
      used_minors = drbd.DRBD8.GetUsedDevs()
1107
    except errors.BlockDeviceError, err:
1108
      logging.warning("Can't get used minors list", exc_info=True)
1109
      used_minors = str(err)
1110
    result[constants.NV_DRBDLIST] = used_minors
1111

    
1112
  if constants.NV_DRBDHELPER in what and vm_capable:
1113
    status = True
1114
    try:
1115
      payload = drbd.DRBD8.GetUsermodeHelper()
1116
    except errors.BlockDeviceError, err:
1117
      logging.error("Can't get DRBD usermode helper: %s", str(err))
1118
      status = False
1119
      payload = str(err)
1120
    result[constants.NV_DRBDHELPER] = (status, payload)
1121

    
1122
  if constants.NV_NODESETUP in what:
1123
    result[constants.NV_NODESETUP] = tmpr = []
1124
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
1125
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
1126
                  " under /sys, missing required directories /sys/block"
1127
                  " and /sys/class/net")
1128
    if (not os.path.isdir("/proc/sys") or
1129
        not os.path.isfile("/proc/sysrq-trigger")):
1130
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
1131
                  " under /proc, missing required directory /proc/sys and"
1132
                  " the file /proc/sysrq-trigger")
1133

    
1134
  if constants.NV_TIME in what:
1135
    result[constants.NV_TIME] = utils.SplitTime(time.time())
1136

    
1137
  if constants.NV_OSLIST in what and vm_capable:
1138
    result[constants.NV_OSLIST] = DiagnoseOS()
1139

    
1140
  if constants.NV_BRIDGES in what and vm_capable:
1141
    result[constants.NV_BRIDGES] = [bridge
1142
                                    for bridge in what[constants.NV_BRIDGES]
1143
                                    if not utils.BridgeExists(bridge)]
1144

    
1145
  if what.get(constants.NV_ACCEPTED_STORAGE_PATHS) == my_name:
1146
    result[constants.NV_ACCEPTED_STORAGE_PATHS] = \
1147
        filestorage.ComputeWrongFileStoragePaths()
1148

    
1149
  if what.get(constants.NV_FILE_STORAGE_PATH):
1150
    pathresult = filestorage.CheckFileStoragePath(
1151
        what[constants.NV_FILE_STORAGE_PATH])
1152
    if pathresult:
1153
      result[constants.NV_FILE_STORAGE_PATH] = pathresult
1154

    
1155
  if what.get(constants.NV_SHARED_FILE_STORAGE_PATH):
1156
    pathresult = filestorage.CheckFileStoragePath(
1157
        what[constants.NV_SHARED_FILE_STORAGE_PATH])
1158
    if pathresult:
1159
      result[constants.NV_SHARED_FILE_STORAGE_PATH] = pathresult
1160

    
1161
  return result
1162

    
1163

    
1164
def GetBlockDevSizes(devices):
1165
  """Return the size of the given block devices
1166

1167
  @type devices: list
1168
  @param devices: list of block device nodes to query
1169
  @rtype: dict
1170
  @return:
1171
    dictionary of all block devices under /dev (key). The value is their
1172
    size in MiB.
1173

1174
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
1175

1176
  """
1177
  DEV_PREFIX = "/dev/"
1178
  blockdevs = {}
1179

    
1180
  for devpath in devices:
1181
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
1182
      continue
1183

    
1184
    try:
1185
      st = os.stat(devpath)
1186
    except EnvironmentError, err:
1187
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
1188
      continue
1189

    
1190
    if stat.S_ISBLK(st.st_mode):
1191
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
1192
      if result.failed:
1193
        # We don't want to fail, just do not list this device as available
1194
        logging.warning("Cannot get size for block device %s", devpath)
1195
        continue
1196

    
1197
      size = int(result.stdout) / (1024 * 1024)
1198
      blockdevs[devpath] = size
1199
  return blockdevs
1200

    
1201

    
1202
def GetVolumeList(vg_names):
1203
  """Compute list of logical volumes and their size.
1204

1205
  @type vg_names: list
1206
  @param vg_names: the volume groups whose LVs we should list, or
1207
      empty for all volume groups
1208
  @rtype: dict
1209
  @return:
1210
      dictionary of all partions (key) with value being a tuple of
1211
      their size (in MiB), inactive and online status::
1212

1213
        {'xenvg/test1': ('20.06', True, True)}
1214

1215
      in case of errors, a string is returned with the error
1216
      details.
1217

1218
  """
1219
  lvs = {}
1220
  sep = "|"
1221
  if not vg_names:
1222
    vg_names = []
1223
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1224
                         "--separator=%s" % sep,
1225
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
1226
  if result.failed:
1227
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
1228

    
1229
  for line in result.stdout.splitlines():
1230
    line = line.strip()
1231
    match = _LVSLINE_REGEX.match(line)
1232
    if not match:
1233
      logging.error("Invalid line returned from lvs output: '%s'", line)
1234
      continue
1235
    vg_name, name, size, attr = match.groups()
1236
    inactive = attr[4] == "-"
1237
    online = attr[5] == "o"
1238
    virtual = attr[0] == "v"
1239
    if virtual:
1240
      # we don't want to report such volumes as existing, since they
1241
      # don't really hold data
1242
      continue
1243
    lvs[vg_name + "/" + name] = (size, inactive, online)
1244

    
1245
  return lvs
1246

    
1247

    
1248
def ListVolumeGroups():
1249
  """List the volume groups and their size.
1250

1251
  @rtype: dict
1252
  @return: dictionary with keys volume name and values the
1253
      size of the volume
1254

1255
  """
1256
  return utils.ListVolumeGroups()
1257

    
1258

    
1259
def NodeVolumes():
1260
  """List all volumes on this node.
1261

1262
  @rtype: list
1263
  @return:
1264
    A list of dictionaries, each having four keys:
1265
      - name: the logical volume name,
1266
      - size: the size of the logical volume
1267
      - dev: the physical device on which the LV lives
1268
      - vg: the volume group to which it belongs
1269

1270
    In case of errors, we return an empty list and log the
1271
    error.
1272

1273
    Note that since a logical volume can live on multiple physical
1274
    volumes, the resulting list might include a logical volume
1275
    multiple times.
1276

1277
  """
1278
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1279
                         "--separator=|",
1280
                         "--options=lv_name,lv_size,devices,vg_name"])
1281
  if result.failed:
1282
    _Fail("Failed to list logical volumes, lvs output: %s",
1283
          result.output)
1284

    
1285
  def parse_dev(dev):
1286
    return dev.split("(")[0]
1287

    
1288
  def handle_dev(dev):
1289
    return [parse_dev(x) for x in dev.split(",")]
1290

    
1291
  def map_line(line):
1292
    line = [v.strip() for v in line]
1293
    return [{"name": line[0], "size": line[1],
1294
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
1295

    
1296
  all_devs = []
1297
  for line in result.stdout.splitlines():
1298
    if line.count("|") >= 3:
1299
      all_devs.extend(map_line(line.split("|")))
1300
    else:
1301
      logging.warning("Strange line in the output from lvs: '%s'", line)
1302
  return all_devs
1303

    
1304

    
1305
def BridgesExist(bridges_list):
1306
  """Check if a list of bridges exist on the current node.
1307

1308
  @rtype: boolean
1309
  @return: C{True} if all of them exist, C{False} otherwise
1310

1311
  """
1312
  missing = []
1313
  for bridge in bridges_list:
1314
    if not utils.BridgeExists(bridge):
1315
      missing.append(bridge)
1316

    
1317
  if missing:
1318
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
1319

    
1320

    
1321
def GetInstanceListForHypervisor(hname, hvparams=None,
1322
                                 get_hv_fn=hypervisor.GetHypervisor):
1323
  """Provides a list of instances of the given hypervisor.
1324

1325
  @type hname: string
1326
  @param hname: name of the hypervisor
1327
  @type hvparams: dict of strings
1328
  @param hvparams: hypervisor parameters for the given hypervisor
1329
  @type get_hv_fn: function
1330
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1331
    name; optional parameter to increase testability
1332

1333
  @rtype: list
1334
  @return: a list of all running instances on the current node
1335
    - instance1.example.com
1336
    - instance2.example.com
1337

1338
  """
1339
  results = []
1340
  try:
1341
    hv = get_hv_fn(hname)
1342
    names = hv.ListInstances(hvparams=hvparams)
1343
    results.extend(names)
1344
  except errors.HypervisorError, err:
1345
    _Fail("Error enumerating instances (hypervisor %s): %s",
1346
          hname, err, exc=True)
1347
  return results
1348

    
1349

    
1350
def GetInstanceList(hypervisor_list, all_hvparams=None,
1351
                    get_hv_fn=hypervisor.GetHypervisor):
1352
  """Provides a list of instances.
1353

1354
  @type hypervisor_list: list
1355
  @param hypervisor_list: the list of hypervisors to query information
1356
  @type all_hvparams: dict of dict of strings
1357
  @param all_hvparams: a dictionary mapping hypervisor types to respective
1358
    cluster-wide hypervisor parameters
1359
  @type get_hv_fn: function
1360
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1361
    name; optional parameter to increase testability
1362

1363
  @rtype: list
1364
  @return: a list of all running instances on the current node
1365
    - instance1.example.com
1366
    - instance2.example.com
1367

1368
  """
1369
  results = []
1370
  for hname in hypervisor_list:
1371
    hvparams = all_hvparams[hname]
1372
    results.extend(GetInstanceListForHypervisor(hname, hvparams=hvparams,
1373
                                                get_hv_fn=get_hv_fn))
1374
  return results
1375

    
1376

    
1377
def GetInstanceInfo(instance, hname, hvparams=None):
1378
  """Gives back the information about an instance as a dictionary.
1379

1380
  @type instance: string
1381
  @param instance: the instance name
1382
  @type hname: string
1383
  @param hname: the hypervisor type of the instance
1384
  @type hvparams: dict of strings
1385
  @param hvparams: the instance's hvparams
1386

1387
  @rtype: dict
1388
  @return: dictionary with the following keys:
1389
      - memory: memory size of instance (int)
1390
      - state: xen state of instance (string)
1391
      - time: cpu time of instance (float)
1392
      - vcpus: the number of vcpus (int)
1393

1394
  """
1395
  output = {}
1396

    
1397
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance,
1398
                                                          hvparams=hvparams)
1399
  if iinfo is not None:
1400
    output["memory"] = iinfo[2]
1401
    output["vcpus"] = iinfo[3]
1402
    output["state"] = iinfo[4]
1403
    output["time"] = iinfo[5]
1404

    
1405
  return output
1406

    
1407

    
1408
def GetInstanceMigratable(instance):
1409
  """Computes whether an instance can be migrated.
1410

1411
  @type instance: L{objects.Instance}
1412
  @param instance: object representing the instance to be checked.
1413

1414
  @rtype: tuple
1415
  @return: tuple of (result, description) where:
1416
      - result: whether the instance can be migrated or not
1417
      - description: a description of the issue, if relevant
1418

1419
  """
1420
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1421
  iname = instance.name
1422
  if iname not in hyper.ListInstances(instance.hvparams):
1423
    _Fail("Instance %s is not running", iname)
1424

    
1425
  for idx in range(len(instance.disks)):
1426
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1427
    if not os.path.islink(link_name):
1428
      logging.warning("Instance %s is missing symlink %s for disk %d",
1429
                      iname, link_name, idx)
1430

    
1431

    
1432
def GetAllInstancesInfo(hypervisor_list, all_hvparams):
1433
  """Gather data about all instances.
1434

1435
  This is the equivalent of L{GetInstanceInfo}, except that it
1436
  computes data for all instances at once, thus being faster if one
1437
  needs data about more than one instance.
1438

1439
  @type hypervisor_list: list
1440
  @param hypervisor_list: list of hypervisors to query for instance data
1441
  @type all_hvparams: dict of dict of strings
1442
  @param all_hvparams: mapping of hypervisor names to hvparams
1443

1444
  @rtype: dict
1445
  @return: dictionary of instance: data, with data having the following keys:
1446
      - memory: memory size of instance (int)
1447
      - state: xen state of instance (string)
1448
      - time: cpu time of instance (float)
1449
      - vcpus: the number of vcpus
1450

1451
  """
1452
  output = {}
1453

    
1454
  for hname in hypervisor_list:
1455
    hvparams = all_hvparams[hname]
1456
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo(hvparams)
1457
    if iinfo:
1458
      for name, _, memory, vcpus, state, times in iinfo:
1459
        value = {
1460
          "memory": memory,
1461
          "vcpus": vcpus,
1462
          "state": state,
1463
          "time": times,
1464
          }
1465
        if name in output:
1466
          # we only check static parameters, like memory and vcpus,
1467
          # and not state and time which can change between the
1468
          # invocations of the different hypervisors
1469
          for key in "memory", "vcpus":
1470
            if value[key] != output[name][key]:
1471
              _Fail("Instance %s is running twice"
1472
                    " with different parameters", name)
1473
        output[name] = value
1474

    
1475
  return output
1476

    
1477

    
1478
def _InstanceLogName(kind, os_name, instance, component):
1479
  """Compute the OS log filename for a given instance and operation.
1480

1481
  The instance name and os name are passed in as strings since not all
1482
  operations have these as part of an instance object.
1483

1484
  @type kind: string
1485
  @param kind: the operation type (e.g. add, import, etc.)
1486
  @type os_name: string
1487
  @param os_name: the os name
1488
  @type instance: string
1489
  @param instance: the name of the instance being imported/added/etc.
1490
  @type component: string or None
1491
  @param component: the name of the component of the instance being
1492
      transferred
1493

1494
  """
1495
  # TODO: Use tempfile.mkstemp to create unique filename
1496
  if component:
1497
    assert "/" not in component
1498
    c_msg = "-%s" % component
1499
  else:
1500
    c_msg = ""
1501
  base = ("%s-%s-%s%s-%s.log" %
1502
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1503
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1504

    
1505

    
1506
def InstanceOsAdd(instance, reinstall, debug):
1507
  """Add an OS to an instance.
1508

1509
  @type instance: L{objects.Instance}
1510
  @param instance: Instance whose OS is to be installed
1511
  @type reinstall: boolean
1512
  @param reinstall: whether this is an instance reinstall
1513
  @type debug: integer
1514
  @param debug: debug level, passed to the OS scripts
1515
  @rtype: None
1516

1517
  """
1518
  inst_os = OSFromDisk(instance.os)
1519

    
1520
  create_env = OSEnvironment(instance, inst_os, debug)
1521
  if reinstall:
1522
    create_env["INSTANCE_REINSTALL"] = "1"
1523

    
1524
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1525

    
1526
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1527
                        cwd=inst_os.path, output=logfile, reset_env=True)
1528
  if result.failed:
1529
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1530
                  " output: %s", result.cmd, result.fail_reason, logfile,
1531
                  result.output)
1532
    lines = [utils.SafeEncode(val)
1533
             for val in utils.TailFile(logfile, lines=20)]
1534
    _Fail("OS create script failed (%s), last lines in the"
1535
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1536

    
1537

    
1538
def RunRenameInstance(instance, old_name, debug):
1539
  """Run the OS rename script for an instance.
1540

1541
  @type instance: L{objects.Instance}
1542
  @param instance: Instance whose OS is to be installed
1543
  @type old_name: string
1544
  @param old_name: previous instance name
1545
  @type debug: integer
1546
  @param debug: debug level, passed to the OS scripts
1547
  @rtype: boolean
1548
  @return: the success of the operation
1549

1550
  """
1551
  inst_os = OSFromDisk(instance.os)
1552

    
1553
  rename_env = OSEnvironment(instance, inst_os, debug)
1554
  rename_env["OLD_INSTANCE_NAME"] = old_name
1555

    
1556
  logfile = _InstanceLogName("rename", instance.os,
1557
                             "%s-%s" % (old_name, instance.name), None)
1558

    
1559
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1560
                        cwd=inst_os.path, output=logfile, reset_env=True)
1561

    
1562
  if result.failed:
1563
    logging.error("os create command '%s' returned error: %s output: %s",
1564
                  result.cmd, result.fail_reason, result.output)
1565
    lines = [utils.SafeEncode(val)
1566
             for val in utils.TailFile(logfile, lines=20)]
1567
    _Fail("OS rename script failed (%s), last lines in the"
1568
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1569

    
1570

    
1571
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1572
  """Returns symlink path for block device.
1573

1574
  """
1575
  if _dir is None:
1576
    _dir = pathutils.DISK_LINKS_DIR
1577

    
1578
  return utils.PathJoin(_dir,
1579
                        ("%s%s%s" %
1580
                         (instance_name, constants.DISK_SEPARATOR, idx)))
1581

    
1582

    
1583
def _SymlinkBlockDev(instance_name, device_path, idx):
1584
  """Set up symlinks to a instance's block device.
1585

1586
  This is an auxiliary function run when an instance is start (on the primary
1587
  node) or when an instance is migrated (on the target node).
1588

1589

1590
  @param instance_name: the name of the target instance
1591
  @param device_path: path of the physical block device, on the node
1592
  @param idx: the disk index
1593
  @return: absolute path to the disk's symlink
1594

1595
  """
1596
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1597
  try:
1598
    os.symlink(device_path, link_name)
1599
  except OSError, err:
1600
    if err.errno == errno.EEXIST:
1601
      if (not os.path.islink(link_name) or
1602
          os.readlink(link_name) != device_path):
1603
        os.remove(link_name)
1604
        os.symlink(device_path, link_name)
1605
    else:
1606
      raise
1607

    
1608
  return link_name
1609

    
1610

    
1611
def _RemoveBlockDevLinks(instance_name, disks):
1612
  """Remove the block device symlinks belonging to the given instance.
1613

1614
  """
1615
  for idx, _ in enumerate(disks):
1616
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1617
    if os.path.islink(link_name):
1618
      try:
1619
        os.remove(link_name)
1620
      except OSError:
1621
        logging.exception("Can't remove symlink '%s'", link_name)
1622

    
1623

    
1624
def _CalculateDeviceURI(instance, disk, device):
1625
  """Get the URI for the device.
1626

1627
  @type instance: L{objects.Instance}
1628
  @param instance: the instance which disk belongs to
1629
  @type disk: L{objects.Disk}
1630
  @param disk: the target disk object
1631
  @type device: L{bdev.BlockDev}
1632
  @param device: the corresponding BlockDevice
1633
  @rtype: string
1634
  @return: the device uri if any else None
1635

1636
  """
1637
  access_mode = disk.params.get(constants.LDP_ACCESS,
1638
                                constants.DISK_KERNELSPACE)
1639
  if access_mode == constants.DISK_USERSPACE:
1640
    # This can raise errors.BlockDeviceError
1641
    return device.GetUserspaceAccessUri(instance.hypervisor)
1642
  else:
1643
    return None
1644

    
1645

    
1646
def _GatherAndLinkBlockDevs(instance):
1647
  """Set up an instance's block device(s).
1648

1649
  This is run on the primary node at instance startup. The block
1650
  devices must be already assembled.
1651

1652
  @type instance: L{objects.Instance}
1653
  @param instance: the instance whose disks we should assemble
1654
  @rtype: list
1655
  @return: list of (disk_object, link_name, drive_uri)
1656

1657
  """
1658
  block_devices = []
1659
  for idx, disk in enumerate(instance.disks):
1660
    device = _RecursiveFindBD(disk)
1661
    if device is None:
1662
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1663
                                    str(disk))
1664
    device.Open()
1665
    try:
1666
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1667
    except OSError, e:
1668
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1669
                                    e.strerror)
1670
    uri = _CalculateDeviceURI(instance, disk, device)
1671

    
1672
    block_devices.append((disk, link_name, uri))
1673

    
1674
  return block_devices
1675

    
1676

    
1677
def StartInstance(instance, startup_paused, reason, store_reason=True):
1678
  """Start an instance.
1679

1680
  @type instance: L{objects.Instance}
1681
  @param instance: the instance object
1682
  @type startup_paused: bool
1683
  @param instance: pause instance at startup?
1684
  @type reason: list of reasons
1685
  @param reason: the reason trail for this startup
1686
  @type store_reason: boolean
1687
  @param store_reason: whether to store the shutdown reason trail on file
1688
  @rtype: None
1689

1690
  """
1691
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1692
                                                   instance.hvparams)
1693

    
1694
  if instance.name in running_instances:
1695
    logging.info("Instance %s already running, not starting", instance.name)
1696
    return
1697

    
1698
  try:
1699
    block_devices = _GatherAndLinkBlockDevs(instance)
1700
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1701
    hyper.StartInstance(instance, block_devices, startup_paused)
1702
    if store_reason:
1703
      _StoreInstReasonTrail(instance.name, reason)
1704
  except errors.BlockDeviceError, err:
1705
    _Fail("Block device error: %s", err, exc=True)
1706
  except errors.HypervisorError, err:
1707
    _RemoveBlockDevLinks(instance.name, instance.disks)
1708
    _Fail("Hypervisor error: %s", err, exc=True)
1709

    
1710

    
1711
def InstanceShutdown(instance, timeout, reason, store_reason=True):
1712
  """Shut an instance down.
1713

1714
  @note: this functions uses polling with a hardcoded timeout.
1715

1716
  @type instance: L{objects.Instance}
1717
  @param instance: the instance object
1718
  @type timeout: integer
1719
  @param timeout: maximum timeout for soft shutdown
1720
  @type reason: list of reasons
1721
  @param reason: the reason trail for this shutdown
1722
  @type store_reason: boolean
1723
  @param store_reason: whether to store the shutdown reason trail on file
1724
  @rtype: None
1725

1726
  """
1727
  hv_name = instance.hypervisor
1728
  hyper = hypervisor.GetHypervisor(hv_name)
1729
  iname = instance.name
1730

    
1731
  if instance.name not in hyper.ListInstances(instance.hvparams):
1732
    logging.info("Instance %s not running, doing nothing", iname)
1733
    return
1734

    
1735
  class _TryShutdown(object):
1736
    def __init__(self):
1737
      self.tried_once = False
1738

    
1739
    def __call__(self):
1740
      if iname not in hyper.ListInstances(instance.hvparams):
1741
        return
1742

    
1743
      try:
1744
        hyper.StopInstance(instance, retry=self.tried_once, timeout=timeout)
1745
        if store_reason:
1746
          _StoreInstReasonTrail(instance.name, reason)
1747
      except errors.HypervisorError, err:
1748
        if iname not in hyper.ListInstances(instance.hvparams):
1749
          # if the instance is no longer existing, consider this a
1750
          # success and go to cleanup
1751
          return
1752

    
1753
        _Fail("Failed to stop instance %s: %s", iname, err)
1754

    
1755
      self.tried_once = True
1756

    
1757
      raise utils.RetryAgain()
1758

    
1759
  try:
1760
    utils.Retry(_TryShutdown(), 5, timeout)
1761
  except utils.RetryTimeout:
1762
    # the shutdown did not succeed
1763
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1764

    
1765
    try:
1766
      hyper.StopInstance(instance, force=True)
1767
    except errors.HypervisorError, err:
1768
      if iname in hyper.ListInstances(instance.hvparams):
1769
        # only raise an error if the instance still exists, otherwise
1770
        # the error could simply be "instance ... unknown"!
1771
        _Fail("Failed to force stop instance %s: %s", iname, err)
1772

    
1773
    time.sleep(1)
1774

    
1775
    if iname in hyper.ListInstances(instance.hvparams):
1776
      _Fail("Could not shutdown instance %s even by destroy", iname)
1777

    
1778
  try:
1779
    hyper.CleanupInstance(instance.name)
1780
  except errors.HypervisorError, err:
1781
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1782

    
1783
  _RemoveBlockDevLinks(iname, instance.disks)
1784

    
1785

    
1786
def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1787
  """Reboot an instance.
1788

1789
  @type instance: L{objects.Instance}
1790
  @param instance: the instance object to reboot
1791
  @type reboot_type: str
1792
  @param reboot_type: the type of reboot, one the following
1793
    constants:
1794
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1795
        instance OS, do not recreate the VM
1796
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1797
        restart the VM (at the hypervisor level)
1798
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1799
        not accepted here, since that mode is handled differently, in
1800
        cmdlib, and translates into full stop and start of the
1801
        instance (instead of a call_instance_reboot RPC)
1802
  @type shutdown_timeout: integer
1803
  @param shutdown_timeout: maximum timeout for soft shutdown
1804
  @type reason: list of reasons
1805
  @param reason: the reason trail for this reboot
1806
  @rtype: None
1807

1808
  """
1809
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1810
                                                   instance.hvparams)
1811

    
1812
  if instance.name not in running_instances:
1813
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1814

    
1815
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1816
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1817
    try:
1818
      hyper.RebootInstance(instance)
1819
    except errors.HypervisorError, err:
1820
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1821
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1822
    try:
1823
      InstanceShutdown(instance, shutdown_timeout, reason, store_reason=False)
1824
      result = StartInstance(instance, False, reason, store_reason=False)
1825
      _StoreInstReasonTrail(instance.name, reason)
1826
      return result
1827
    except errors.HypervisorError, err:
1828
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1829
  else:
1830
    _Fail("Invalid reboot_type received: %s", reboot_type)
1831

    
1832

    
1833
def InstanceBalloonMemory(instance, memory):
1834
  """Resize an instance's memory.
1835

1836
  @type instance: L{objects.Instance}
1837
  @param instance: the instance object
1838
  @type memory: int
1839
  @param memory: new memory amount in MB
1840
  @rtype: None
1841

1842
  """
1843
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1844
  running = hyper.ListInstances(instance.hvparams)
1845
  if instance.name not in running:
1846
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1847
    return
1848
  try:
1849
    hyper.BalloonInstanceMemory(instance, memory)
1850
  except errors.HypervisorError, err:
1851
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1852

    
1853

    
1854
def MigrationInfo(instance):
1855
  """Gather information about an instance to be migrated.
1856

1857
  @type instance: L{objects.Instance}
1858
  @param instance: the instance definition
1859

1860
  """
1861
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1862
  try:
1863
    info = hyper.MigrationInfo(instance)
1864
  except errors.HypervisorError, err:
1865
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1866
  return info
1867

    
1868

    
1869
def AcceptInstance(instance, info, target):
1870
  """Prepare the node to accept an instance.
1871

1872
  @type instance: L{objects.Instance}
1873
  @param instance: the instance definition
1874
  @type info: string/data (opaque)
1875
  @param info: migration information, from the source node
1876
  @type target: string
1877
  @param target: target host (usually ip), on this node
1878

1879
  """
1880
  # TODO: why is this required only for DTS_EXT_MIRROR?
1881
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1882
    # Create the symlinks, as the disks are not active
1883
    # in any way
1884
    try:
1885
      _GatherAndLinkBlockDevs(instance)
1886
    except errors.BlockDeviceError, err:
1887
      _Fail("Block device error: %s", err, exc=True)
1888

    
1889
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1890
  try:
1891
    hyper.AcceptInstance(instance, info, target)
1892
  except errors.HypervisorError, err:
1893
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1894
      _RemoveBlockDevLinks(instance.name, instance.disks)
1895
    _Fail("Failed to accept instance: %s", err, exc=True)
1896

    
1897

    
1898
def FinalizeMigrationDst(instance, info, success):
1899
  """Finalize any preparation to accept an instance.
1900

1901
  @type instance: L{objects.Instance}
1902
  @param instance: the instance definition
1903
  @type info: string/data (opaque)
1904
  @param info: migration information, from the source node
1905
  @type success: boolean
1906
  @param success: whether the migration was a success or a failure
1907

1908
  """
1909
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1910
  try:
1911
    hyper.FinalizeMigrationDst(instance, info, success)
1912
  except errors.HypervisorError, err:
1913
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1914

    
1915

    
1916
def MigrateInstance(cluster_name, instance, target, live):
1917
  """Migrates an instance to another node.
1918

1919
  @type cluster_name: string
1920
  @param cluster_name: name of the cluster
1921
  @type instance: L{objects.Instance}
1922
  @param instance: the instance definition
1923
  @type target: string
1924
  @param target: the target node name
1925
  @type live: boolean
1926
  @param live: whether the migration should be done live or not (the
1927
      interpretation of this parameter is left to the hypervisor)
1928
  @raise RPCFail: if migration fails for some reason
1929

1930
  """
1931
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1932

    
1933
  try:
1934
    hyper.MigrateInstance(cluster_name, instance, target, live)
1935
  except errors.HypervisorError, err:
1936
    _Fail("Failed to migrate instance: %s", err, exc=True)
1937

    
1938

    
1939
def FinalizeMigrationSource(instance, success, live):
1940
  """Finalize the instance migration on the source node.
1941

1942
  @type instance: L{objects.Instance}
1943
  @param instance: the instance definition of the migrated instance
1944
  @type success: bool
1945
  @param success: whether the migration succeeded or not
1946
  @type live: bool
1947
  @param live: whether the user requested a live migration or not
1948
  @raise RPCFail: If the execution fails for some reason
1949

1950
  """
1951
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1952

    
1953
  try:
1954
    hyper.FinalizeMigrationSource(instance, success, live)
1955
  except Exception, err:  # pylint: disable=W0703
1956
    _Fail("Failed to finalize the migration on the source node: %s", err,
1957
          exc=True)
1958

    
1959

    
1960
def GetMigrationStatus(instance):
1961
  """Get the migration status
1962

1963
  @type instance: L{objects.Instance}
1964
  @param instance: the instance that is being migrated
1965
  @rtype: L{objects.MigrationStatus}
1966
  @return: the status of the current migration (one of
1967
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1968
           progress info that can be retrieved from the hypervisor
1969
  @raise RPCFail: If the migration status cannot be retrieved
1970

1971
  """
1972
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1973
  try:
1974
    return hyper.GetMigrationStatus(instance)
1975
  except Exception, err:  # pylint: disable=W0703
1976
    _Fail("Failed to get migration status: %s", err, exc=True)
1977

    
1978

    
1979
def HotplugDevice(instance, action, dev_type, device, extra, seq):
1980
  """Hotplug a device
1981

1982
  Hotplug is currently supported only for KVM Hypervisor.
1983
  @type instance: L{objects.Instance}
1984
  @param instance: the instance to which we hotplug a device
1985
  @type action: string
1986
  @param action: the hotplug action to perform
1987
  @type dev_type: string
1988
  @param dev_type: the device type to hotplug
1989
  @type device: either L{objects.NIC} or L{objects.Disk}
1990
  @param device: the device object to hotplug
1991
  @type extra: tuple
1992
  @param extra: extra info used for disk hotplug (disk link, drive uri)
1993
  @type seq: int
1994
  @param seq: the index of the device from master perspective
1995
  @raise RPCFail: in case instance does not have KVM hypervisor
1996

1997
  """
1998
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1999
  try:
2000
    hyper.VerifyHotplugSupport(instance, action, dev_type)
2001
  except errors.HotplugError, err:
2002
    _Fail("Hotplug is not supported: %s", err)
2003

    
2004
  if action == constants.HOTPLUG_ACTION_ADD:
2005
    fn = hyper.HotAddDevice
2006
  elif action == constants.HOTPLUG_ACTION_REMOVE:
2007
    fn = hyper.HotDelDevice
2008
  elif action == constants.HOTPLUG_ACTION_MODIFY:
2009
    fn = hyper.HotModDevice
2010
  else:
2011
    assert action in constants.HOTPLUG_ALL_ACTIONS
2012

    
2013
  return fn(instance, dev_type, device, extra, seq)
2014

    
2015

    
2016
def HotplugSupported(instance):
2017
  """Checks if hotplug is generally supported.
2018

2019
  """
2020
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
2021
  try:
2022
    hyper.HotplugSupported(instance)
2023
  except errors.HotplugError, err:
2024
    _Fail("Hotplug is not supported: %s", err)
2025

    
2026

    
2027
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
2028
  """Creates a block device for an instance.
2029

2030
  @type disk: L{objects.Disk}
2031
  @param disk: the object describing the disk we should create
2032
  @type size: int
2033
  @param size: the size of the physical underlying device, in MiB
2034
  @type owner: str
2035
  @param owner: the name of the instance for which disk is created,
2036
      used for device cache data
2037
  @type on_primary: boolean
2038
  @param on_primary:  indicates if it is the primary node or not
2039
  @type info: string
2040
  @param info: string that will be sent to the physical device
2041
      creation, used for example to set (LVM) tags on LVs
2042
  @type excl_stor: boolean
2043
  @param excl_stor: Whether exclusive_storage is active
2044

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

2049
  """
2050
  # TODO: remove the obsolete "size" argument
2051
  # pylint: disable=W0613
2052
  clist = []
2053
  if disk.children:
2054
    for child in disk.children:
2055
      try:
2056
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
2057
      except errors.BlockDeviceError, err:
2058
        _Fail("Can't assemble device %s: %s", child, err)
2059
      if on_primary or disk.AssembleOnSecondary():
2060
        # we need the children open in case the device itself has to
2061
        # be assembled
2062
        try:
2063
          # pylint: disable=E1103
2064
          crdev.Open()
2065
        except errors.BlockDeviceError, err:
2066
          _Fail("Can't make child '%s' read-write: %s", child, err)
2067
      clist.append(crdev)
2068

    
2069
  try:
2070
    device = bdev.Create(disk, clist, excl_stor)
2071
  except errors.BlockDeviceError, err:
2072
    _Fail("Can't create block device: %s", err)
2073

    
2074
  if on_primary or disk.AssembleOnSecondary():
2075
    try:
2076
      device.Assemble()
2077
    except errors.BlockDeviceError, err:
2078
      _Fail("Can't assemble device after creation, unusual event: %s", err)
2079
    if on_primary or disk.OpenOnSecondary():
2080
      try:
2081
        device.Open(force=True)
2082
      except errors.BlockDeviceError, err:
2083
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
2084
    DevCacheManager.UpdateCache(device.dev_path, owner,
2085
                                on_primary, disk.iv_name)
2086

    
2087
  device.SetInfo(info)
2088

    
2089
  return device.unique_id
2090

    
2091

    
2092
def _WipeDevice(path, offset, size):
2093
  """This function actually wipes the device.
2094

2095
  @param path: The path to the device to wipe
2096
  @param offset: The offset in MiB in the file
2097
  @param size: The size in MiB to write
2098

2099
  """
2100
  # Internal sizes are always in Mebibytes; if the following "dd" command
2101
  # should use a different block size the offset and size given to this
2102
  # function must be adjusted accordingly before being passed to "dd".
2103
  block_size = 1024 * 1024
2104

    
2105
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
2106
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
2107
         "count=%d" % size]
2108
  result = utils.RunCmd(cmd)
2109

    
2110
  if result.failed:
2111
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
2112
          result.fail_reason, result.output)
2113

    
2114

    
2115
def BlockdevWipe(disk, offset, size):
2116
  """Wipes a block device.
2117

2118
  @type disk: L{objects.Disk}
2119
  @param disk: the disk object we want to wipe
2120
  @type offset: int
2121
  @param offset: The offset in MiB in the file
2122
  @type size: int
2123
  @param size: The size in MiB to write
2124

2125
  """
2126
  try:
2127
    rdev = _RecursiveFindBD(disk)
2128
  except errors.BlockDeviceError:
2129
    rdev = None
2130

    
2131
  if not rdev:
2132
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
2133

    
2134
  # Do cross verify some of the parameters
2135
  if offset < 0:
2136
    _Fail("Negative offset")
2137
  if size < 0:
2138
    _Fail("Negative size")
2139
  if offset > rdev.size:
2140
    _Fail("Offset is bigger than device size")
2141
  if (offset + size) > rdev.size:
2142
    _Fail("The provided offset and size to wipe is bigger than device size")
2143

    
2144
  _WipeDevice(rdev.dev_path, offset, size)
2145

    
2146

    
2147
def BlockdevPauseResumeSync(disks, pause):
2148
  """Pause or resume the sync of the block device.
2149

2150
  @type disks: list of L{objects.Disk}
2151
  @param disks: the disks object we want to pause/resume
2152
  @type pause: bool
2153
  @param pause: Wheater to pause or resume
2154

2155
  """
2156
  success = []
2157
  for disk in disks:
2158
    try:
2159
      rdev = _RecursiveFindBD(disk)
2160
    except errors.BlockDeviceError:
2161
      rdev = None
2162

    
2163
    if not rdev:
2164
      success.append((False, ("Cannot change sync for device %s:"
2165
                              " device not found" % disk.iv_name)))
2166
      continue
2167

    
2168
    result = rdev.PauseResumeSync(pause)
2169

    
2170
    if result:
2171
      success.append((result, None))
2172
    else:
2173
      if pause:
2174
        msg = "Pause"
2175
      else:
2176
        msg = "Resume"
2177
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
2178

    
2179
  return success
2180

    
2181

    
2182
def BlockdevRemove(disk):
2183
  """Remove a block device.
2184

2185
  @note: This is intended to be called recursively.
2186

2187
  @type disk: L{objects.Disk}
2188
  @param disk: the disk object we should remove
2189
  @rtype: boolean
2190
  @return: the success of the operation
2191

2192
  """
2193
  msgs = []
2194
  try:
2195
    rdev = _RecursiveFindBD(disk)
2196
  except errors.BlockDeviceError, err:
2197
    # probably can't attach
2198
    logging.info("Can't attach to device %s in remove", disk)
2199
    rdev = None
2200
  if rdev is not None:
2201
    r_path = rdev.dev_path
2202

    
2203
    def _TryRemove():
2204
      try:
2205
        rdev.Remove()
2206
        return []
2207
      except errors.BlockDeviceError, err:
2208
        return [str(err)]
2209

    
2210
    msgs.extend(utils.SimpleRetry([], _TryRemove,
2211
                                  constants.DISK_REMOVE_RETRY_INTERVAL,
2212
                                  constants.DISK_REMOVE_RETRY_TIMEOUT))
2213

    
2214
    if not msgs:
2215
      DevCacheManager.RemoveCache(r_path)
2216

    
2217
  if disk.children:
2218
    for child in disk.children:
2219
      try:
2220
        BlockdevRemove(child)
2221
      except RPCFail, err:
2222
        msgs.append(str(err))
2223

    
2224
  if msgs:
2225
    _Fail("; ".join(msgs))
2226

    
2227

    
2228
def _RecursiveAssembleBD(disk, owner, as_primary):
2229
  """Activate a block device for an instance.
2230

2231
  This is run on the primary and secondary nodes for an instance.
2232

2233
  @note: this function is called recursively.
2234

2235
  @type disk: L{objects.Disk}
2236
  @param disk: the disk we try to assemble
2237
  @type owner: str
2238
  @param owner: the name of the instance which owns the disk
2239
  @type as_primary: boolean
2240
  @param as_primary: if we should make the block device
2241
      read/write
2242

2243
  @return: the assembled device or None (in case no device
2244
      was assembled)
2245
  @raise errors.BlockDeviceError: in case there is an error
2246
      during the activation of the children or the device
2247
      itself
2248

2249
  """
2250
  children = []
2251
  if disk.children:
2252
    mcn = disk.ChildrenNeeded()
2253
    if mcn == -1:
2254
      mcn = 0 # max number of Nones allowed
2255
    else:
2256
      mcn = len(disk.children) - mcn # max number of Nones
2257
    for chld_disk in disk.children:
2258
      try:
2259
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
2260
      except errors.BlockDeviceError, err:
2261
        if children.count(None) >= mcn:
2262
          raise
2263
        cdev = None
2264
        logging.error("Error in child activation (but continuing): %s",
2265
                      str(err))
2266
      children.append(cdev)
2267

    
2268
  if as_primary or disk.AssembleOnSecondary():
2269
    r_dev = bdev.Assemble(disk, children)
2270
    result = r_dev
2271
    if as_primary or disk.OpenOnSecondary():
2272
      r_dev.Open()
2273
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
2274
                                as_primary, disk.iv_name)
2275

    
2276
  else:
2277
    result = True
2278
  return result
2279

    
2280

    
2281
def BlockdevAssemble(disk, instance, as_primary, idx):
2282
  """Activate a block device for an instance.
2283

2284
  This is a wrapper over _RecursiveAssembleBD.
2285

2286
  @rtype: str or boolean
2287
  @return: a tuple with the C{/dev/...} path and the created symlink
2288
      for primary nodes, and (C{True}, C{True}) for secondary nodes
2289

2290
  """
2291
  try:
2292
    result = _RecursiveAssembleBD(disk, instance.name, as_primary)
2293
    if isinstance(result, BlockDev):
2294
      # pylint: disable=E1103
2295
      dev_path = result.dev_path
2296
      link_name = None
2297
      uri = None
2298
      if as_primary:
2299
        link_name = _SymlinkBlockDev(instance.name, dev_path, idx)
2300
        uri = _CalculateDeviceURI(instance, disk, result)
2301
    elif result:
2302
      return result, result
2303
    else:
2304
      _Fail("Unexpected result from _RecursiveAssembleBD")
2305
  except errors.BlockDeviceError, err:
2306
    _Fail("Error while assembling disk: %s", err, exc=True)
2307
  except OSError, err:
2308
    _Fail("Error while symlinking disk: %s", err, exc=True)
2309

    
2310
  return dev_path, link_name, uri
2311

    
2312

    
2313
def BlockdevShutdown(disk):
2314
  """Shut down a block device.
2315

2316
  First, if the device is assembled (Attach() is successful), then
2317
  the device is shutdown. Then the children of the device are
2318
  shutdown.
2319

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

2324
  @type disk: L{objects.Disk}
2325
  @param disk: the description of the disk we should
2326
      shutdown
2327
  @rtype: None
2328

2329
  """
2330
  msgs = []
2331
  r_dev = _RecursiveFindBD(disk)
2332
  if r_dev is not None:
2333
    r_path = r_dev.dev_path
2334
    try:
2335
      r_dev.Shutdown()
2336
      DevCacheManager.RemoveCache(r_path)
2337
    except errors.BlockDeviceError, err:
2338
      msgs.append(str(err))
2339

    
2340
  if disk.children:
2341
    for child in disk.children:
2342
      try:
2343
        BlockdevShutdown(child)
2344
      except RPCFail, err:
2345
        msgs.append(str(err))
2346

    
2347
  if msgs:
2348
    _Fail("; ".join(msgs))
2349

    
2350

    
2351
def BlockdevAddchildren(parent_cdev, new_cdevs):
2352
  """Extend a mirrored block device.
2353

2354
  @type parent_cdev: L{objects.Disk}
2355
  @param parent_cdev: the disk to which we should add children
2356
  @type new_cdevs: list of L{objects.Disk}
2357
  @param new_cdevs: the list of children which we should add
2358
  @rtype: None
2359

2360
  """
2361
  parent_bdev = _RecursiveFindBD(parent_cdev)
2362
  if parent_bdev is None:
2363
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
2364
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
2365
  if new_bdevs.count(None) > 0:
2366
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
2367
  parent_bdev.AddChildren(new_bdevs)
2368

    
2369

    
2370
def BlockdevRemovechildren(parent_cdev, new_cdevs):
2371
  """Shrink a mirrored block device.
2372

2373
  @type parent_cdev: L{objects.Disk}
2374
  @param parent_cdev: the disk from which we should remove children
2375
  @type new_cdevs: list of L{objects.Disk}
2376
  @param new_cdevs: the list of children which we should remove
2377
  @rtype: None
2378

2379
  """
2380
  parent_bdev = _RecursiveFindBD(parent_cdev)
2381
  if parent_bdev is None:
2382
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
2383
  devs = []
2384
  for disk in new_cdevs:
2385
    rpath = disk.StaticDevPath()
2386
    if rpath is None:
2387
      bd = _RecursiveFindBD(disk)
2388
      if bd is None:
2389
        _Fail("Can't find device %s while removing children", disk)
2390
      else:
2391
        devs.append(bd.dev_path)
2392
    else:
2393
      if not utils.IsNormAbsPath(rpath):
2394
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
2395
      devs.append(rpath)
2396
  parent_bdev.RemoveChildren(devs)
2397

    
2398

    
2399
def BlockdevGetmirrorstatus(disks):
2400
  """Get the mirroring status of a list of devices.
2401

2402
  @type disks: list of L{objects.Disk}
2403
  @param disks: the list of disks which we should query
2404
  @rtype: disk
2405
  @return: List of L{objects.BlockDevStatus}, one for each disk
2406
  @raise errors.BlockDeviceError: if any of the disks cannot be
2407
      found
2408

2409
  """
2410
  stats = []
2411
  for dsk in disks:
2412
    rbd = _RecursiveFindBD(dsk)
2413
    if rbd is None:
2414
      _Fail("Can't find device %s", dsk)
2415

    
2416
    stats.append(rbd.CombinedSyncStatus())
2417

    
2418
  return stats
2419

    
2420

    
2421
def BlockdevGetmirrorstatusMulti(disks):
2422
  """Get the mirroring status of a list of devices.
2423

2424
  @type disks: list of L{objects.Disk}
2425
  @param disks: the list of disks which we should query
2426
  @rtype: disk
2427
  @return: List of tuples, (bool, status), one for each disk; bool denotes
2428
    success/failure, status is L{objects.BlockDevStatus} on success, string
2429
    otherwise
2430

2431
  """
2432
  result = []
2433
  for disk in disks:
2434
    try:
2435
      rbd = _RecursiveFindBD(disk)
2436
      if rbd is None:
2437
        result.append((False, "Can't find device %s" % disk))
2438
        continue
2439

    
2440
      status = rbd.CombinedSyncStatus()
2441
    except errors.BlockDeviceError, err:
2442
      logging.exception("Error while getting disk status")
2443
      result.append((False, str(err)))
2444
    else:
2445
      result.append((True, status))
2446

    
2447
  assert len(disks) == len(result)
2448

    
2449
  return result
2450

    
2451

    
2452
def _RecursiveFindBD(disk):
2453
  """Check if a device is activated.
2454

2455
  If so, return information about the real device.
2456

2457
  @type disk: L{objects.Disk}
2458
  @param disk: the disk object we need to find
2459

2460
  @return: None if the device can't be found,
2461
      otherwise the device instance
2462

2463
  """
2464
  children = []
2465
  if disk.children:
2466
    for chdisk in disk.children:
2467
      children.append(_RecursiveFindBD(chdisk))
2468

    
2469
  return bdev.FindDevice(disk, children)
2470

    
2471

    
2472
def _OpenRealBD(disk):
2473
  """Opens the underlying block device of a disk.
2474

2475
  @type disk: L{objects.Disk}
2476
  @param disk: the disk object we want to open
2477

2478
  """
2479
  real_disk = _RecursiveFindBD(disk)
2480
  if real_disk is None:
2481
    _Fail("Block device '%s' is not set up", disk)
2482

    
2483
  real_disk.Open()
2484

    
2485
  return real_disk
2486

    
2487

    
2488
def BlockdevFind(disk):
2489
  """Check if a device is activated.
2490

2491
  If it is, return information about the real device.
2492

2493
  @type disk: L{objects.Disk}
2494
  @param disk: the disk to find
2495
  @rtype: None or objects.BlockDevStatus
2496
  @return: None if the disk cannot be found, otherwise a the current
2497
           information
2498

2499
  """
2500
  try:
2501
    rbd = _RecursiveFindBD(disk)
2502
  except errors.BlockDeviceError, err:
2503
    _Fail("Failed to find device: %s", err, exc=True)
2504

    
2505
  if rbd is None:
2506
    return None
2507

    
2508
  return rbd.GetSyncStatus()
2509

    
2510

    
2511
def BlockdevGetdimensions(disks):
2512
  """Computes the size of the given disks.
2513

2514
  If a disk is not found, returns None instead.
2515

2516
  @type disks: list of L{objects.Disk}
2517
  @param disks: the list of disk to compute the size for
2518
  @rtype: list
2519
  @return: list with elements None if the disk cannot be found,
2520
      otherwise the pair (size, spindles), where spindles is None if the
2521
      device doesn't support that
2522

2523
  """
2524
  result = []
2525
  for cf in disks:
2526
    try:
2527
      rbd = _RecursiveFindBD(cf)
2528
    except errors.BlockDeviceError:
2529
      result.append(None)
2530
      continue
2531
    if rbd is None:
2532
      result.append(None)
2533
    else:
2534
      result.append(rbd.GetActualDimensions())
2535
  return result
2536

    
2537

    
2538
def BlockdevExport(disk, dest_node_ip, dest_path, cluster_name):
2539
  """Export a block device to a remote node.
2540

2541
  @type disk: L{objects.Disk}
2542
  @param disk: the description of the disk to export
2543
  @type dest_node_ip: str
2544
  @param dest_node_ip: the destination node IP to export to
2545
  @type dest_path: str
2546
  @param dest_path: the destination path on the target node
2547
  @type cluster_name: str
2548
  @param cluster_name: the cluster name, needed for SSH hostalias
2549
  @rtype: None
2550

2551
  """
2552
  real_disk = _OpenRealBD(disk)
2553

    
2554
  # the block size on the read dd is 1MiB to match our units
2555
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2556
                               "dd if=%s bs=1048576 count=%s",
2557
                               real_disk.dev_path, str(disk.size))
2558

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

    
2568
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node_ip,
2569
                                                   constants.SSH_LOGIN_USER,
2570
                                                   destcmd)
2571

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

    
2575
  result = utils.RunCmd(["bash", "-c", command])
2576

    
2577
  if result.failed:
2578
    _Fail("Disk copy command '%s' returned error: %s"
2579
          " output: %s", command, result.fail_reason, result.output)
2580

    
2581

    
2582
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2583
  """Write a file to the filesystem.
2584

2585
  This allows the master to overwrite(!) a file. It will only perform
2586
  the operation if the file belongs to a list of configuration files.
2587

2588
  @type file_name: str
2589
  @param file_name: the target file name
2590
  @type data: str
2591
  @param data: the new contents of the file
2592
  @type mode: int
2593
  @param mode: the mode to give the file (can be None)
2594
  @type uid: string
2595
  @param uid: the owner of the file
2596
  @type gid: string
2597
  @param gid: the group of the file
2598
  @type atime: float
2599
  @param atime: the atime to set on the file (can be None)
2600
  @type mtime: float
2601
  @param mtime: the mtime to set on the file (can be None)
2602
  @rtype: None
2603

2604
  """
2605
  file_name = vcluster.LocalizeVirtualPath(file_name)
2606

    
2607
  if not os.path.isabs(file_name):
2608
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2609

    
2610
  if file_name not in _ALLOWED_UPLOAD_FILES:
2611
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2612
          file_name)
2613

    
2614
  raw_data = _Decompress(data)
2615

    
2616
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2617
    _Fail("Invalid username/groupname type")
2618

    
2619
  getents = runtime.GetEnts()
2620
  uid = getents.LookupUser(uid)
2621
  gid = getents.LookupGroup(gid)
2622

    
2623
  utils.SafeWriteFile(file_name, None,
2624
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2625
                      atime=atime, mtime=mtime)
2626

    
2627

    
2628
def RunOob(oob_program, command, node, timeout):
2629
  """Executes oob_program with given command on given node.
2630

2631
  @param oob_program: The path to the executable oob_program
2632
  @param command: The command to invoke on oob_program
2633
  @param node: The node given as an argument to the program
2634
  @param timeout: Timeout after which we kill the oob program
2635

2636
  @return: stdout
2637
  @raise RPCFail: If execution fails for some reason
2638

2639
  """
2640
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2641

    
2642
  if result.failed:
2643
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2644
          result.fail_reason, result.output)
2645

    
2646
  return result.stdout
2647

    
2648

    
2649
def _OSOndiskAPIVersion(os_dir):
2650
  """Compute and return the API version of a given OS.
2651

2652
  This function will try to read the API version of the OS residing in
2653
  the 'os_dir' directory.
2654

2655
  @type os_dir: str
2656
  @param os_dir: the directory in which we should look for the OS
2657
  @rtype: tuple
2658
  @return: tuple (status, data) with status denoting the validity and
2659
      data holding either the vaid versions or an error message
2660

2661
  """
2662
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2663

    
2664
  try:
2665
    st = os.stat(api_file)
2666
  except EnvironmentError, err:
2667
    return False, ("Required file '%s' not found under path %s: %s" %
2668
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2669

    
2670
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2671
    return False, ("File '%s' in %s is not a regular file" %
2672
                   (constants.OS_API_FILE, os_dir))
2673

    
2674
  try:
2675
    api_versions = utils.ReadFile(api_file).splitlines()
2676
  except EnvironmentError, err:
2677
    return False, ("Error while reading the API version file at %s: %s" %
2678
                   (api_file, utils.ErrnoOrStr(err)))
2679

    
2680
  try:
2681
    api_versions = [int(version.strip()) for version in api_versions]
2682
  except (TypeError, ValueError), err:
2683
    return False, ("API version(s) can't be converted to integer: %s" %
2684
                   str(err))
2685

    
2686
  return True, api_versions
2687

    
2688

    
2689
def DiagnoseOS(top_dirs=None):
2690
  """Compute the validity for all OSes.
2691

2692
  @type top_dirs: list
2693
  @param top_dirs: the list of directories in which to
2694
      search (if not given defaults to
2695
      L{pathutils.OS_SEARCH_PATH})
2696
  @rtype: list of L{objects.OS}
2697
  @return: a list of tuples (name, path, status, diagnose, variants,
2698
      parameters, api_version) for all (potential) OSes under all
2699
      search paths, where:
2700
          - name is the (potential) OS name
2701
          - path is the full path to the OS
2702
          - status True/False is the validity of the OS
2703
          - diagnose is the error message for an invalid OS, otherwise empty
2704
          - variants is a list of supported OS variants, if any
2705
          - parameters is a list of (name, help) parameters, if any
2706
          - api_version is a list of support OS API versions
2707

2708
  """
2709
  if top_dirs is None:
2710
    top_dirs = pathutils.OS_SEARCH_PATH
2711

    
2712
  result = []
2713
  for dir_name in top_dirs:
2714
    if os.path.isdir(dir_name):
2715
      try:
2716
        f_names = utils.ListVisibleFiles(dir_name)
2717
      except EnvironmentError, err:
2718
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2719
        break
2720
      for name in f_names:
2721
        os_path = utils.PathJoin(dir_name, name)
2722
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2723
        if status:
2724
          diagnose = ""
2725
          variants = os_inst.supported_variants
2726
          parameters = os_inst.supported_parameters
2727
          api_versions = os_inst.api_versions
2728
        else:
2729
          diagnose = os_inst
2730
          variants = parameters = api_versions = []
2731
        result.append((name, os_path, status, diagnose, variants,
2732
                       parameters, api_versions))
2733

    
2734
  return result
2735

    
2736

    
2737
def _TryOSFromDisk(name, base_dir=None):
2738
  """Create an OS instance from disk.
2739

2740
  This function will return an OS instance if the given name is a
2741
  valid OS name.
2742

2743
  @type base_dir: string
2744
  @keyword base_dir: Base directory containing OS installations.
2745
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2746
  @rtype: tuple
2747
  @return: success and either the OS instance if we find a valid one,
2748
      or error message
2749

2750
  """
2751
  if base_dir is None:
2752
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2753
  else:
2754
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2755

    
2756
  if os_dir is None:
2757
    return False, "Directory for OS %s not found in search path" % name
2758

    
2759
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2760
  if not status:
2761
    # push the error up
2762
    return status, api_versions
2763

    
2764
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2765
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2766
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2767

    
2768
  # OS Files dictionary, we will populate it with the absolute path
2769
  # names; if the value is True, then it is a required file, otherwise
2770
  # an optional one
2771
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2772

    
2773
  if max(api_versions) >= constants.OS_API_V15:
2774
    os_files[constants.OS_VARIANTS_FILE] = False
2775

    
2776
  if max(api_versions) >= constants.OS_API_V20:
2777
    os_files[constants.OS_PARAMETERS_FILE] = True
2778
  else:
2779
    del os_files[constants.OS_SCRIPT_VERIFY]
2780

    
2781
  for (filename, required) in os_files.items():
2782
    os_files[filename] = utils.PathJoin(os_dir, filename)
2783

    
2784
    try:
2785
      st = os.stat(os_files[filename])
2786
    except EnvironmentError, err:
2787
      if err.errno == errno.ENOENT and not required:
2788
        del os_files[filename]
2789
        continue
2790
      return False, ("File '%s' under path '%s' is missing (%s)" %
2791
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2792

    
2793
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2794
      return False, ("File '%s' under path '%s' is not a regular file" %
2795
                     (filename, os_dir))
2796

    
2797
    if filename in constants.OS_SCRIPTS:
2798
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2799
        return False, ("File '%s' under path '%s' is not executable" %
2800
                       (filename, os_dir))
2801

    
2802
  variants = []
2803
  if constants.OS_VARIANTS_FILE in os_files:
2804
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2805
    try:
2806
      variants = \
2807
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2808
    except EnvironmentError, err:
2809
      # we accept missing files, but not other errors
2810
      if err.errno != errno.ENOENT:
2811
        return False, ("Error while reading the OS variants file at %s: %s" %
2812
                       (variants_file, utils.ErrnoOrStr(err)))
2813

    
2814
  parameters = []
2815
  if constants.OS_PARAMETERS_FILE in os_files:
2816
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2817
    try:
2818
      parameters = utils.ReadFile(parameters_file).splitlines()
2819
    except EnvironmentError, err:
2820
      return False, ("Error while reading the OS parameters file at %s: %s" %
2821
                     (parameters_file, utils.ErrnoOrStr(err)))
2822
    parameters = [v.split(None, 1) for v in parameters]
2823

    
2824
  os_obj = objects.OS(name=name, path=os_dir,
2825
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2826
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2827
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2828
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2829
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2830
                                                 None),
2831
                      supported_variants=variants,
2832
                      supported_parameters=parameters,
2833
                      api_versions=api_versions)
2834
  return True, os_obj
2835

    
2836

    
2837
def OSFromDisk(name, base_dir=None):
2838
  """Create an OS instance from disk.
2839

2840
  This function will return an OS instance if the given name is a
2841
  valid OS name. Otherwise, it will raise an appropriate
2842
  L{RPCFail} exception, detailing why this is not a valid OS.
2843

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

2847
  @type base_dir: string
2848
  @keyword base_dir: Base directory containing OS installations.
2849
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2850
  @rtype: L{objects.OS}
2851
  @return: the OS instance if we find a valid one
2852
  @raise RPCFail: if we don't find a valid OS
2853

2854
  """
2855
  name_only = objects.OS.GetName(name)
2856
  status, payload = _TryOSFromDisk(name_only, base_dir)
2857

    
2858
  if not status:
2859
    _Fail(payload)
2860

    
2861
  return payload
2862

    
2863

    
2864
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2865
  """Calculate the basic environment for an os script.
2866

2867
  @type os_name: str
2868
  @param os_name: full operating system name (including variant)
2869
  @type inst_os: L{objects.OS}
2870
  @param inst_os: operating system for which the environment is being built
2871
  @type os_params: dict
2872
  @param os_params: the OS parameters
2873
  @type debug: integer
2874
  @param debug: debug level (0 or 1, for OS Api 10)
2875
  @rtype: dict
2876
  @return: dict of environment variables
2877
  @raise errors.BlockDeviceError: if the block device
2878
      cannot be found
2879

2880
  """
2881
  result = {}
2882
  api_version = \
2883
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2884
  result["OS_API_VERSION"] = "%d" % api_version
2885
  result["OS_NAME"] = inst_os.name
2886
  result["DEBUG_LEVEL"] = "%d" % debug
2887

    
2888
  # OS variants
2889
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2890
    variant = objects.OS.GetVariant(os_name)
2891
    if not variant:
2892
      variant = inst_os.supported_variants[0]
2893
  else:
2894
    variant = ""
2895
  result["OS_VARIANT"] = variant
2896

    
2897
  # OS params
2898
  for pname, pvalue in os_params.items():
2899
    result["OSP_%s" % pname.upper()] = pvalue
2900

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

    
2906
  return result
2907

    
2908

    
2909
def OSEnvironment(instance, inst_os, debug=0):
2910
  """Calculate the environment for an os script.
2911

2912
  @type instance: L{objects.Instance}
2913
  @param instance: target instance for the os script run
2914
  @type inst_os: L{objects.OS}
2915
  @param inst_os: operating system for which the environment is being built
2916
  @type debug: integer
2917
  @param debug: debug level (0 or 1, for OS Api 10)
2918
  @rtype: dict
2919
  @return: dict of environment variables
2920
  @raise errors.BlockDeviceError: if the block device
2921
      cannot be found
2922

2923
  """
2924
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2925

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

    
2929
  result["HYPERVISOR"] = instance.hypervisor
2930
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2931
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2932
  result["INSTANCE_SECONDARY_NODES"] = \
2933
      ("%s" % " ".join(instance.secondary_nodes))
2934

    
2935
  # Disks
2936
  for idx, disk in enumerate(instance.disks):
2937
    real_disk = _OpenRealBD(disk)
2938
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2939
    result["DISK_%d_ACCESS" % idx] = disk.mode
2940
    result["DISK_%d_UUID" % idx] = disk.uuid
2941
    if disk.name:
2942
      result["DISK_%d_NAME" % idx] = disk.name
2943
    if constants.HV_DISK_TYPE in instance.hvparams:
2944
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2945
        instance.hvparams[constants.HV_DISK_TYPE]
2946
    if disk.dev_type in constants.DTS_BLOCK:
2947
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2948
    elif disk.dev_type in [constants.DT_FILE, constants.DT_SHARED_FILE]:
2949
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2950
        "file:%s" % disk.logical_id[0]
2951

    
2952
  # NICs
2953
  for idx, nic in enumerate(instance.nics):
2954
    result["NIC_%d_MAC" % idx] = nic.mac
2955
    result["NIC_%d_UUID" % idx] = nic.uuid
2956
    if nic.name:
2957
      result["NIC_%d_NAME" % idx] = nic.name
2958
    if nic.ip:
2959
      result["NIC_%d_IP" % idx] = nic.ip
2960
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2961
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2962
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2963
    if nic.nicparams[constants.NIC_LINK]:
2964
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2965
    if nic.netinfo:
2966
      nobj = objects.Network.FromDict(nic.netinfo)
2967
      result.update(nobj.HooksDict("NIC_%d_" % idx))
2968
    if constants.HV_NIC_TYPE in instance.hvparams:
2969
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2970
        instance.hvparams[constants.HV_NIC_TYPE]
2971

    
2972
  # HV/BE params
2973
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2974
    for key, value in source.items():
2975
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2976

    
2977
  return result
2978

    
2979

    
2980
def DiagnoseExtStorage(top_dirs=None):
2981
  """Compute the validity for all ExtStorage Providers.
2982

2983
  @type top_dirs: list
2984
  @param top_dirs: the list of directories in which to
2985
      search (if not given defaults to
2986
      L{pathutils.ES_SEARCH_PATH})
2987
  @rtype: list of L{objects.ExtStorage}
2988
  @return: a list of tuples (name, path, status, diagnose, parameters)
2989
      for all (potential) ExtStorage Providers under all
2990
      search paths, where:
2991
          - name is the (potential) ExtStorage Provider
2992
          - path is the full path to the ExtStorage Provider
2993
          - status True/False is the validity of the ExtStorage Provider
2994
          - diagnose is the error message for an invalid ExtStorage Provider,
2995
            otherwise empty
2996
          - parameters is a list of (name, help) parameters, if any
2997

2998
  """
2999
  if top_dirs is None:
3000
    top_dirs = pathutils.ES_SEARCH_PATH
3001

    
3002
  result = []
3003
  for dir_name in top_dirs:
3004
    if os.path.isdir(dir_name):
3005
      try:
3006
        f_names = utils.ListVisibleFiles(dir_name)
3007
      except EnvironmentError, err:
3008
        logging.exception("Can't list the ExtStorage directory %s: %s",
3009
                          dir_name, err)
3010
        break
3011
      for name in f_names:
3012
        es_path = utils.PathJoin(dir_name, name)
3013
        status, es_inst = extstorage.ExtStorageFromDisk(name, base_dir=dir_name)
3014
        if status:
3015
          diagnose = ""
3016
          parameters = es_inst.supported_parameters
3017
        else:
3018
          diagnose = es_inst
3019
          parameters = []
3020
        result.append((name, es_path, status, diagnose, parameters))
3021

    
3022
  return result
3023

    
3024

    
3025
def BlockdevGrow(disk, amount, dryrun, backingstore, excl_stor):
3026
  """Grow a stack of block devices.
3027

3028
  This function is called recursively, with the childrens being the
3029
  first ones to resize.
3030

3031
  @type disk: L{objects.Disk}
3032
  @param disk: the disk to be grown
3033
  @type amount: integer
3034
  @param amount: the amount (in mebibytes) to grow with
3035
  @type dryrun: boolean
3036
  @param dryrun: whether to execute the operation in simulation mode
3037
      only, without actually increasing the size
3038
  @param backingstore: whether to execute the operation on backing storage
3039
      only, or on "logical" storage only; e.g. DRBD is logical storage,
3040
      whereas LVM, file, RBD are backing storage
3041
  @rtype: (status, result)
3042
  @type excl_stor: boolean
3043
  @param excl_stor: Whether exclusive_storage is active
3044
  @return: a tuple with the status of the operation (True/False), and
3045
      the errors message if status is False
3046

3047
  """
3048
  r_dev = _RecursiveFindBD(disk)
3049
  if r_dev is None:
3050
    _Fail("Cannot find block device %s", disk)
3051

    
3052
  try:
3053
    r_dev.Grow(amount, dryrun, backingstore, excl_stor)
3054
  except errors.BlockDeviceError, err:
3055
    _Fail("Failed to grow block device: %s", err, exc=True)
3056

    
3057

    
3058
def BlockdevSnapshot(disk, snap_name, snap_size):
3059
  """Create a snapshot copy of a block device.
3060

3061
  This function is called recursively, and the snapshot is actually created
3062
  just for the leaf lvm backend device.
3063

3064
  @type disk: L{objects.Disk}
3065
  @param disk: the disk to be snapshotted
3066
  @type snap_name: string
3067
  @param snap_name: the name of the snapshot
3068
  @type snap_size: int
3069
  @param snap_size: the size of the snapshot
3070
  @rtype: string
3071
  @return: snapshot disk ID as (vg, lv)
3072

3073
  """
3074
  def _DiskSnapshot(disk, snap_name=None, snap_size=None):
3075
    r_dev = _RecursiveFindBD(disk)
3076
    if r_dev is not None:
3077
      return r_dev.Snapshot(snap_name=snap_name, snap_size=snap_size)
3078
    else:
3079
      _Fail("Cannot find block device %s", disk)
3080

    
3081
  if disk.dev_type == constants.DT_DRBD8:
3082
    if not disk.children:
3083
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
3084
            disk.unique_id)
3085
    return BlockdevSnapshot(disk.children[0], snap_name, snap_size)
3086
  elif disk.dev_type == constants.DT_PLAIN:
3087
    return _DiskSnapshot(disk, snap_name, snap_size)
3088
  elif disk.dev_type == constants.DT_EXT:
3089
    return _DiskSnapshot(disk, snap_name, snap_size)
3090
  else:
3091
    _Fail("Cannot snapshot block device '%s' of type '%s'",
3092
          disk.logical_id, disk.dev_type)
3093

    
3094

    
3095
def BlockdevSetInfo(disk, info):
3096
  """Sets 'metadata' information on block devices.
3097

3098
  This function sets 'info' metadata on block devices. Initial
3099
  information is set at device creation; this function should be used
3100
  for example after renames.
3101

3102
  @type disk: L{objects.Disk}
3103
  @param disk: the disk to be grown
3104
  @type info: string
3105
  @param info: new 'info' metadata
3106
  @rtype: (status, result)
3107
  @return: a tuple with the status of the operation (True/False), and
3108
      the errors message if status is False
3109

3110
  """
3111
  r_dev = _RecursiveFindBD(disk)
3112
  if r_dev is None:
3113
    _Fail("Cannot find block device %s", disk)
3114

    
3115
  try:
3116
    r_dev.SetInfo(info)
3117
  except errors.BlockDeviceError, err:
3118
    _Fail("Failed to set information on block device: %s", err, exc=True)
3119

    
3120

    
3121
def FinalizeExport(instance, snap_disks):
3122
  """Write out the export configuration information.
3123

3124
  @type instance: L{objects.Instance}
3125
  @param instance: the instance which we export, used for
3126
      saving configuration
3127
  @type snap_disks: list of L{objects.Disk}
3128
  @param snap_disks: list of snapshot block devices, which
3129
      will be used to get the actual name of the dump file
3130

3131
  @rtype: None
3132

3133
  """
3134
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
3135
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
3136

    
3137
  config = objects.SerializableConfigParser()
3138

    
3139
  config.add_section(constants.INISECT_EXP)
3140
  config.set(constants.INISECT_EXP, "version", "0")
3141
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
3142
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
3143
  config.set(constants.INISECT_EXP, "os", instance.os)
3144
  config.set(constants.INISECT_EXP, "compression", "none")
3145

    
3146
  config.add_section(constants.INISECT_INS)
3147
  config.set(constants.INISECT_INS, "name", instance.name)
3148
  config.set(constants.INISECT_INS, "maxmem", "%d" %
3149
             instance.beparams[constants.BE_MAXMEM])
3150
  config.set(constants.INISECT_INS, "minmem", "%d" %
3151
             instance.beparams[constants.BE_MINMEM])
3152
  # "memory" is deprecated, but useful for exporting to old ganeti versions
3153
  config.set(constants.INISECT_INS, "memory", "%d" %
3154
             instance.beparams[constants.BE_MAXMEM])
3155
  config.set(constants.INISECT_INS, "vcpus", "%d" %
3156
             instance.beparams[constants.BE_VCPUS])
3157
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
3158
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
3159
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
3160

    
3161
  nic_total = 0
3162
  for nic_count, nic in enumerate(instance.nics):
3163
    nic_total += 1
3164
    config.set(constants.INISECT_INS, "nic%d_mac" %
3165
               nic_count, "%s" % nic.mac)
3166
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
3167
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
3168
               "%s" % nic.network)
3169
    config.set(constants.INISECT_INS, "nic%d_name" % nic_count,
3170
               "%s" % nic.name)
3171
    for param in constants.NICS_PARAMETER_TYPES:
3172
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
3173
                 "%s" % nic.nicparams.get(param, None))
3174
  # TODO: redundant: on load can read nics until it doesn't exist
3175
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
3176

    
3177
  disk_total = 0
3178
  for disk_count, disk in enumerate(snap_disks):
3179
    if disk:
3180
      disk_total += 1
3181
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
3182
                 ("%s" % disk.iv_name))
3183
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
3184
                 ("%s" % disk.logical_id[1]))
3185
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
3186
                 ("%d" % disk.size))
3187
      config.set(constants.INISECT_INS, "disk%d_name" % disk_count,
3188
                 "%s" % disk.name)
3189

    
3190
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
3191

    
3192
  # New-style hypervisor/backend parameters
3193

    
3194
  config.add_section(constants.INISECT_HYP)
3195
  for name, value in instance.hvparams.items():
3196
    if name not in constants.HVC_GLOBALS:
3197
      config.set(constants.INISECT_HYP, name, str(value))
3198

    
3199
  config.add_section(constants.INISECT_BEP)
3200
  for name, value in instance.beparams.items():
3201
    config.set(constants.INISECT_BEP, name, str(value))
3202

    
3203
  config.add_section(constants.INISECT_OSP)
3204
  for name, value in instance.osparams.items():
3205
    config.set(constants.INISECT_OSP, name, str(value))
3206

    
3207
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
3208
                  data=config.Dumps())
3209
  shutil.rmtree(finaldestdir, ignore_errors=True)
3210
  shutil.move(destdir, finaldestdir)
3211

    
3212

    
3213
def ExportInfo(dest):
3214
  """Get export configuration information.
3215

3216
  @type dest: str
3217
  @param dest: directory containing the export
3218

3219
  @rtype: L{objects.SerializableConfigParser}
3220
  @return: a serializable config file containing the
3221
      export info
3222

3223
  """
3224
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
3225

    
3226
  config = objects.SerializableConfigParser()
3227
  config.read(cff)
3228

    
3229
  if (not config.has_section(constants.INISECT_EXP) or
3230
      not config.has_section(constants.INISECT_INS)):
3231
    _Fail("Export info file doesn't have the required fields")
3232

    
3233
  return config.Dumps()
3234

    
3235

    
3236
def ListExports():
3237
  """Return a list of exports currently available on this machine.
3238

3239
  @rtype: list
3240
  @return: list of the exports
3241

3242
  """
3243
  if os.path.isdir(pathutils.EXPORT_DIR):
3244
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
3245
  else:
3246
    _Fail("No exports directory")
3247

    
3248

    
3249
def RemoveExport(export):
3250
  """Remove an existing export from the node.
3251

3252
  @type export: str
3253
  @param export: the name of the export to remove
3254
  @rtype: None
3255

3256
  """
3257
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
3258

    
3259
  try:
3260
    shutil.rmtree(target)
3261
  except EnvironmentError, err:
3262
    _Fail("Error while removing the export: %s", err, exc=True)
3263

    
3264

    
3265
def BlockdevRename(devlist):
3266
  """Rename a list of block devices.
3267

3268
  @type devlist: list of tuples
3269
  @param devlist: list of tuples of the form  (disk, new_unique_id); disk is
3270
      an L{objects.Disk} object describing the current disk, and new
3271
      unique_id is the name we rename it to
3272
  @rtype: boolean
3273
  @return: True if all renames succeeded, False otherwise
3274

3275
  """
3276
  msgs = []
3277
  result = True
3278
  for disk, unique_id in devlist:
3279
    dev = _RecursiveFindBD(disk)
3280
    if dev is None:
3281
      msgs.append("Can't find device %s in rename" % str(disk))
3282
      result = False
3283
      continue
3284
    try:
3285
      old_rpath = dev.dev_path
3286
      dev.Rename(unique_id)
3287
      new_rpath = dev.dev_path
3288
      if old_rpath != new_rpath:
3289
        DevCacheManager.RemoveCache(old_rpath)
3290
        # FIXME: we should add the new cache information here, like:
3291
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
3292
        # but we don't have the owner here - maybe parse from existing
3293
        # cache? for now, we only lose lvm data when we rename, which
3294
        # is less critical than DRBD or MD
3295
    except errors.BlockDeviceError, err:
3296
      msgs.append("Can't rename device '%s' to '%s': %s" %
3297
                  (dev, unique_id, err))
3298
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
3299
      result = False
3300
  if not result:
3301
    _Fail("; ".join(msgs))
3302

    
3303

    
3304
def _TransformFileStorageDir(fs_dir):
3305
  """Checks whether given file_storage_dir is valid.
3306

3307
  Checks wheter the given fs_dir is within the cluster-wide default
3308
  file_storage_dir or the shared_file_storage_dir, which are stored in
3309
  SimpleStore. Only paths under those directories are allowed.
3310

3311
  @type fs_dir: str
3312
  @param fs_dir: the path to check
3313

3314
  @return: the normalized path if valid, None otherwise
3315

3316
  """
3317
  filestorage.CheckFileStoragePath(fs_dir)
3318

    
3319
  return os.path.normpath(fs_dir)
3320

    
3321

    
3322
def CreateFileStorageDir(file_storage_dir):
3323
  """Create file storage directory.
3324

3325
  @type file_storage_dir: str
3326
  @param file_storage_dir: directory to create
3327

3328
  @rtype: tuple
3329
  @return: tuple with first element a boolean indicating wheter dir
3330
      creation was successful or not
3331

3332
  """
3333
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3334
  if os.path.exists(file_storage_dir):
3335
    if not os.path.isdir(file_storage_dir):
3336
      _Fail("Specified storage dir '%s' is not a directory",
3337
            file_storage_dir)
3338
  else:
3339
    try:
3340
      os.makedirs(file_storage_dir, 0750)
3341
    except OSError, err:
3342
      _Fail("Cannot create file storage directory '%s': %s",
3343
            file_storage_dir, err, exc=True)
3344

    
3345

    
3346
def RemoveFileStorageDir(file_storage_dir):
3347
  """Remove file storage directory.
3348

3349
  Remove it only if it's empty. If not log an error and return.
3350

3351
  @type file_storage_dir: str
3352
  @param file_storage_dir: the directory we should cleanup
3353
  @rtype: tuple (success,)
3354
  @return: tuple of one element, C{success}, denoting
3355
      whether the operation was successful
3356

3357
  """
3358
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3359
  if os.path.exists(file_storage_dir):
3360
    if not os.path.isdir(file_storage_dir):
3361
      _Fail("Specified Storage directory '%s' is not a directory",
3362
            file_storage_dir)
3363
    # deletes dir only if empty, otherwise we want to fail the rpc call
3364
    try:
3365
      os.rmdir(file_storage_dir)
3366
    except OSError, err:
3367
      _Fail("Cannot remove file storage directory '%s': %s",
3368
            file_storage_dir, err)
3369

    
3370

    
3371
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
3372
  """Rename the file storage directory.
3373

3374
  @type old_file_storage_dir: str
3375
  @param old_file_storage_dir: the current path
3376
  @type new_file_storage_dir: str
3377
  @param new_file_storage_dir: the name we should rename to
3378
  @rtype: tuple (success,)
3379
  @return: tuple of one element, C{success}, denoting
3380
      whether the operation was successful
3381

3382
  """
3383
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
3384
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
3385
  if not os.path.exists(new_file_storage_dir):
3386
    if os.path.isdir(old_file_storage_dir):
3387
      try:
3388
        os.rename(old_file_storage_dir, new_file_storage_dir)
3389
      except OSError, err:
3390
        _Fail("Cannot rename '%s' to '%s': %s",
3391
              old_file_storage_dir, new_file_storage_dir, err)
3392
    else:
3393
      _Fail("Specified storage dir '%s' is not a directory",
3394
            old_file_storage_dir)
3395
  else:
3396
    if os.path.exists(old_file_storage_dir):
3397
      _Fail("Cannot rename '%s' to '%s': both locations exist",
3398
            old_file_storage_dir, new_file_storage_dir)
3399

    
3400

    
3401
def _EnsureJobQueueFile(file_name):
3402
  """Checks whether the given filename is in the queue directory.
3403

3404
  @type file_name: str
3405
  @param file_name: the file name we should check
3406
  @rtype: None
3407
  @raises RPCFail: if the file is not valid
3408

3409
  """
3410
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
3411
    _Fail("Passed job queue file '%s' does not belong to"
3412
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
3413

    
3414

    
3415
def JobQueueUpdate(file_name, content):
3416
  """Updates a file in the queue directory.
3417

3418
  This is just a wrapper over L{utils.io.WriteFile}, with proper
3419
  checking.
3420

3421
  @type file_name: str
3422
  @param file_name: the job file name
3423
  @type content: str
3424
  @param content: the new job contents
3425
  @rtype: boolean
3426
  @return: the success of the operation
3427

3428
  """
3429
  file_name = vcluster.LocalizeVirtualPath(file_name)
3430

    
3431
  _EnsureJobQueueFile(file_name)
3432
  getents = runtime.GetEnts()
3433

    
3434
  # Write and replace the file atomically
3435
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3436
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3437

    
3438

    
3439
def JobQueueRename(old, new):
3440
  """Renames a job queue file.
3441

3442
  This is just a wrapper over os.rename with proper checking.
3443

3444
  @type old: str
3445
  @param old: the old (actual) file name
3446
  @type new: str
3447
  @param new: the desired file name
3448
  @rtype: tuple
3449
  @return: the success of the operation and payload
3450

3451
  """
3452
  old = vcluster.LocalizeVirtualPath(old)
3453
  new = vcluster.LocalizeVirtualPath(new)
3454

    
3455
  _EnsureJobQueueFile(old)
3456
  _EnsureJobQueueFile(new)
3457

    
3458
  getents = runtime.GetEnts()
3459

    
3460
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3461
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3462

    
3463

    
3464
def BlockdevClose(instance_name, disks):
3465
  """Closes the given block devices.
3466

3467
  This means they will be switched to secondary mode (in case of
3468
  DRBD).
3469

3470
  @param instance_name: if the argument is not empty, the symlinks
3471
      of this instance will be removed
3472
  @type disks: list of L{objects.Disk}
3473
  @param disks: the list of disks to be closed
3474
  @rtype: tuple (success, message)
3475
  @return: a tuple of success and message, where success
3476
      indicates the succes of the operation, and message
3477
      which will contain the error details in case we
3478
      failed
3479

3480
  """
3481
  bdevs = []
3482
  for cf in disks:
3483
    rd = _RecursiveFindBD(cf)
3484
    if rd is None:
3485
      _Fail("Can't find device %s", cf)
3486
    bdevs.append(rd)
3487

    
3488
  msg = []
3489
  for rd in bdevs:
3490
    try:
3491
      rd.Close()
3492
    except errors.BlockDeviceError, err:
3493
      msg.append(str(err))
3494
  if msg:
3495
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3496
  else:
3497
    if instance_name:
3498
      _RemoveBlockDevLinks(instance_name, disks)
3499

    
3500

    
3501
def ValidateHVParams(hvname, hvparams):
3502
  """Validates the given hypervisor parameters.
3503

3504
  @type hvname: string
3505
  @param hvname: the hypervisor name
3506
  @type hvparams: dict
3507
  @param hvparams: the hypervisor parameters to be validated
3508
  @rtype: None
3509

3510
  """
3511
  try:
3512
    hv_type = hypervisor.GetHypervisor(hvname)
3513
    hv_type.ValidateParameters(hvparams)
3514
  except errors.HypervisorError, err:
3515
    _Fail(str(err), log=False)
3516

    
3517

    
3518
def _CheckOSPList(os_obj, parameters):
3519
  """Check whether a list of parameters is supported by the OS.
3520

3521
  @type os_obj: L{objects.OS}
3522
  @param os_obj: OS object to check
3523
  @type parameters: list
3524
  @param parameters: the list of parameters to check
3525

3526
  """
3527
  supported = [v[0] for v in os_obj.supported_parameters]
3528
  delta = frozenset(parameters).difference(supported)
3529
  if delta:
3530
    _Fail("The following parameters are not supported"
3531
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3532

    
3533

    
3534
def ValidateOS(required, osname, checks, osparams):
3535
  """Validate the given OS' parameters.
3536

3537
  @type required: boolean
3538
  @param required: whether absence of the OS should translate into
3539
      failure or not
3540
  @type osname: string
3541
  @param osname: the OS to be validated
3542
  @type checks: list
3543
  @param checks: list of the checks to run (currently only 'parameters')
3544
  @type osparams: dict
3545
  @param osparams: dictionary with OS parameters
3546
  @rtype: boolean
3547
  @return: True if the validation passed, or False if the OS was not
3548
      found and L{required} was false
3549

3550
  """
3551
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3552
    _Fail("Unknown checks required for OS %s: %s", osname,
3553
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3554

    
3555
  name_only = objects.OS.GetName(osname)
3556
  status, tbv = _TryOSFromDisk(name_only, None)
3557

    
3558
  if not status:
3559
    if required:
3560
      _Fail(tbv)
3561
    else:
3562
      return False
3563

    
3564
  if max(tbv.api_versions) < constants.OS_API_V20:
3565
    return True
3566

    
3567
  if constants.OS_VALIDATE_PARAMETERS in checks:
3568
    _CheckOSPList(tbv, osparams.keys())
3569

    
3570
  validate_env = OSCoreEnv(osname, tbv, osparams)
3571
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3572
                        cwd=tbv.path, reset_env=True)
3573
  if result.failed:
3574
    logging.error("os validate command '%s' returned error: %s output: %s",
3575
                  result.cmd, result.fail_reason, result.output)
3576
    _Fail("OS validation script failed (%s), output: %s",
3577
          result.fail_reason, result.output, log=False)
3578

    
3579
  return True
3580

    
3581

    
3582
def DemoteFromMC():
3583
  """Demotes the current node from master candidate role.
3584

3585
  """
3586
  # try to ensure we're not the master by mistake
3587
  master, myself = ssconf.GetMasterAndMyself()
3588
  if master == myself:
3589
    _Fail("ssconf status shows I'm the master node, will not demote")
3590

    
3591
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3592
  if not result.failed:
3593
    _Fail("The master daemon is running, will not demote")
3594

    
3595
  try:
3596
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3597
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3598
  except EnvironmentError, err:
3599
    if err.errno != errno.ENOENT:
3600
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3601

    
3602
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3603

    
3604

    
3605
def _GetX509Filenames(cryptodir, name):
3606
  """Returns the full paths for the private key and certificate.
3607

3608
  """
3609
  return (utils.PathJoin(cryptodir, name),
3610
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3611
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3612

    
3613

    
3614
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3615
  """Creates a new X509 certificate for SSL/TLS.
3616

3617
  @type validity: int
3618
  @param validity: Validity in seconds
3619
  @rtype: tuple; (string, string)
3620
  @return: Certificate name and public part
3621

3622
  """
3623
  (key_pem, cert_pem) = \
3624
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3625
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3626

    
3627
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3628
                              prefix="x509-%s-" % utils.TimestampForFilename())
3629
  try:
3630
    name = os.path.basename(cert_dir)
3631
    assert len(name) > 5
3632

    
3633
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3634

    
3635
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3636
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3637

    
3638
    # Never return private key as it shouldn't leave the node
3639
    return (name, cert_pem)
3640
  except Exception:
3641
    shutil.rmtree(cert_dir, ignore_errors=True)
3642
    raise
3643

    
3644

    
3645
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3646
  """Removes a X509 certificate.
3647

3648
  @type name: string
3649
  @param name: Certificate name
3650

3651
  """
3652
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3653

    
3654
  utils.RemoveFile(key_file)
3655
  utils.RemoveFile(cert_file)
3656

    
3657
  try:
3658
    os.rmdir(cert_dir)
3659
  except EnvironmentError, err:
3660
    _Fail("Cannot remove certificate directory '%s': %s",
3661
          cert_dir, err)
3662

    
3663

    
3664
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3665
  """Returns the command for the requested input/output.
3666

3667
  @type instance: L{objects.Instance}
3668
  @param instance: The instance object
3669
  @param mode: Import/export mode
3670
  @param ieio: Input/output type
3671
  @param ieargs: Input/output arguments
3672

3673
  """
3674
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3675

    
3676
  env = None
3677
  prefix = None
3678
  suffix = None
3679
  exp_size = None
3680

    
3681
  if ieio == constants.IEIO_FILE:
3682
    (filename, ) = ieargs
3683

    
3684
    if not utils.IsNormAbsPath(filename):
3685
      _Fail("Path '%s' is not normalized or absolute", filename)
3686

    
3687
    real_filename = os.path.realpath(filename)
3688
    directory = os.path.dirname(real_filename)
3689

    
3690
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3691
      _Fail("File '%s' is not under exports directory '%s': %s",
3692
            filename, pathutils.EXPORT_DIR, real_filename)
3693

    
3694
    # Create directory
3695
    utils.Makedirs(directory, mode=0750)
3696

    
3697
    quoted_filename = utils.ShellQuote(filename)
3698

    
3699
    if mode == constants.IEM_IMPORT:
3700
      suffix = "> %s" % quoted_filename
3701
    elif mode == constants.IEM_EXPORT:
3702
      suffix = "< %s" % quoted_filename
3703

    
3704
      # Retrieve file size
3705
      try:
3706
        st = os.stat(filename)
3707
      except EnvironmentError, err:
3708
        logging.error("Can't stat(2) %s: %s", filename, err)
3709
      else:
3710
        exp_size = utils.BytesToMebibyte(st.st_size)
3711

    
3712
  elif ieio == constants.IEIO_RAW_DISK:
3713
    (disk, ) = ieargs
3714

    
3715
    real_disk = _OpenRealBD(disk)
3716

    
3717
    if mode == constants.IEM_IMPORT:
3718
      # we set here a smaller block size as, due to transport buffering, more
3719
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3720
      # is not already there or we pass a wrong path; we use notrunc to no
3721
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3722
      # much memory; this means that at best, we flush every 64k, which will
3723
      # not be very fast
3724
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3725
                                    " bs=%s oflag=dsync"),
3726
                                    real_disk.dev_path,
3727
                                    str(64 * 1024))
3728

    
3729
    elif mode == constants.IEM_EXPORT:
3730
      # the block size on the read dd is 1MiB to match our units
3731
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3732
                                   real_disk.dev_path,
3733
                                   str(1024 * 1024), # 1 MB
3734
                                   str(disk.size))
3735
      exp_size = disk.size
3736

    
3737
  elif ieio == constants.IEIO_SCRIPT:
3738
    (disk, disk_index, ) = ieargs
3739

    
3740
    assert isinstance(disk_index, (int, long))
3741

    
3742
    inst_os = OSFromDisk(instance.os)
3743
    env = OSEnvironment(instance, inst_os)
3744

    
3745
    if mode == constants.IEM_IMPORT:
3746
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3747
      env["IMPORT_INDEX"] = str(disk_index)
3748
      script = inst_os.import_script
3749

    
3750
    elif mode == constants.IEM_EXPORT:
3751
      real_disk = _OpenRealBD(disk)
3752
      env["EXPORT_DEVICE"] = real_disk.dev_path
3753
      env["EXPORT_INDEX"] = str(disk_index)
3754
      script = inst_os.export_script
3755

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

    
3759
    if mode == constants.IEM_IMPORT:
3760
      suffix = "| %s" % script_cmd
3761

    
3762
    elif mode == constants.IEM_EXPORT:
3763
      prefix = "%s |" % script_cmd
3764

    
3765
    # Let script predict size
3766
    exp_size = constants.IE_CUSTOM_SIZE
3767

    
3768
  else:
3769
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3770

    
3771
  return (env, prefix, suffix, exp_size)
3772

    
3773

    
3774
def _CreateImportExportStatusDir(prefix):
3775
  """Creates status directory for import/export.
3776

3777
  """
3778
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3779
                          prefix=("%s-%s-" %
3780
                                  (prefix, utils.TimestampForFilename())))
3781

    
3782

    
3783
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3784
                            ieio, ieioargs):
3785
  """Starts an import or export daemon.
3786

3787
  @param mode: Import/output mode
3788
  @type opts: L{objects.ImportExportOptions}
3789
  @param opts: Daemon options
3790
  @type host: string
3791
  @param host: Remote host for export (None for import)
3792
  @type port: int
3793
  @param port: Remote port for export (None for import)
3794
  @type instance: L{objects.Instance}
3795
  @param instance: Instance object
3796
  @type component: string
3797
  @param component: which part of the instance is transferred now,
3798
      e.g. 'disk/0'
3799
  @param ieio: Input/output type
3800
  @param ieioargs: Input/output arguments
3801

3802
  """
3803
  if mode == constants.IEM_IMPORT:
3804
    prefix = "import"
3805

    
3806
    if not (host is None and port is None):
3807
      _Fail("Can not specify host or port on import")
3808

    
3809
  elif mode == constants.IEM_EXPORT:
3810
    prefix = "export"
3811

    
3812
    if host is None or port is None:
3813
      _Fail("Host and port must be specified for an export")
3814

    
3815
  else:
3816
    _Fail("Invalid mode %r", mode)
3817

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

    
3821
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3822
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3823

    
3824
  if opts.key_name is None:
3825
    # Use server.pem
3826
    key_path = pathutils.NODED_CERT_FILE
3827
    cert_path = pathutils.NODED_CERT_FILE
3828
    assert opts.ca_pem is None
3829
  else:
3830
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3831
                                                 opts.key_name)
3832
    assert opts.ca_pem is not None
3833

    
3834
  for i in [key_path, cert_path]:
3835
    if not os.path.exists(i):
3836
      _Fail("File '%s' does not exist" % i)
3837

    
3838
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3839
  try:
3840
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3841
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3842
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3843

    
3844
    if opts.ca_pem is None:
3845
      # Use server.pem
3846
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3847
    else:
3848
      ca = opts.ca_pem
3849

    
3850
    # Write CA file
3851
    utils.WriteFile(ca_file, data=ca, mode=0400)
3852

    
3853
    cmd = [
3854
      pathutils.IMPORT_EXPORT_DAEMON,
3855
      status_file, mode,
3856
      "--key=%s" % key_path,
3857
      "--cert=%s" % cert_path,
3858
      "--ca=%s" % ca_file,
3859
      ]
3860

    
3861
    if host:
3862
      cmd.append("--host=%s" % host)
3863

    
3864
    if port:
3865
      cmd.append("--port=%s" % port)
3866

    
3867
    if opts.ipv6:
3868
      cmd.append("--ipv6")
3869
    else:
3870
      cmd.append("--ipv4")
3871

    
3872
    if opts.compress:
3873
      cmd.append("--compress=%s" % opts.compress)
3874

    
3875
    if opts.magic:
3876
      cmd.append("--magic=%s" % opts.magic)
3877

    
3878
    if exp_size is not None:
3879
      cmd.append("--expected-size=%s" % exp_size)
3880

    
3881
    if cmd_prefix:
3882
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3883

    
3884
    if cmd_suffix:
3885
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3886

    
3887
    if mode == constants.IEM_EXPORT:
3888
      # Retry connection a few times when connecting to remote peer
3889
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3890
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3891
    elif opts.connect_timeout is not None:
3892
      assert mode == constants.IEM_IMPORT
3893
      # Overall timeout for establishing connection while listening
3894
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3895

    
3896
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3897

    
3898
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3899
    # support for receiving a file descriptor for output
3900
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3901
                      output=logfile)
3902

    
3903
    # The import/export name is simply the status directory name
3904
    return os.path.basename(status_dir)
3905

    
3906
  except Exception:
3907
    shutil.rmtree(status_dir, ignore_errors=True)
3908
    raise
3909

    
3910

    
3911
def GetImportExportStatus(names):
3912
  """Returns import/export daemon status.
3913

3914
  @type names: sequence
3915
  @param names: List of names
3916
  @rtype: List of dicts
3917
  @return: Returns a list of the state of each named import/export or None if a
3918
           status couldn't be read
3919

3920
  """
3921
  result = []
3922

    
3923
  for name in names:
3924
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3925
                                 _IES_STATUS_FILE)
3926

    
3927
    try:
3928
      data = utils.ReadFile(status_file)
3929
    except EnvironmentError, err:
3930
      if err.errno != errno.ENOENT:
3931
        raise
3932
      data = None
3933

    
3934
    if not data:
3935
      result.append(None)
3936
      continue
3937

    
3938
    result.append(serializer.LoadJson(data))
3939

    
3940
  return result
3941

    
3942

    
3943
def AbortImportExport(name):
3944
  """Sends SIGTERM to a running import/export daemon.
3945

3946
  """
3947
  logging.info("Abort import/export %s", name)
3948

    
3949
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3950
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3951

    
3952
  if pid:
3953
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3954
                 name, pid)
3955
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3956

    
3957

    
3958
def CleanupImportExport(name):
3959
  """Cleanup after an import or export.
3960

3961
  If the import/export daemon is still running it's killed. Afterwards the
3962
  whole status directory is removed.
3963

3964
  """
3965
  logging.info("Finalizing import/export %s", name)
3966

    
3967
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3968

    
3969
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3970

    
3971
  if pid:
3972
    logging.info("Import/export %s is still running with PID %s",
3973
                 name, pid)
3974
    utils.KillProcess(pid, waitpid=False)
3975

    
3976
  shutil.rmtree(status_dir, ignore_errors=True)
3977

    
3978

    
3979
def _FindDisks(disks):
3980
  """Finds attached L{BlockDev}s for the given disks.
3981

3982
  @type disks: list of L{objects.Disk}
3983
  @param disks: the disk objects we need to find
3984

3985
  @return: list of L{BlockDev} objects or C{None} if a given disk
3986
           was not found or was no attached.
3987

3988
  """
3989
  bdevs = []
3990

    
3991
  for disk in disks:
3992
    rd = _RecursiveFindBD(disk)
3993
    if rd is None:
3994
      _Fail("Can't find device %s", disk)
3995
    bdevs.append(rd)
3996
  return bdevs
3997

    
3998

    
3999
def DrbdDisconnectNet(disks):
4000
  """Disconnects the network on a list of drbd devices.
4001

4002
  """
4003
  bdevs = _FindDisks(disks)
4004

    
4005
  # disconnect disks
4006
  for rd in bdevs:
4007
    try:
4008
      rd.DisconnectNet()
4009
    except errors.BlockDeviceError, err:
4010
      _Fail("Can't change network configuration to standalone mode: %s",
4011
            err, exc=True)
4012

    
4013

    
4014
def DrbdAttachNet(disks, instance_name, multimaster):
4015
  """Attaches the network on a list of drbd devices.
4016

4017
  """
4018
  bdevs = _FindDisks(disks)
4019

    
4020
  if multimaster:
4021
    for idx, rd in enumerate(bdevs):
4022
      try:
4023
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
4024
      except EnvironmentError, err:
4025
        _Fail("Can't create symlink: %s", err)
4026
  # reconnect disks, switch to new master configuration and if
4027
  # needed primary mode
4028
  for rd in bdevs:
4029
    try:
4030
      rd.AttachNet(multimaster)
4031
    except errors.BlockDeviceError, err:
4032
      _Fail("Can't change network configuration: %s", err)
4033

    
4034
  # wait until the disks are connected; we need to retry the re-attach
4035
  # if the device becomes standalone, as this might happen if the one
4036
  # node disconnects and reconnects in a different mode before the
4037
  # other node reconnects; in this case, one or both of the nodes will
4038
  # decide it has wrong configuration and switch to standalone
4039

    
4040
  def _Attach():
4041
    all_connected = True
4042

    
4043
    for rd in bdevs:
4044
      stats = rd.GetProcStatus()
4045

    
4046
      if multimaster:
4047
        # In the multimaster case we have to wait explicitly until
4048
        # the resource is Connected and UpToDate/UpToDate, because
4049
        # we promote *both nodes* to primary directly afterwards.
4050
        # Being in resync is not enough, since there is a race during which we
4051
        # may promote a node with an Outdated disk to primary, effectively
4052
        # tearing down the connection.
4053
        all_connected = (all_connected and
4054
                         stats.is_connected and
4055
                         stats.is_disk_uptodate and
4056
                         stats.peer_disk_uptodate)
4057
      else:
4058
        all_connected = (all_connected and
4059
                         (stats.is_connected or stats.is_in_resync))
4060

    
4061
      if stats.is_standalone:
4062
        # peer had different config info and this node became
4063
        # standalone, even though this should not happen with the
4064
        # new staged way of changing disk configs
4065
        try:
4066
          rd.AttachNet(multimaster)
4067
        except errors.BlockDeviceError, err:
4068
          _Fail("Can't change network configuration: %s", err)
4069

    
4070
    if not all_connected:
4071
      raise utils.RetryAgain()
4072

    
4073
  try:
4074
    # Start with a delay of 100 miliseconds and go up to 5 seconds
4075
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
4076
  except utils.RetryTimeout:
4077
    _Fail("Timeout in disk reconnecting")
4078

    
4079
  if multimaster:
4080
    # change to primary mode
4081
    for rd in bdevs:
4082
      try:
4083
        rd.Open()
4084
      except errors.BlockDeviceError, err:
4085
        _Fail("Can't change to primary mode: %s", err)
4086

    
4087

    
4088
def DrbdWaitSync(disks):
4089
  """Wait until DRBDs have synchronized.
4090

4091
  """
4092
  def _helper(rd):
4093
    stats = rd.GetProcStatus()
4094
    if not (stats.is_connected or stats.is_in_resync):
4095
      raise utils.RetryAgain()
4096
    return stats
4097

    
4098
  bdevs = _FindDisks(disks)
4099

    
4100
  min_resync = 100
4101
  alldone = True
4102
  for rd in bdevs:
4103
    try:
4104
      # poll each second for 15 seconds
4105
      stats = utils.Retry(_helper, 1, 15, args=[rd])
4106
    except utils.RetryTimeout:
4107
      stats = rd.GetProcStatus()
4108
      # last check
4109
      if not (stats.is_connected or stats.is_in_resync):
4110
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
4111
    alldone = alldone and (not stats.is_in_resync)
4112
    if stats.sync_percent is not None:
4113
      min_resync = min(min_resync, stats.sync_percent)
4114

    
4115
  return (alldone, min_resync)
4116

    
4117

    
4118
def DrbdNeedsActivation(disks):
4119
  """Checks which of the passed disks needs activation and returns their UUIDs.
4120

4121
  """
4122
  faulty_disks = []
4123

    
4124
  for disk in disks:
4125
    rd = _RecursiveFindBD(disk)
4126
    if rd is None:
4127
      faulty_disks.append(disk)
4128
      continue
4129

    
4130
    stats = rd.GetProcStatus()
4131
    if stats.is_standalone or stats.is_diskless:
4132
      faulty_disks.append(disk)
4133

    
4134
  return [disk.uuid for disk in faulty_disks]
4135

    
4136

    
4137
def GetDrbdUsermodeHelper():
4138
  """Returns DRBD usermode helper currently configured.
4139

4140
  """
4141
  try:
4142
    return drbd.DRBD8.GetUsermodeHelper()
4143
  except errors.BlockDeviceError, err:
4144
    _Fail(str(err))
4145

    
4146

    
4147
def PowercycleNode(hypervisor_type, hvparams=None):
4148
  """Hard-powercycle the node.
4149

4150
  Because we need to return first, and schedule the powercycle in the
4151
  background, we won't be able to report failures nicely.
4152

4153
  """
4154
  hyper = hypervisor.GetHypervisor(hypervisor_type)
4155
  try:
4156
    pid = os.fork()
4157
  except OSError:
4158
    # if we can't fork, we'll pretend that we're in the child process
4159
    pid = 0
4160
  if pid > 0:
4161
    return "Reboot scheduled in 5 seconds"
4162
  # ensure the child is running on ram
4163
  try:
4164
    utils.Mlockall()
4165
  except Exception: # pylint: disable=W0703
4166
    pass
4167
  time.sleep(5)
4168
  hyper.PowercycleNode(hvparams=hvparams)
4169

    
4170

    
4171
def _VerifyRestrictedCmdName(cmd):
4172
  """Verifies a restricted command name.
4173

4174
  @type cmd: string
4175
  @param cmd: Command name
4176
  @rtype: tuple; (boolean, string or None)
4177
  @return: The tuple's first element is the status; if C{False}, the second
4178
    element is an error message string, otherwise it's C{None}
4179

4180
  """
4181
  if not cmd.strip():
4182
    return (False, "Missing command name")
4183

    
4184
  if os.path.basename(cmd) != cmd:
4185
    return (False, "Invalid command name")
4186

    
4187
  if not constants.EXT_PLUGIN_MASK.match(cmd):
4188
    return (False, "Command name contains forbidden characters")
4189

    
4190
  return (True, None)
4191

    
4192

    
4193
def _CommonRestrictedCmdCheck(path, owner):
4194
  """Common checks for restricted command file system directories and files.
4195

4196
  @type path: string
4197
  @param path: Path to check
4198
  @param owner: C{None} or tuple containing UID and GID
4199
  @rtype: tuple; (boolean, string or C{os.stat} result)
4200
  @return: The tuple's first element is the status; if C{False}, the second
4201
    element is an error message string, otherwise it's the result of C{os.stat}
4202

4203
  """
4204
  if owner is None:
4205
    # Default to root as owner
4206
    owner = (0, 0)
4207

    
4208
  try:
4209
    st = os.stat(path)
4210
  except EnvironmentError, err:
4211
    return (False, "Can't stat(2) '%s': %s" % (path, err))
4212

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

    
4216
  if (st.st_uid, st.st_gid) != owner:
4217
    (owner_uid, owner_gid) = owner
4218
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
4219

    
4220
  return (True, st)
4221

    
4222

    
4223
def _VerifyRestrictedCmdDirectory(path, _owner=None):
4224
  """Verifies restricted command directory.
4225

4226
  @type path: string
4227
  @param path: Path to check
4228
  @rtype: tuple; (boolean, string or None)
4229
  @return: The tuple's first element is the status; if C{False}, the second
4230
    element is an error message string, otherwise it's C{None}
4231

4232
  """
4233
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
4234

    
4235
  if not status:
4236
    return (False, value)
4237

    
4238
  if not stat.S_ISDIR(value.st_mode):
4239
    return (False, "Path '%s' is not a directory" % path)
4240

    
4241
  return (True, None)
4242

    
4243

    
4244
def _VerifyRestrictedCmd(path, cmd, _owner=None):
4245
  """Verifies a whole restricted command and returns its executable filename.
4246

4247
  @type path: string
4248
  @param path: Directory containing restricted commands
4249
  @type cmd: string
4250
  @param cmd: Command name
4251
  @rtype: tuple; (boolean, string)
4252
  @return: The tuple's first element is the status; if C{False}, the second
4253
    element is an error message string, otherwise the second element is the
4254
    absolute path to the executable
4255

4256
  """
4257
  executable = utils.PathJoin(path, cmd)
4258

    
4259
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
4260

    
4261
  if not status:
4262
    return (False, msg)
4263

    
4264
  if not utils.IsExecutable(executable):
4265
    return (False, "access(2) thinks '%s' can't be executed" % executable)
4266

    
4267
  return (True, executable)
4268

    
4269

    
4270
def _PrepareRestrictedCmd(path, cmd,
4271
                          _verify_dir=_VerifyRestrictedCmdDirectory,
4272
                          _verify_name=_VerifyRestrictedCmdName,
4273
                          _verify_cmd=_VerifyRestrictedCmd):
4274
  """Performs a number of tests on a restricted command.
4275

4276
  @type path: string
4277
  @param path: Directory containing restricted commands
4278
  @type cmd: string
4279
  @param cmd: Command name
4280
  @return: Same as L{_VerifyRestrictedCmd}
4281

4282
  """
4283
  # Verify the directory first
4284
  (status, msg) = _verify_dir(path)
4285
  if status:
4286
    # Check command if everything was alright
4287
    (status, msg) = _verify_name(cmd)
4288

    
4289
  if not status:
4290
    return (False, msg)
4291

    
4292
  # Check actual executable
4293
  return _verify_cmd(path, cmd)
4294

    
4295

    
4296
def RunRestrictedCmd(cmd,
4297
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
4298
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
4299
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
4300
                     _sleep_fn=time.sleep,
4301
                     _prepare_fn=_PrepareRestrictedCmd,
4302
                     _runcmd_fn=utils.RunCmd,
4303
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
4304
  """Executes a restricted command after performing strict tests.
4305

4306
  @type cmd: string
4307
  @param cmd: Command name
4308
  @rtype: string
4309
  @return: Command output
4310
  @raise RPCFail: In case of an error
4311

4312
  """
4313
  logging.info("Preparing to run restricted command '%s'", cmd)
4314

    
4315
  if not _enabled:
4316
    _Fail("Restricted commands disabled at configure time")
4317

    
4318
  lock = None
4319
  try:
4320
    cmdresult = None
4321
    try:
4322
      lock = utils.FileLock.Open(_lock_file)
4323
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
4324

    
4325
      (status, value) = _prepare_fn(_path, cmd)
4326

    
4327
      if status:
4328
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
4329
                               postfork_fn=lambda _: lock.Unlock())
4330
      else:
4331
        logging.error(value)
4332
    except Exception: # pylint: disable=W0703
4333
      # Keep original error in log
4334
      logging.exception("Caught exception")
4335

    
4336
    if cmdresult is None:
4337
      logging.info("Sleeping for %0.1f seconds before returning",
4338
                   _RCMD_INVALID_DELAY)
4339
      _sleep_fn(_RCMD_INVALID_DELAY)
4340

    
4341
      # Do not include original error message in returned error
4342
      _Fail("Executing command '%s' failed" % cmd)
4343
    elif cmdresult.failed or cmdresult.fail_reason:
4344
      _Fail("Restricted command '%s' failed: %s; output: %s",
4345
            cmd, cmdresult.fail_reason, cmdresult.output)
4346
    else:
4347
      return cmdresult.output
4348
  finally:
4349
    if lock is not None:
4350
      # Release lock at last
4351
      lock.Close()
4352
      lock = None
4353

    
4354

    
4355
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
4356
  """Creates or removes the watcher pause file.
4357

4358
  @type until: None or number
4359
  @param until: Unix timestamp saying until when the watcher shouldn't run
4360

4361
  """
4362
  if until is None:
4363
    logging.info("Received request to no longer pause watcher")
4364
    utils.RemoveFile(_filename)
4365
  else:
4366
    logging.info("Received request to pause watcher until %s", until)
4367

    
4368
    if not ht.TNumber(until):
4369
      _Fail("Duration must be numeric")
4370

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

    
4373

    
4374
def ConfigureOVS(ovs_name, ovs_link):
4375
  """Creates a OpenvSwitch on the node.
4376

4377
  This function sets up a OpenvSwitch on the node with given name nad
4378
  connects it via a given eth device.
4379

4380
  @type ovs_name: string
4381
  @param ovs_name: Name of the OpenvSwitch to create.
4382
  @type ovs_link: None or string
4383
  @param ovs_link: Ethernet device for outside connection (can be missing)
4384

4385
  """
4386
  # Initialize the OpenvSwitch
4387
  result = utils.RunCmd(["ovs-vsctl", "add-br", ovs_name])
4388
  if result.failed:
4389
    _Fail("Failed to create openvswitch. Script return value: %s, output: '%s'"
4390
          % (result.exit_code, result.output), log=True)
4391

    
4392
  # And connect it to a physical interface, if given
4393
  if ovs_link:
4394
    result = utils.RunCmd(["ovs-vsctl", "add-port", ovs_name, ovs_link])
4395
    if result.failed:
4396
      _Fail("Failed to connect openvswitch to  interface %s. Script return"
4397
            " value: %s, output: '%s'" % (ovs_link, result.exit_code,
4398
            result.output), log=True)
4399

    
4400

    
4401
class HooksRunner(object):
4402
  """Hook runner.
4403

4404
  This class is instantiated on the node side (ganeti-noded) and not
4405
  on the master side.
4406

4407
  """
4408
  def __init__(self, hooks_base_dir=None):
4409
    """Constructor for hooks runner.
4410

4411
    @type hooks_base_dir: str or None
4412
    @param hooks_base_dir: if not None, this overrides the
4413
        L{pathutils.HOOKS_BASE_DIR} (useful for unittests)
4414

4415
    """
4416
    if hooks_base_dir is None:
4417
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
4418
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
4419
    # constant
4420
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
4421

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

4425
    """
4426
    assert len(node_list) == 1
4427
    node = node_list[0]
4428
    _, myself = ssconf.GetMasterAndMyself()
4429
    assert node == myself
4430

    
4431
    results = self.RunHooks(hpath, phase, env)
4432

    
4433
    # Return values in the form expected by HooksMaster
4434
    return {node: (None, False, results)}
4435

    
4436
  def RunHooks(self, hpath, phase, env):
4437
    """Run the scripts in the hooks directory.
4438

4439
    @type hpath: str
4440
    @param hpath: the path to the hooks directory which
4441
        holds the scripts
4442
    @type phase: str
4443
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
4444
        L{constants.HOOKS_PHASE_POST}
4445
    @type env: dict
4446
    @param env: dictionary with the environment for the hook
4447
    @rtype: list
4448
    @return: list of 3-element tuples:
4449
      - script path
4450
      - script result, either L{constants.HKR_SUCCESS} or
4451
        L{constants.HKR_FAIL}
4452
      - output of the script
4453

4454
    @raise errors.ProgrammerError: for invalid input
4455
        parameters
4456

4457
    """
4458
    if phase == constants.HOOKS_PHASE_PRE:
4459
      suffix = "pre"
4460
    elif phase == constants.HOOKS_PHASE_POST:
4461
      suffix = "post"
4462
    else:
4463
      _Fail("Unknown hooks phase '%s'", phase)
4464

    
4465
    subdir = "%s-%s.d" % (hpath, suffix)
4466
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
4467

    
4468
    results = []
4469

    
4470
    if not os.path.isdir(dir_name):
4471
      # for non-existing/non-dirs, we simply exit instead of logging a
4472
      # warning at every operation
4473
      return results
4474

    
4475
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
4476

    
4477
    for (relname, relstatus, runresult) in runparts_results:
4478
      if relstatus == constants.RUNPARTS_SKIP:
4479
        rrval = constants.HKR_SKIP
4480
        output = ""
4481
      elif relstatus == constants.RUNPARTS_ERR:
4482
        rrval = constants.HKR_FAIL
4483
        output = "Hook script execution error: %s" % runresult
4484
      elif relstatus == constants.RUNPARTS_RUN:
4485
        if runresult.failed:
4486
          rrval = constants.HKR_FAIL
4487
        else:
4488
          rrval = constants.HKR_SUCCESS
4489
        output = utils.SafeEncode(runresult.output.strip())
4490
      results.append(("%s/%s" % (subdir, relname), rrval, output))
4491

    
4492
    return results
4493

    
4494

    
4495
class IAllocatorRunner(object):
4496
  """IAllocator runner.
4497

4498
  This class is instantiated on the node side (ganeti-noded) and not on
4499
  the master side.
4500

4501
  """
4502
  @staticmethod
4503
  def Run(name, idata):
4504
    """Run an iallocator script.
4505

4506
    @type name: str
4507
    @param name: the iallocator script name
4508
    @type idata: str
4509
    @param idata: the allocator input data
4510

4511
    @rtype: tuple
4512
    @return: two element tuple of:
4513
       - status
4514
       - either error message or stdout of allocator (for success)
4515

4516
    """
4517
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
4518
                                  os.path.isfile)
4519
    if alloc_script is None:
4520
      _Fail("iallocator module '%s' not found in the search path", name)
4521

    
4522
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
4523
    try:
4524
      os.write(fd, idata)
4525
      os.close(fd)
4526
      result = utils.RunCmd([alloc_script, fin_name])
4527
      if result.failed:
4528
        _Fail("iallocator module '%s' failed: %s, output '%s'",
4529
              name, result.fail_reason, result.output)
4530
    finally:
4531
      os.unlink(fin_name)
4532

    
4533
    return result.stdout
4534

    
4535

    
4536
class DevCacheManager(object):
4537
  """Simple class for managing a cache of block device information.
4538

4539
  """
4540
  _DEV_PREFIX = "/dev/"
4541
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4542

    
4543
  @classmethod
4544
  def _ConvertPath(cls, dev_path):
4545
    """Converts a /dev/name path to the cache file name.
4546

4547
    This replaces slashes with underscores and strips the /dev
4548
    prefix. It then returns the full path to the cache file.
4549

4550
    @type dev_path: str
4551
    @param dev_path: the C{/dev/} path name
4552
    @rtype: str
4553
    @return: the converted path name
4554

4555
    """
4556
    if dev_path.startswith(cls._DEV_PREFIX):
4557
      dev_path = dev_path[len(cls._DEV_PREFIX):]
4558
    dev_path = dev_path.replace("/", "_")
4559
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4560
    return fpath
4561

    
4562
  @classmethod
4563
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4564
    """Updates the cache information for a given device.
4565

4566
    @type dev_path: str
4567
    @param dev_path: the pathname of the device
4568
    @type owner: str
4569
    @param owner: the owner (instance name) of the device
4570
    @type on_primary: bool
4571
    @param on_primary: whether this is the primary
4572
        node nor not
4573
    @type iv_name: str
4574
    @param iv_name: the instance-visible name of the
4575
        device, as in objects.Disk.iv_name
4576

4577
    @rtype: None
4578

4579
    """
4580
    if dev_path is None:
4581
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
4582
      return
4583
    fpath = cls._ConvertPath(dev_path)
4584
    if on_primary:
4585
      state = "primary"
4586
    else:
4587
      state = "secondary"
4588
    if iv_name is None:
4589
      iv_name = "not_visible"
4590
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4591
    try:
4592
      utils.WriteFile(fpath, data=fdata)
4593
    except EnvironmentError, err:
4594
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4595

    
4596
  @classmethod
4597
  def RemoveCache(cls, dev_path):
4598
    """Remove data for a dev_path.
4599

4600
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
4601
    path name and logging.
4602

4603
    @type dev_path: str
4604
    @param dev_path: the pathname of the device
4605

4606
    @rtype: None
4607

4608
    """
4609
    if dev_path is None:
4610
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
4611
      return
4612
    fpath = cls._ConvertPath(dev_path)
4613
    try:
4614
      utils.RemoveFile(fpath)
4615
    except EnvironmentError, err:
4616
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)