Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 7d81bb8b

History | View | Annotate | Download (141.9 kB)

1
#
2
#
3

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

    
21

    
22
"""Functions used by the node daemon
23

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

29
"""
30

    
31
# pylint: disable=E1103,C0302
32

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

    
37
# C0302: This module has become too big and should be split up
38

    
39

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

    
54
from ganeti import errors
55
from ganeti import utils
56
from ganeti import ssh
57
from ganeti import hypervisor
58
from ganeti import constants
59
from ganeti.storage import bdev
60
from ganeti.storage import drbd
61
from ganeti.storage import extstorage
62
from ganeti.storage import filestorage
63
from ganeti import objects
64
from ganeti import ssconf
65
from ganeti import serializer
66
from ganeti import netutils
67
from ganeti import runtime
68
from ganeti import compat
69
from ganeti import pathutils
70
from ganeti import vcluster
71
from ganeti import ht
72
from ganeti.storage.base import BlockDev
73
from ganeti.storage.drbd import DRBD8
74
from ganeti import hooksmaster
75

    
76

    
77
_BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id"
78
_ALLOWED_CLEAN_DIRS = compat.UniqueFrozenset([
79
  pathutils.DATA_DIR,
80
  pathutils.JOB_QUEUE_ARCHIVE_DIR,
81
  pathutils.QUEUE_DIR,
82
  pathutils.CRYPTO_KEYS_DIR,
83
  ])
84
_MAX_SSL_CERT_VALIDITY = 7 * 24 * 60 * 60
85
_X509_KEY_FILE = "key"
86
_X509_CERT_FILE = "cert"
87
_IES_STATUS_FILE = "status"
88
_IES_PID_FILE = "pid"
89
_IES_CA_FILE = "ca"
90

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

    
94
# Actions for the master setup script
95
_MASTER_START = "start"
96
_MASTER_STOP = "stop"
97

    
98
#: Maximum file permissions for restricted command directory and executables
99
_RCMD_MAX_MODE = (stat.S_IRWXU |
100
                  stat.S_IRGRP | stat.S_IXGRP |
101
                  stat.S_IROTH | stat.S_IXOTH)
102

    
103
#: Delay before returning an error for restricted commands
104
_RCMD_INVALID_DELAY = 10
105

    
106
#: How long to wait to acquire lock for restricted commands (shorter than
107
#: L{_RCMD_INVALID_DELAY}) to reduce blockage of noded forks when many
108
#: command requests arrive
109
_RCMD_LOCK_TIMEOUT = _RCMD_INVALID_DELAY * 0.8
110

    
111

    
112
class RPCFail(Exception):
113
  """Class denoting RPC failure.
114

115
  Its argument is the error message.
116

117
  """
118

    
119

    
120
def _GetInstReasonFilename(instance_name):
121
  """Path of the file containing the reason of the instance status change.
122

123
  @type instance_name: string
124
  @param instance_name: The name of the instance
125
  @rtype: string
126
  @return: The path of the file
127

128
  """
129
  return utils.PathJoin(pathutils.INSTANCE_REASON_DIR, instance_name)
130

    
131

    
132
def _StoreInstReasonTrail(instance_name, trail):
133
  """Serialize a reason trail related to an instance change of state to file.
134

135
  The exact location of the file depends on the name of the instance and on
136
  the configuration of the Ganeti cluster defined at deploy time.
137

138
  @type instance_name: string
139
  @param instance_name: The name of the instance
140
  @rtype: None
141

142
  """
143
  json = serializer.DumpJson(trail)
144
  filename = _GetInstReasonFilename(instance_name)
145
  utils.WriteFile(filename, data=json)
146

    
147

    
148
def _Fail(msg, *args, **kwargs):
149
  """Log an error and the raise an RPCFail exception.
150

151
  This exception is then handled specially in the ganeti daemon and
152
  turned into a 'failed' return type. As such, this function is a
153
  useful shortcut for logging the error and returning it to the master
154
  daemon.
155

156
  @type msg: string
157
  @param msg: the text of the exception
158
  @raise RPCFail
159

160
  """
161
  if args:
162
    msg = msg % args
163
  if "log" not in kwargs or kwargs["log"]: # if we should log this error
164
    if "exc" in kwargs and kwargs["exc"]:
165
      logging.exception(msg)
166
    else:
167
      logging.error(msg)
168
  raise RPCFail(msg)
169

    
170

    
171
def _GetConfig():
172
  """Simple wrapper to return a SimpleStore.
173

174
  @rtype: L{ssconf.SimpleStore}
175
  @return: a SimpleStore instance
176

177
  """
178
  return ssconf.SimpleStore()
179

    
180

    
181
def _GetSshRunner(cluster_name):
182
  """Simple wrapper to return an SshRunner.
183

184
  @type cluster_name: str
185
  @param cluster_name: the cluster name, which is needed
186
      by the SshRunner constructor
187
  @rtype: L{ssh.SshRunner}
188
  @return: an SshRunner instance
189

190
  """
191
  return ssh.SshRunner(cluster_name)
192

    
193

    
194
def _Decompress(data):
195
  """Unpacks data compressed by the RPC client.
196

197
  @type data: list or tuple
198
  @param data: Data sent by RPC client
199
  @rtype: str
200
  @return: Decompressed data
201

202
  """
203
  assert isinstance(data, (list, tuple))
204
  assert len(data) == 2
205
  (encoding, content) = data
206
  if encoding == constants.RPC_ENCODING_NONE:
207
    return content
208
  elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
209
    return zlib.decompress(base64.b64decode(content))
210
  else:
211
    raise AssertionError("Unknown data encoding")
212

    
213

    
214
def _CleanDirectory(path, exclude=None):
215
  """Removes all regular files in a directory.
216

217
  @type path: str
218
  @param path: the directory to clean
219
  @type exclude: list
220
  @param exclude: list of files to be excluded, defaults
221
      to the empty list
222

223
  """
224
  if path not in _ALLOWED_CLEAN_DIRS:
225
    _Fail("Path passed to _CleanDirectory not in allowed clean targets: '%s'",
226
          path)
227

    
228
  if not os.path.isdir(path):
229
    return
230
  if exclude is None:
231
    exclude = []
232
  else:
233
    # Normalize excluded paths
234
    exclude = [os.path.normpath(i) for i in exclude]
235

    
236
  for rel_name in utils.ListVisibleFiles(path):
237
    full_name = utils.PathJoin(path, rel_name)
238
    if full_name in exclude:
239
      continue
240
    if os.path.isfile(full_name) and not os.path.islink(full_name):
241
      utils.RemoveFile(full_name)
242

    
243

    
244
def _BuildUploadFileList():
245
  """Build the list of allowed upload files.
246

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

249
  """
250
  allowed_files = set([
251
    pathutils.CLUSTER_CONF_FILE,
252
    pathutils.ETC_HOSTS,
253
    pathutils.SSH_KNOWN_HOSTS_FILE,
254
    pathutils.VNC_PASSWORD_FILE,
255
    pathutils.RAPI_CERT_FILE,
256
    pathutils.SPICE_CERT_FILE,
257
    pathutils.SPICE_CACERT_FILE,
258
    pathutils.RAPI_USERS_FILE,
259
    pathutils.CONFD_HMAC_KEY,
260
    pathutils.CLUSTER_DOMAIN_SECRET_FILE,
261
    ])
262

    
263
  for hv_name in constants.HYPER_TYPES:
264
    hv_class = hypervisor.GetHypervisorClass(hv_name)
265
    allowed_files.update(hv_class.GetAncillaryFiles()[0])
266

    
267
  assert pathutils.FILE_STORAGE_PATHS_FILE not in allowed_files, \
268
    "Allowed file storage paths should never be uploaded via RPC"
269

    
270
  return frozenset(allowed_files)
271

    
272

    
273
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
274

    
275

    
276
def JobQueuePurge():
277
  """Removes job queue files and archived jobs.
278

279
  @rtype: tuple
280
  @return: True, None
281

282
  """
283
  _CleanDirectory(pathutils.QUEUE_DIR, exclude=[pathutils.JOB_QUEUE_LOCK_FILE])
284
  _CleanDirectory(pathutils.JOB_QUEUE_ARCHIVE_DIR)
285

    
286

    
287
def GetMasterInfo():
288
  """Returns master information.
289

290
  This is an utility function to compute master information, either
291
  for consumption here or from the node daemon.
292

293
  @rtype: tuple
294
  @return: master_netdev, master_ip, master_name, primary_ip_family,
295
    master_netmask
296
  @raise RPCFail: in case of errors
297

298
  """
299
  try:
300
    cfg = _GetConfig()
301
    master_netdev = cfg.GetMasterNetdev()
302
    master_ip = cfg.GetMasterIP()
303
    master_netmask = cfg.GetMasterNetmask()
304
    master_node = cfg.GetMasterNode()
305
    primary_ip_family = cfg.GetPrimaryIPFamily()
306
  except errors.ConfigurationError, err:
307
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
308
  return (master_netdev, master_ip, master_node, primary_ip_family,
309
          master_netmask)
310

    
311

    
312
def RunLocalHooks(hook_opcode, hooks_path, env_builder_fn):
313
  """Decorator that runs hooks before and after the decorated function.
314

315
  @type hook_opcode: string
316
  @param hook_opcode: opcode of the hook
317
  @type hooks_path: string
318
  @param hooks_path: path of the hooks
319
  @type env_builder_fn: function
320
  @param env_builder_fn: function that returns a dictionary containing the
321
    environment variables for the hooks. Will get all the parameters of the
322
    decorated function.
323
  @raise RPCFail: in case of pre-hook failure
324

325
  """
326
  def decorator(fn):
327
    def wrapper(*args, **kwargs):
328
      _, myself = ssconf.GetMasterAndMyself()
329
      nodes = ([myself], [myself])  # these hooks run locally
330

    
331
      env_fn = compat.partial(env_builder_fn, *args, **kwargs)
332

    
333
      cfg = _GetConfig()
334
      hr = HooksRunner()
335
      hm = hooksmaster.HooksMaster(hook_opcode, hooks_path, nodes,
336
                                   hr.RunLocalHooks, None, env_fn, None,
337
                                   logging.warning, cfg.GetClusterName(),
338
                                   cfg.GetMasterNode())
339
      hm.RunPhase(constants.HOOKS_PHASE_PRE)
340
      result = fn(*args, **kwargs)
341
      hm.RunPhase(constants.HOOKS_PHASE_POST)
342

    
343
      return result
344
    return wrapper
345
  return decorator
346

    
347

    
348
def _BuildMasterIpEnv(master_params, use_external_mip_script=None):
349
  """Builds environment variables for master IP hooks.
350

351
  @type master_params: L{objects.MasterNetworkParameters}
352
  @param master_params: network parameters of the master
353
  @type use_external_mip_script: boolean
354
  @param use_external_mip_script: whether to use an external master IP
355
    address setup script (unused, but necessary per the implementation of the
356
    _RunLocalHooks decorator)
357

358
  """
359
  # pylint: disable=W0613
360
  ver = netutils.IPAddress.GetVersionFromAddressFamily(master_params.ip_family)
361
  env = {
362
    "MASTER_NETDEV": master_params.netdev,
363
    "MASTER_IP": master_params.ip,
364
    "MASTER_NETMASK": str(master_params.netmask),
365
    "CLUSTER_IP_VERSION": str(ver),
366
  }
367

    
368
  return env
369

    
370

    
371
def _RunMasterSetupScript(master_params, action, use_external_mip_script):
372
  """Execute the master IP address setup script.
373

374
  @type master_params: L{objects.MasterNetworkParameters}
375
  @param master_params: network parameters of the master
376
  @type action: string
377
  @param action: action to pass to the script. Must be one of
378
    L{backend._MASTER_START} or L{backend._MASTER_STOP}
379
  @type use_external_mip_script: boolean
380
  @param use_external_mip_script: whether to use an external master IP
381
    address setup script
382
  @raise backend.RPCFail: if there are errors during the execution of the
383
    script
384

385
  """
386
  env = _BuildMasterIpEnv(master_params)
387

    
388
  if use_external_mip_script:
389
    setup_script = pathutils.EXTERNAL_MASTER_SETUP_SCRIPT
390
  else:
391
    setup_script = pathutils.DEFAULT_MASTER_SETUP_SCRIPT
392

    
393
  result = utils.RunCmd([setup_script, action], env=env, reset_env=True)
394

    
395
  if result.failed:
396
    _Fail("Failed to %s the master IP. Script return value: %s, output: '%s'" %
397
          (action, result.exit_code, result.output), log=True)
398

    
399

    
400
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNUP, "master-ip-turnup",
401
               _BuildMasterIpEnv)
402
def ActivateMasterIp(master_params, use_external_mip_script):
403
  """Activate the IP address of the master daemon.
404

405
  @type master_params: L{objects.MasterNetworkParameters}
406
  @param master_params: network parameters of the master
407
  @type use_external_mip_script: boolean
408
  @param use_external_mip_script: whether to use an external master IP
409
    address setup script
410
  @raise RPCFail: in case of errors during the IP startup
411

412
  """
413
  _RunMasterSetupScript(master_params, _MASTER_START,
414
                        use_external_mip_script)
415

    
416

    
417
def StartMasterDaemons(no_voting):
418
  """Activate local node as master node.
419

420
  The function will start the master daemons (ganeti-masterd and ganeti-rapi).
421

422
  @type no_voting: boolean
423
  @param no_voting: whether to start ganeti-masterd without a node vote
424
      but still non-interactively
425
  @rtype: None
426

427
  """
428

    
429
  if no_voting:
430
    masterd_args = "--no-voting --yes-do-it"
431
  else:
432
    masterd_args = ""
433

    
434
  env = {
435
    "EXTRA_MASTERD_ARGS": masterd_args,
436
    }
437

    
438
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "start-master"], env=env)
439
  if result.failed:
440
    msg = "Can't start Ganeti master: %s" % result.output
441
    logging.error(msg)
442
    _Fail(msg)
443

    
444

    
445
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNDOWN, "master-ip-turndown",
446
               _BuildMasterIpEnv)
447
def DeactivateMasterIp(master_params, use_external_mip_script):
448
  """Deactivate the master IP on this node.
449

450
  @type master_params: L{objects.MasterNetworkParameters}
451
  @param master_params: network parameters of the master
452
  @type use_external_mip_script: boolean
453
  @param use_external_mip_script: whether to use an external master IP
454
    address setup script
455
  @raise RPCFail: in case of errors during the IP turndown
456

457
  """
458
  _RunMasterSetupScript(master_params, _MASTER_STOP,
459
                        use_external_mip_script)
460

    
461

    
462
def StopMasterDaemons():
463
  """Stop the master daemons on this node.
464

465
  Stop the master daemons (ganeti-masterd and ganeti-rapi) on this node.
466

467
  @rtype: None
468

469
  """
470
  # TODO: log and report back to the caller the error failures; we
471
  # need to decide in which case we fail the RPC for this
472

    
473
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop-master"])
474
  if result.failed:
475
    logging.error("Could not stop Ganeti master, command %s had exitcode %s"
476
                  " and error %s",
477
                  result.cmd, result.exit_code, result.output)
478

    
479

    
480
def ChangeMasterNetmask(old_netmask, netmask, master_ip, master_netdev):
481
  """Change the netmask of the master IP.
482

483
  @param old_netmask: the old value of the netmask
484
  @param netmask: the new value of the netmask
485
  @param master_ip: the master IP
486
  @param master_netdev: the master network device
487

488
  """
489
  if old_netmask == netmask:
490
    return
491

    
492
  if not netutils.IPAddress.Own(master_ip):
493
    _Fail("The master IP address is not up, not attempting to change its"
494
          " netmask")
495

    
496
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
497
                         "%s/%s" % (master_ip, netmask),
498
                         "dev", master_netdev, "label",
499
                         "%s:0" % master_netdev])
500
  if result.failed:
501
    _Fail("Could not set the new netmask on the master IP address")
502

    
503
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
504
                         "%s/%s" % (master_ip, old_netmask),
505
                         "dev", master_netdev, "label",
506
                         "%s:0" % master_netdev])
507
  if result.failed:
508
    _Fail("Could not bring down the master IP address with the old netmask")
509

    
510

    
511
def EtcHostsModify(mode, host, ip):
512
  """Modify a host entry in /etc/hosts.
513

514
  @param mode: The mode to operate. Either add or remove entry
515
  @param host: The host to operate on
516
  @param ip: The ip associated with the entry
517

518
  """
519
  if mode == constants.ETC_HOSTS_ADD:
520
    if not ip:
521
      RPCFail("Mode 'add' needs 'ip' parameter, but parameter not"
522
              " present")
523
    utils.AddHostToEtcHosts(host, ip)
524
  elif mode == constants.ETC_HOSTS_REMOVE:
525
    if ip:
526
      RPCFail("Mode 'remove' does not allow 'ip' parameter, but"
527
              " parameter is present")
528
    utils.RemoveHostFromEtcHosts(host)
529
  else:
530
    RPCFail("Mode not supported")
531

    
532

    
533
def LeaveCluster(modify_ssh_setup):
534
  """Cleans up and remove the current node.
535

536
  This function cleans up and prepares the current node to be removed
537
  from the cluster.
538

539
  If processing is successful, then it raises an
540
  L{errors.QuitGanetiException} which is used as a special case to
541
  shutdown the node daemon.
542

543
  @param modify_ssh_setup: boolean
544

545
  """
546
  _CleanDirectory(pathutils.DATA_DIR)
547
  _CleanDirectory(pathutils.CRYPTO_KEYS_DIR)
548
  JobQueuePurge()
549

    
550
  if modify_ssh_setup:
551
    try:
552
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.SSH_LOGIN_USER)
553

    
554
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
555

    
556
      utils.RemoveFile(priv_key)
557
      utils.RemoveFile(pub_key)
558
    except errors.OpExecError:
559
      logging.exception("Error while processing ssh files")
560

    
561
  try:
562
    utils.RemoveFile(pathutils.CONFD_HMAC_KEY)
563
    utils.RemoveFile(pathutils.RAPI_CERT_FILE)
564
    utils.RemoveFile(pathutils.SPICE_CERT_FILE)
565
    utils.RemoveFile(pathutils.SPICE_CACERT_FILE)
566
    utils.RemoveFile(pathutils.NODED_CERT_FILE)
567
  except: # pylint: disable=W0702
568
    logging.exception("Error while removing cluster secrets")
569

    
570
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop", constants.CONFD])
571
  if result.failed:
572
    logging.error("Command %s failed with exitcode %s and error %s",
573
                  result.cmd, result.exit_code, result.output)
574

    
575
  # Raise a custom exception (handled in ganeti-noded)
576
  raise errors.QuitGanetiException(True, "Shutdown scheduled")
577

    
578

    
579
def _CheckStorageParams(params, num_params):
580
  """Performs sanity checks for storage parameters.
581

582
  @type params: list
583
  @param params: list of storage parameters
584
  @type num_params: int
585
  @param num_params: expected number of parameters
586

587
  """
588
  if params is None:
589
    raise errors.ProgrammerError("No storage parameters for storage"
590
                                 " reporting is provided.")
591
  if not isinstance(params, list):
592
    raise errors.ProgrammerError("The storage parameters are not of type"
593
                                 " list: '%s'" % params)
594
  if not len(params) == num_params:
595
    raise errors.ProgrammerError("Did not receive the expected number of"
596
                                 "storage parameters: expected %s,"
597
                                 " received '%s'" % (num_params, len(params)))
598

    
599

    
600
def _CheckLvmStorageParams(params):
601
  """Performs sanity check for the 'exclusive storage' flag.
602

603
  @see: C{_CheckStorageParams}
604

605
  """
606
  _CheckStorageParams(params, 1)
607
  excl_stor = params[0]
608
  if not isinstance(params[0], bool):
609
    raise errors.ProgrammerError("Exclusive storage parameter is not"
610
                                 " boolean: '%s'." % excl_stor)
611
  return excl_stor
612

    
613

    
614
def _GetLvmVgSpaceInfo(name, params):
615
  """Wrapper around C{_GetVgInfo} which checks the storage parameters.
616

617
  @type name: string
618
  @param name: name of the volume group
619
  @type params: list
620
  @param params: list of storage parameters, which in this case should be
621
    containing only one for exclusive storage
622

623
  """
624
  excl_stor = _CheckLvmStorageParams(params)
625
  return _GetVgInfo(name, excl_stor)
626

    
627

    
628
def _GetVgInfo(
629
    name, excl_stor, info_fn=bdev.LogicalVolume.GetVGInfo):
630
  """Retrieves information about a LVM volume group.
631

632
  """
633
  # TODO: GetVGInfo supports returning information for multiple VGs at once
634
  vginfo = info_fn([name], excl_stor)
635
  if vginfo:
636
    vg_free = int(round(vginfo[0][0], 0))
637
    vg_size = int(round(vginfo[0][1], 0))
638
  else:
639
    vg_free = None
640
    vg_size = None
641

    
642
  return {
643
    "type": constants.ST_LVM_VG,
644
    "name": name,
645
    "storage_free": vg_free,
646
    "storage_size": vg_size,
647
    }
648

    
649

    
650
def _GetLvmPvSpaceInfo(name, params):
651
  """Wrapper around C{_GetVgSpindlesInfo} with sanity checks.
652

653
  @see: C{_GetLvmVgSpaceInfo}
654

655
  """
656
  excl_stor = _CheckLvmStorageParams(params)
657
  return _GetVgSpindlesInfo(name, excl_stor)
658

    
659

    
660
def _GetVgSpindlesInfo(
661
    name, excl_stor, info_fn=bdev.LogicalVolume.GetVgSpindlesInfo):
662
  """Retrieves information about spindles in an LVM volume group.
663

664
  @type name: string
665
  @param name: VG name
666
  @type excl_stor: bool
667
  @param excl_stor: exclusive storage
668
  @rtype: dict
669
  @return: dictionary whose keys are "name", "vg_free", "vg_size" for VG name,
670
      free spindles, total spindles respectively
671

672
  """
673
  if excl_stor:
674
    (vg_free, vg_size) = info_fn(name)
675
  else:
676
    vg_free = 0
677
    vg_size = 0
678
  return {
679
    "type": constants.ST_LVM_PV,
680
    "name": name,
681
    "storage_free": vg_free,
682
    "storage_size": vg_size,
683
    }
684

    
685

    
686
def _GetHvInfo(name, hvparams, get_hv_fn=hypervisor.GetHypervisor):
687
  """Retrieves node information from a hypervisor.
688

689
  The information returned depends on the hypervisor. Common items:
690

691
    - vg_size is the size of the configured volume group in MiB
692
    - vg_free is the free size of the volume group in MiB
693
    - memory_dom0 is the memory allocated for domain0 in MiB
694
    - memory_free is the currently available (free) ram in MiB
695
    - memory_total is the total number of ram in MiB
696
    - hv_version: the hypervisor version, if available
697

698
  @type hvparams: dict of string
699
  @param hvparams: the hypervisor's hvparams
700

701
  """
702
  return get_hv_fn(name).GetNodeInfo(hvparams=hvparams)
703

    
704

    
705
def _GetHvInfoAll(hv_specs, get_hv_fn=hypervisor.GetHypervisor):
706
  """Retrieves node information for all hypervisors.
707

708
  See C{_GetHvInfo} for information on the output.
709

710
  @type hv_specs: list of pairs (string, dict of strings)
711
  @param hv_specs: list of pairs of a hypervisor's name and its hvparams
712

713
  """
714
  if hv_specs is None:
715
    return None
716

    
717
  result = []
718
  for hvname, hvparams in hv_specs:
719
    result.append(_GetHvInfo(hvname, hvparams, get_hv_fn))
720
  return result
721

    
722

    
723
def _GetNamedNodeInfo(names, fn):
724
  """Calls C{fn} for all names in C{names} and returns a dictionary.
725

726
  @rtype: None or dict
727

728
  """
729
  if names is None:
730
    return None
731
  else:
732
    return map(fn, names)
733

    
734

    
735
def GetNodeInfo(storage_units, hv_specs):
736
  """Gives back a hash with different information about the node.
737

738
  @type storage_units: list of tuples (string, string, list)
739
  @param storage_units: List of tuples (storage unit, identifier, parameters) to
740
    ask for disk space information. In case of lvm-vg, the identifier is
741
    the VG name. The parameters can contain additional, storage-type-specific
742
    parameters, for example exclusive storage for lvm storage.
743
  @type hv_specs: list of pairs (string, dict of strings)
744
  @param hv_specs: list of pairs of a hypervisor's name and its hvparams
745
  @rtype: tuple; (string, None/dict, None/dict)
746
  @return: Tuple containing boot ID, volume group information and hypervisor
747
    information
748

749
  """
750
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
751
  storage_info = _GetNamedNodeInfo(
752
    storage_units,
753
    (lambda (storage_type, storage_key, storage_params):
754
        _ApplyStorageInfoFunction(storage_type, storage_key, storage_params)))
755
  hv_info = _GetHvInfoAll(hv_specs)
756
  return (bootid, storage_info, hv_info)
757

    
758

    
759
def _GetFileStorageSpaceInfo(path, params):
760
  """Wrapper around filestorage.GetSpaceInfo.
761

762
  The purpose of this wrapper is to call filestorage.GetFileStorageSpaceInfo
763
  and ignore the *args parameter to not leak it into the filestorage
764
  module's code.
765

766
  @see: C{filestorage.GetFileStorageSpaceInfo} for description of the
767
    parameters.
768

769
  """
770
  _CheckStorageParams(params, 0)
771
  return filestorage.GetFileStorageSpaceInfo(path)
772

    
773

    
774
# FIXME: implement storage reporting for all missing storage types.
775
_STORAGE_TYPE_INFO_FN = {
776
  constants.ST_BLOCK: None,
777
  constants.ST_DISKLESS: None,
778
  constants.ST_EXT: None,
779
  constants.ST_FILE: _GetFileStorageSpaceInfo,
780
  constants.ST_LVM_PV: _GetLvmPvSpaceInfo,
781
  constants.ST_LVM_VG: _GetLvmVgSpaceInfo,
782
  constants.ST_RADOS: None,
783
}
784

    
785

    
786
def _ApplyStorageInfoFunction(storage_type, storage_key, *args):
787
  """Looks up and applies the correct function to calculate free and total
788
  storage for the given storage type.
789

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

    
811

    
812
def _CheckExclusivePvs(pvi_list):
813
  """Check that PVs are not shared among LVs
814

815
  @type pvi_list: list of L{objects.LvmPvInfo} objects
816
  @param pvi_list: information about the PVs
817

818
  @rtype: list of tuples (string, list of strings)
819
  @return: offending volumes, as tuples: (pv_name, [lv1_name, lv2_name...])
820

821
  """
822
  res = []
823
  for pvi in pvi_list:
824
    if len(pvi.lv_list) > 1:
825
      res.append((pvi.name, pvi.lv_list))
826
  return res
827

    
828

    
829
def _VerifyHypervisors(what, vm_capable, result, all_hvparams,
830
                       get_hv_fn=hypervisor.GetHypervisor):
831
  """Verifies the hypervisor. Appends the results to the 'results' list.
832

833
  @type what: C{dict}
834
  @param what: a dictionary of things to check
835
  @type vm_capable: boolean
836
  @param vm_capable: whether or not this node is vm capable
837
  @type result: dict
838
  @param result: dictionary of verification results; results of the
839
    verifications in this function will be added here
840
  @type all_hvparams: dict of dict of string
841
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
842
  @type get_hv_fn: function
843
  @param get_hv_fn: function to retrieve the hypervisor, to improve testability
844

845
  """
846
  if not vm_capable:
847
    return
848

    
849
  if constants.NV_HYPERVISOR in what:
850
    result[constants.NV_HYPERVISOR] = {}
851
    for hv_name in what[constants.NV_HYPERVISOR]:
852
      hvparams = all_hvparams[hv_name]
853
      try:
854
        val = get_hv_fn(hv_name).Verify(hvparams=hvparams)
855
      except errors.HypervisorError, err:
856
        val = "Error while checking hypervisor: %s" % str(err)
857
      result[constants.NV_HYPERVISOR][hv_name] = val
858

    
859

    
860
def _VerifyHvparams(what, vm_capable, result,
861
                    get_hv_fn=hypervisor.GetHypervisor):
862
  """Verifies the hvparams. Appends the results to the 'results' list.
863

864
  @type what: C{dict}
865
  @param what: a dictionary of things to check
866
  @type vm_capable: boolean
867
  @param vm_capable: whether or not this node is vm capable
868
  @type result: dict
869
  @param result: dictionary of verification results; results of the
870
    verifications in this function will be added here
871
  @type get_hv_fn: function
872
  @param get_hv_fn: function to retrieve the hypervisor, to improve testability
873

874
  """
875
  if not vm_capable:
876
    return
877

    
878
  if constants.NV_HVPARAMS in what:
879
    result[constants.NV_HVPARAMS] = []
880
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
881
      try:
882
        logging.info("Validating hv %s, %s", hv_name, hvparms)
883
        get_hv_fn(hv_name).ValidateParameters(hvparms)
884
      except errors.HypervisorError, err:
885
        result[constants.NV_HVPARAMS].append((source, hv_name, str(err)))
886

    
887

    
888
def _VerifyInstanceList(what, vm_capable, result, all_hvparams):
889
  """Verifies the instance list.
890

891
  @type what: C{dict}
892
  @param what: a dictionary of things to check
893
  @type vm_capable: boolean
894
  @param vm_capable: whether or not this node is vm capable
895
  @type result: dict
896
  @param result: dictionary of verification results; results of the
897
    verifications in this function will be added here
898
  @type all_hvparams: dict of dict of string
899
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
900

901
  """
902
  if constants.NV_INSTANCELIST in what and vm_capable:
903
    # GetInstanceList can fail
904
    try:
905
      val = GetInstanceList(what[constants.NV_INSTANCELIST],
906
                            all_hvparams=all_hvparams)
907
    except RPCFail, err:
908
      val = str(err)
909
    result[constants.NV_INSTANCELIST] = val
910

    
911

    
912
def _VerifyNodeInfo(what, vm_capable, result, all_hvparams):
913
  """Verifies the node info.
914

915
  @type what: C{dict}
916
  @param what: a dictionary of things to check
917
  @type vm_capable: boolean
918
  @param vm_capable: whether or not this node is vm capable
919
  @type result: dict
920
  @param result: dictionary of verification results; results of the
921
    verifications in this function will be added here
922
  @type all_hvparams: dict of dict of string
923
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
924

925
  """
926
  if constants.NV_HVINFO in what and vm_capable:
927
    hvname = what[constants.NV_HVINFO]
928
    hyper = hypervisor.GetHypervisor(hvname)
929
    hvparams = all_hvparams[hvname]
930
    result[constants.NV_HVINFO] = hyper.GetNodeInfo(hvparams=hvparams)
931

    
932

    
933
def VerifyNode(what, cluster_name, all_hvparams):
934
  """Verify the status of the local node.
935

936
  Based on the input L{what} parameter, various checks are done on the
937
  local node.
938

939
  If the I{filelist} key is present, this list of
940
  files is checksummed and the file/checksum pairs are returned.
941

942
  If the I{nodelist} key is present, we check that we have
943
  connectivity via ssh with the target nodes (and check the hostname
944
  report).
945

946
  If the I{node-net-test} key is present, we check that we have
947
  connectivity to the given nodes via both primary IP and, if
948
  applicable, secondary IPs.
949

950
  @type what: C{dict}
951
  @param what: a dictionary of things to check:
952
      - filelist: list of files for which to compute checksums
953
      - nodelist: list of nodes we should check ssh communication with
954
      - node-net-test: list of nodes we should check node daemon port
955
        connectivity with
956
      - hypervisor: list with hypervisors to run the verify for
957
  @type cluster_name: string
958
  @param cluster_name: the cluster's name
959
  @type all_hvparams: dict of dict of strings
960
  @param all_hvparams: a dictionary mapping hypervisor names to hvparams
961
  @rtype: dict
962
  @return: a dictionary with the same keys as the input dict, and
963
      values representing the result of the checks
964

965
  """
966
  result = {}
967
  my_name = netutils.Hostname.GetSysName()
968
  port = netutils.GetDaemonPort(constants.NODED)
969
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
970

    
971
  _VerifyHypervisors(what, vm_capable, result, all_hvparams)
972
  _VerifyHvparams(what, vm_capable, result)
973

    
974
  if constants.NV_FILELIST in what:
975
    fingerprints = utils.FingerprintFiles(map(vcluster.LocalizeVirtualPath,
976
                                              what[constants.NV_FILELIST]))
977
    result[constants.NV_FILELIST] = \
978
      dict((vcluster.MakeVirtualPath(key), value)
979
           for (key, value) in fingerprints.items())
980

    
981
  if constants.NV_NODELIST in what:
982
    (nodes, bynode) = what[constants.NV_NODELIST]
983

    
984
    # Add nodes from other groups (different for each node)
985
    try:
986
      nodes.extend(bynode[my_name])
987
    except KeyError:
988
      pass
989

    
990
    # Use a random order
991
    random.shuffle(nodes)
992

    
993
    # Try to contact all nodes
994
    val = {}
995
    for node in nodes:
996
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
997
      if not success:
998
        val[node] = message
999

    
1000
    result[constants.NV_NODELIST] = val
1001

    
1002
  if constants.NV_NODENETTEST in what:
1003
    result[constants.NV_NODENETTEST] = tmp = {}
1004
    my_pip = my_sip = None
1005
    for name, pip, sip in what[constants.NV_NODENETTEST]:
1006
      if name == my_name:
1007
        my_pip = pip
1008
        my_sip = sip
1009
        break
1010
    if not my_pip:
1011
      tmp[my_name] = ("Can't find my own primary/secondary IP"
1012
                      " in the node list")
1013
    else:
1014
      for name, pip, sip in what[constants.NV_NODENETTEST]:
1015
        fail = []
1016
        if not netutils.TcpPing(pip, port, source=my_pip):
1017
          fail.append("primary")
1018
        if sip != pip:
1019
          if not netutils.TcpPing(sip, port, source=my_sip):
1020
            fail.append("secondary")
1021
        if fail:
1022
          tmp[name] = ("failure using the %s interface(s)" %
1023
                       " and ".join(fail))
1024

    
1025
  if constants.NV_MASTERIP in what:
1026
    # FIXME: add checks on incoming data structures (here and in the
1027
    # rest of the function)
1028
    master_name, master_ip = what[constants.NV_MASTERIP]
1029
    if master_name == my_name:
1030
      source = constants.IP4_ADDRESS_LOCALHOST
1031
    else:
1032
      source = None
1033
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
1034
                                                     source=source)
1035

    
1036
  if constants.NV_USERSCRIPTS in what:
1037
    result[constants.NV_USERSCRIPTS] = \
1038
      [script for script in what[constants.NV_USERSCRIPTS]
1039
       if not utils.IsExecutable(script)]
1040

    
1041
  if constants.NV_OOB_PATHS in what:
1042
    result[constants.NV_OOB_PATHS] = tmp = []
1043
    for path in what[constants.NV_OOB_PATHS]:
1044
      try:
1045
        st = os.stat(path)
1046
      except OSError, err:
1047
        tmp.append("error stating out of band helper: %s" % err)
1048
      else:
1049
        if stat.S_ISREG(st.st_mode):
1050
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
1051
            tmp.append(None)
1052
          else:
1053
            tmp.append("out of band helper %s is not executable" % path)
1054
        else:
1055
          tmp.append("out of band helper %s is not a file" % path)
1056

    
1057
  if constants.NV_LVLIST in what and vm_capable:
1058
    try:
1059
      val = GetVolumeList(utils.ListVolumeGroups().keys())
1060
    except RPCFail, err:
1061
      val = str(err)
1062
    result[constants.NV_LVLIST] = val
1063

    
1064
  _VerifyInstanceList(what, vm_capable, result, all_hvparams)
1065

    
1066
  if constants.NV_VGLIST in what and vm_capable:
1067
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
1068

    
1069
  if constants.NV_PVLIST in what and vm_capable:
1070
    check_exclusive_pvs = constants.NV_EXCLUSIVEPVS in what
1071
    val = bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
1072
                                       filter_allocatable=False,
1073
                                       include_lvs=check_exclusive_pvs)
1074
    if check_exclusive_pvs:
1075
      result[constants.NV_EXCLUSIVEPVS] = _CheckExclusivePvs(val)
1076
      for pvi in val:
1077
        # Avoid sending useless data on the wire
1078
        pvi.lv_list = []
1079
    result[constants.NV_PVLIST] = map(objects.LvmPvInfo.ToDict, val)
1080

    
1081
  if constants.NV_VERSION in what:
1082
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
1083
                                    constants.RELEASE_VERSION)
1084

    
1085
  _VerifyNodeInfo(what, vm_capable, result, all_hvparams)
1086

    
1087
  if constants.NV_DRBDVERSION in what and vm_capable:
1088
    try:
1089
      drbd_version = DRBD8.GetProcInfo().GetVersionString()
1090
    except errors.BlockDeviceError, err:
1091
      logging.warning("Can't get DRBD version", exc_info=True)
1092
      drbd_version = str(err)
1093
    result[constants.NV_DRBDVERSION] = drbd_version
1094

    
1095
  if constants.NV_DRBDLIST in what and vm_capable:
1096
    try:
1097
      used_minors = drbd.DRBD8.GetUsedDevs()
1098
    except errors.BlockDeviceError, err:
1099
      logging.warning("Can't get used minors list", exc_info=True)
1100
      used_minors = str(err)
1101
    result[constants.NV_DRBDLIST] = used_minors
1102

    
1103
  if constants.NV_DRBDHELPER in what and vm_capable:
1104
    status = True
1105
    try:
1106
      payload = drbd.DRBD8.GetUsermodeHelper()
1107
    except errors.BlockDeviceError, err:
1108
      logging.error("Can't get DRBD usermode helper: %s", str(err))
1109
      status = False
1110
      payload = str(err)
1111
    result[constants.NV_DRBDHELPER] = (status, payload)
1112

    
1113
  if constants.NV_NODESETUP in what:
1114
    result[constants.NV_NODESETUP] = tmpr = []
1115
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
1116
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
1117
                  " under /sys, missing required directories /sys/block"
1118
                  " and /sys/class/net")
1119
    if (not os.path.isdir("/proc/sys") or
1120
        not os.path.isfile("/proc/sysrq-trigger")):
1121
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
1122
                  " under /proc, missing required directory /proc/sys and"
1123
                  " the file /proc/sysrq-trigger")
1124

    
1125
  if constants.NV_TIME in what:
1126
    result[constants.NV_TIME] = utils.SplitTime(time.time())
1127

    
1128
  if constants.NV_OSLIST in what and vm_capable:
1129
    result[constants.NV_OSLIST] = DiagnoseOS()
1130

    
1131
  if constants.NV_BRIDGES in what and vm_capable:
1132
    result[constants.NV_BRIDGES] = [bridge
1133
                                    for bridge in what[constants.NV_BRIDGES]
1134
                                    if not utils.BridgeExists(bridge)]
1135

    
1136
  if what.get(constants.NV_ACCEPTED_STORAGE_PATHS) == my_name:
1137
    result[constants.NV_ACCEPTED_STORAGE_PATHS] = \
1138
        filestorage.ComputeWrongFileStoragePaths()
1139

    
1140
  if what.get(constants.NV_FILE_STORAGE_PATH):
1141
    pathresult = filestorage.CheckFileStoragePath(
1142
        what[constants.NV_FILE_STORAGE_PATH])
1143
    if pathresult:
1144
      result[constants.NV_FILE_STORAGE_PATH] = pathresult
1145

    
1146
  if what.get(constants.NV_SHARED_FILE_STORAGE_PATH):
1147
    pathresult = filestorage.CheckFileStoragePath(
1148
        what[constants.NV_SHARED_FILE_STORAGE_PATH])
1149
    if pathresult:
1150
      result[constants.NV_SHARED_FILE_STORAGE_PATH] = pathresult
1151

    
1152
  return result
1153

    
1154

    
1155
def GetBlockDevSizes(devices):
1156
  """Return the size of the given block devices
1157

1158
  @type devices: list
1159
  @param devices: list of block device nodes to query
1160
  @rtype: dict
1161
  @return:
1162
    dictionary of all block devices under /dev (key). The value is their
1163
    size in MiB.
1164

1165
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
1166

1167
  """
1168
  DEV_PREFIX = "/dev/"
1169
  blockdevs = {}
1170

    
1171
  for devpath in devices:
1172
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
1173
      continue
1174

    
1175
    try:
1176
      st = os.stat(devpath)
1177
    except EnvironmentError, err:
1178
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
1179
      continue
1180

    
1181
    if stat.S_ISBLK(st.st_mode):
1182
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
1183
      if result.failed:
1184
        # We don't want to fail, just do not list this device as available
1185
        logging.warning("Cannot get size for block device %s", devpath)
1186
        continue
1187

    
1188
      size = int(result.stdout) / (1024 * 1024)
1189
      blockdevs[devpath] = size
1190
  return blockdevs
1191

    
1192

    
1193
def GetVolumeList(vg_names):
1194
  """Compute list of logical volumes and their size.
1195

1196
  @type vg_names: list
1197
  @param vg_names: the volume groups whose LVs we should list, or
1198
      empty for all volume groups
1199
  @rtype: dict
1200
  @return:
1201
      dictionary of all partions (key) with value being a tuple of
1202
      their size (in MiB), inactive and online status::
1203

1204
        {'xenvg/test1': ('20.06', True, True)}
1205

1206
      in case of errors, a string is returned with the error
1207
      details.
1208

1209
  """
1210
  lvs = {}
1211
  sep = "|"
1212
  if not vg_names:
1213
    vg_names = []
1214
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1215
                         "--separator=%s" % sep,
1216
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
1217
  if result.failed:
1218
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
1219

    
1220
  for line in result.stdout.splitlines():
1221
    line = line.strip()
1222
    match = _LVSLINE_REGEX.match(line)
1223
    if not match:
1224
      logging.error("Invalid line returned from lvs output: '%s'", line)
1225
      continue
1226
    vg_name, name, size, attr = match.groups()
1227
    inactive = attr[4] == "-"
1228
    online = attr[5] == "o"
1229
    virtual = attr[0] == "v"
1230
    if virtual:
1231
      # we don't want to report such volumes as existing, since they
1232
      # don't really hold data
1233
      continue
1234
    lvs[vg_name + "/" + name] = (size, inactive, online)
1235

    
1236
  return lvs
1237

    
1238

    
1239
def ListVolumeGroups():
1240
  """List the volume groups and their size.
1241

1242
  @rtype: dict
1243
  @return: dictionary with keys volume name and values the
1244
      size of the volume
1245

1246
  """
1247
  return utils.ListVolumeGroups()
1248

    
1249

    
1250
def NodeVolumes():
1251
  """List all volumes on this node.
1252

1253
  @rtype: list
1254
  @return:
1255
    A list of dictionaries, each having four keys:
1256
      - name: the logical volume name,
1257
      - size: the size of the logical volume
1258
      - dev: the physical device on which the LV lives
1259
      - vg: the volume group to which it belongs
1260

1261
    In case of errors, we return an empty list and log the
1262
    error.
1263

1264
    Note that since a logical volume can live on multiple physical
1265
    volumes, the resulting list might include a logical volume
1266
    multiple times.
1267

1268
  """
1269
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1270
                         "--separator=|",
1271
                         "--options=lv_name,lv_size,devices,vg_name"])
1272
  if result.failed:
1273
    _Fail("Failed to list logical volumes, lvs output: %s",
1274
          result.output)
1275

    
1276
  def parse_dev(dev):
1277
    return dev.split("(")[0]
1278

    
1279
  def handle_dev(dev):
1280
    return [parse_dev(x) for x in dev.split(",")]
1281

    
1282
  def map_line(line):
1283
    line = [v.strip() for v in line]
1284
    return [{"name": line[0], "size": line[1],
1285
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
1286

    
1287
  all_devs = []
1288
  for line in result.stdout.splitlines():
1289
    if line.count("|") >= 3:
1290
      all_devs.extend(map_line(line.split("|")))
1291
    else:
1292
      logging.warning("Strange line in the output from lvs: '%s'", line)
1293
  return all_devs
1294

    
1295

    
1296
def BridgesExist(bridges_list):
1297
  """Check if a list of bridges exist on the current node.
1298

1299
  @rtype: boolean
1300
  @return: C{True} if all of them exist, C{False} otherwise
1301

1302
  """
1303
  missing = []
1304
  for bridge in bridges_list:
1305
    if not utils.BridgeExists(bridge):
1306
      missing.append(bridge)
1307

    
1308
  if missing:
1309
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
1310

    
1311

    
1312
def GetInstanceListForHypervisor(hname, hvparams=None,
1313
                                 get_hv_fn=hypervisor.GetHypervisor):
1314
  """Provides a list of instances of the given hypervisor.
1315

1316
  @type hname: string
1317
  @param hname: name of the hypervisor
1318
  @type hvparams: dict of strings
1319
  @param hvparams: hypervisor parameters for the given hypervisor
1320
  @type get_hv_fn: function
1321
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1322
    name; optional parameter to increase testability
1323

1324
  @rtype: list
1325
  @return: a list of all running instances on the current node
1326
    - instance1.example.com
1327
    - instance2.example.com
1328

1329
  """
1330
  results = []
1331
  try:
1332
    hv = get_hv_fn(hname)
1333
    names = hv.ListInstances(hvparams=hvparams)
1334
    results.extend(names)
1335
  except errors.HypervisorError, err:
1336
    _Fail("Error enumerating instances (hypervisor %s): %s",
1337
          hname, err, exc=True)
1338
  return results
1339

    
1340

    
1341
def GetInstanceList(hypervisor_list, all_hvparams=None,
1342
                    get_hv_fn=hypervisor.GetHypervisor):
1343
  """Provides a list of instances.
1344

1345
  @type hypervisor_list: list
1346
  @param hypervisor_list: the list of hypervisors to query information
1347
  @type all_hvparams: dict of dict of strings
1348
  @param all_hvparams: a dictionary mapping hypervisor types to respective
1349
    cluster-wide hypervisor parameters
1350
  @type get_hv_fn: function
1351
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1352
    name; optional parameter to increase testability
1353

1354
  @rtype: list
1355
  @return: a list of all running instances on the current node
1356
    - instance1.example.com
1357
    - instance2.example.com
1358

1359
  """
1360
  results = []
1361
  for hname in hypervisor_list:
1362
    hvparams = all_hvparams[hname]
1363
    results.extend(GetInstanceListForHypervisor(hname, hvparams=hvparams,
1364
                                                get_hv_fn=get_hv_fn))
1365
  return results
1366

    
1367

    
1368
def GetInstanceInfo(instance, hname, hvparams=None):
1369
  """Gives back the information about an instance as a dictionary.
1370

1371
  @type instance: string
1372
  @param instance: the instance name
1373
  @type hname: string
1374
  @param hname: the hypervisor type of the instance
1375
  @type hvparams: dict of strings
1376
  @param hvparams: the instance's hvparams
1377

1378
  @rtype: dict
1379
  @return: dictionary with the following keys:
1380
      - memory: memory size of instance (int)
1381
      - state: xen state of instance (string)
1382
      - time: cpu time of instance (float)
1383
      - vcpus: the number of vcpus (int)
1384

1385
  """
1386
  output = {}
1387

    
1388
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance,
1389
                                                          hvparams=hvparams)
1390
  if iinfo is not None:
1391
    output["memory"] = iinfo[2]
1392
    output["vcpus"] = iinfo[3]
1393
    output["state"] = iinfo[4]
1394
    output["time"] = iinfo[5]
1395

    
1396
  return output
1397

    
1398

    
1399
def GetInstanceMigratable(instance):
1400
  """Computes whether an instance can be migrated.
1401

1402
  @type instance: L{objects.Instance}
1403
  @param instance: object representing the instance to be checked.
1404

1405
  @rtype: tuple
1406
  @return: tuple of (result, description) where:
1407
      - result: whether the instance can be migrated or not
1408
      - description: a description of the issue, if relevant
1409

1410
  """
1411
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1412
  iname = instance.name
1413
  if iname not in hyper.ListInstances(instance.hvparams):
1414
    _Fail("Instance %s is not running", iname)
1415

    
1416
  for idx in range(len(instance.disks)):
1417
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1418
    if not os.path.islink(link_name):
1419
      logging.warning("Instance %s is missing symlink %s for disk %d",
1420
                      iname, link_name, idx)
1421

    
1422

    
1423
def GetAllInstancesInfo(hypervisor_list, all_hvparams):
1424
  """Gather data about all instances.
1425

1426
  This is the equivalent of L{GetInstanceInfo}, except that it
1427
  computes data for all instances at once, thus being faster if one
1428
  needs data about more than one instance.
1429

1430
  @type hypervisor_list: list
1431
  @param hypervisor_list: list of hypervisors to query for instance data
1432
  @type all_hvparams: dict of dict of strings
1433
  @param all_hvparams: mapping of hypervisor names to hvparams
1434

1435
  @rtype: dict
1436
  @return: dictionary of instance: data, with data having the following keys:
1437
      - memory: memory size of instance (int)
1438
      - state: xen state of instance (string)
1439
      - time: cpu time of instance (float)
1440
      - vcpus: the number of vcpus
1441

1442
  """
1443
  output = {}
1444

    
1445
  for hname in hypervisor_list:
1446
    hvparams = all_hvparams[hname]
1447
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo(hvparams)
1448
    if iinfo:
1449
      for name, _, memory, vcpus, state, times in iinfo:
1450
        value = {
1451
          "memory": memory,
1452
          "vcpus": vcpus,
1453
          "state": state,
1454
          "time": times,
1455
          }
1456
        if name in output:
1457
          # we only check static parameters, like memory and vcpus,
1458
          # and not state and time which can change between the
1459
          # invocations of the different hypervisors
1460
          for key in "memory", "vcpus":
1461
            if value[key] != output[name][key]:
1462
              _Fail("Instance %s is running twice"
1463
                    " with different parameters", name)
1464
        output[name] = value
1465

    
1466
  return output
1467

    
1468

    
1469
def _InstanceLogName(kind, os_name, instance, component):
1470
  """Compute the OS log filename for a given instance and operation.
1471

1472
  The instance name and os name are passed in as strings since not all
1473
  operations have these as part of an instance object.
1474

1475
  @type kind: string
1476
  @param kind: the operation type (e.g. add, import, etc.)
1477
  @type os_name: string
1478
  @param os_name: the os name
1479
  @type instance: string
1480
  @param instance: the name of the instance being imported/added/etc.
1481
  @type component: string or None
1482
  @param component: the name of the component of the instance being
1483
      transferred
1484

1485
  """
1486
  # TODO: Use tempfile.mkstemp to create unique filename
1487
  if component:
1488
    assert "/" not in component
1489
    c_msg = "-%s" % component
1490
  else:
1491
    c_msg = ""
1492
  base = ("%s-%s-%s%s-%s.log" %
1493
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1494
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1495

    
1496

    
1497
def InstanceOsAdd(instance, reinstall, debug):
1498
  """Add an OS to an instance.
1499

1500
  @type instance: L{objects.Instance}
1501
  @param instance: Instance whose OS is to be installed
1502
  @type reinstall: boolean
1503
  @param reinstall: whether this is an instance reinstall
1504
  @type debug: integer
1505
  @param debug: debug level, passed to the OS scripts
1506
  @rtype: None
1507

1508
  """
1509
  inst_os = OSFromDisk(instance.os)
1510

    
1511
  create_env = OSEnvironment(instance, inst_os, debug)
1512
  if reinstall:
1513
    create_env["INSTANCE_REINSTALL"] = "1"
1514

    
1515
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1516

    
1517
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1518
                        cwd=inst_os.path, output=logfile, reset_env=True)
1519
  if result.failed:
1520
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1521
                  " output: %s", result.cmd, result.fail_reason, logfile,
1522
                  result.output)
1523
    lines = [utils.SafeEncode(val)
1524
             for val in utils.TailFile(logfile, lines=20)]
1525
    _Fail("OS create script failed (%s), last lines in the"
1526
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1527

    
1528

    
1529
def RunRenameInstance(instance, old_name, debug):
1530
  """Run the OS rename script for an instance.
1531

1532
  @type instance: L{objects.Instance}
1533
  @param instance: Instance whose OS is to be installed
1534
  @type old_name: string
1535
  @param old_name: previous instance name
1536
  @type debug: integer
1537
  @param debug: debug level, passed to the OS scripts
1538
  @rtype: boolean
1539
  @return: the success of the operation
1540

1541
  """
1542
  inst_os = OSFromDisk(instance.os)
1543

    
1544
  rename_env = OSEnvironment(instance, inst_os, debug)
1545
  rename_env["OLD_INSTANCE_NAME"] = old_name
1546

    
1547
  logfile = _InstanceLogName("rename", instance.os,
1548
                             "%s-%s" % (old_name, instance.name), None)
1549

    
1550
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1551
                        cwd=inst_os.path, output=logfile, reset_env=True)
1552

    
1553
  if result.failed:
1554
    logging.error("os create command '%s' returned error: %s output: %s",
1555
                  result.cmd, result.fail_reason, result.output)
1556
    lines = [utils.SafeEncode(val)
1557
             for val in utils.TailFile(logfile, lines=20)]
1558
    _Fail("OS rename script failed (%s), last lines in the"
1559
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1560

    
1561

    
1562
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1563
  """Returns symlink path for block device.
1564

1565
  """
1566
  if _dir is None:
1567
    _dir = pathutils.DISK_LINKS_DIR
1568

    
1569
  return utils.PathJoin(_dir,
1570
                        ("%s%s%s" %
1571
                         (instance_name, constants.DISK_SEPARATOR, idx)))
1572

    
1573

    
1574
def _SymlinkBlockDev(instance_name, device_path, idx):
1575
  """Set up symlinks to a instance's block device.
1576

1577
  This is an auxiliary function run when an instance is start (on the primary
1578
  node) or when an instance is migrated (on the target node).
1579

1580

1581
  @param instance_name: the name of the target instance
1582
  @param device_path: path of the physical block device, on the node
1583
  @param idx: the disk index
1584
  @return: absolute path to the disk's symlink
1585

1586
  """
1587
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1588
  try:
1589
    os.symlink(device_path, link_name)
1590
  except OSError, err:
1591
    if err.errno == errno.EEXIST:
1592
      if (not os.path.islink(link_name) or
1593
          os.readlink(link_name) != device_path):
1594
        os.remove(link_name)
1595
        os.symlink(device_path, link_name)
1596
    else:
1597
      raise
1598

    
1599
  return link_name
1600

    
1601

    
1602
def _RemoveBlockDevLinks(instance_name, disks):
1603
  """Remove the block device symlinks belonging to the given instance.
1604

1605
  """
1606
  for idx, _ in enumerate(disks):
1607
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1608
    if os.path.islink(link_name):
1609
      try:
1610
        os.remove(link_name)
1611
      except OSError:
1612
        logging.exception("Can't remove symlink '%s'", link_name)
1613

    
1614

    
1615
def _CalculateDeviceURI(instance, disk, device):
1616
  """Get the URI for the device.
1617

1618
  @type instance: L{objects.Instance}
1619
  @param instance: the instance which disk belongs to
1620
  @type disk: L{objects.Disk}
1621
  @param disk: the target disk object
1622
  @type device: L{bdev.BlockDev}
1623
  @param device: the corresponding BlockDevice
1624
  @rtype: string
1625
  @return: the device uri if any else None
1626

1627
  """
1628
  access_mode = disk.params.get(constants.LDP_ACCESS,
1629
                                constants.DISK_KERNELSPACE)
1630
  if access_mode == constants.DISK_USERSPACE:
1631
    # This can raise errors.BlockDeviceError
1632
    return device.GetUserspaceAccessUri(instance.hypervisor)
1633
  else:
1634
    return None
1635

    
1636

    
1637
def _GatherAndLinkBlockDevs(instance):
1638
  """Set up an instance's block device(s).
1639

1640
  This is run on the primary node at instance startup. The block
1641
  devices must be already assembled.
1642

1643
  @type instance: L{objects.Instance}
1644
  @param instance: the instance whose disks we should assemble
1645
  @rtype: list
1646
  @return: list of (disk_object, link_name, drive_uri)
1647

1648
  """
1649
  block_devices = []
1650
  for idx, disk in enumerate(instance.disks):
1651
    device = _RecursiveFindBD(disk)
1652
    if device is None:
1653
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1654
                                    str(disk))
1655
    device.Open()
1656
    try:
1657
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1658
    except OSError, e:
1659
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1660
                                    e.strerror)
1661
    uri = _CalculateDeviceURI(instance, disk, device)
1662

    
1663
    block_devices.append((disk, link_name, uri))
1664

    
1665
  return block_devices
1666

    
1667

    
1668
def StartInstance(instance, startup_paused, reason, store_reason=True):
1669
  """Start an instance.
1670

1671
  @type instance: L{objects.Instance}
1672
  @param instance: the instance object
1673
  @type startup_paused: bool
1674
  @param instance: pause instance at startup?
1675
  @type reason: list of reasons
1676
  @param reason: the reason trail for this startup
1677
  @type store_reason: boolean
1678
  @param store_reason: whether to store the shutdown reason trail on file
1679
  @rtype: None
1680

1681
  """
1682
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1683
                                                   instance.hvparams)
1684

    
1685
  if instance.name in running_instances:
1686
    logging.info("Instance %s already running, not starting", instance.name)
1687
    return
1688

    
1689
  try:
1690
    block_devices = _GatherAndLinkBlockDevs(instance)
1691
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1692
    hyper.StartInstance(instance, block_devices, startup_paused)
1693
    if store_reason:
1694
      _StoreInstReasonTrail(instance.name, reason)
1695
  except errors.BlockDeviceError, err:
1696
    _Fail("Block device error: %s", err, exc=True)
1697
  except errors.HypervisorError, err:
1698
    _RemoveBlockDevLinks(instance.name, instance.disks)
1699
    _Fail("Hypervisor error: %s", err, exc=True)
1700

    
1701

    
1702
def InstanceShutdown(instance, timeout, reason, store_reason=True):
1703
  """Shut an instance down.
1704

1705
  @note: this functions uses polling with a hardcoded timeout.
1706

1707
  @type instance: L{objects.Instance}
1708
  @param instance: the instance object
1709
  @type timeout: integer
1710
  @param timeout: maximum timeout for soft shutdown
1711
  @type reason: list of reasons
1712
  @param reason: the reason trail for this shutdown
1713
  @type store_reason: boolean
1714
  @param store_reason: whether to store the shutdown reason trail on file
1715
  @rtype: None
1716

1717
  """
1718
  hv_name = instance.hypervisor
1719
  hyper = hypervisor.GetHypervisor(hv_name)
1720
  iname = instance.name
1721

    
1722
  if instance.name not in hyper.ListInstances(instance.hvparams):
1723
    logging.info("Instance %s not running, doing nothing", iname)
1724
    return
1725

    
1726
  class _TryShutdown(object):
1727
    def __init__(self):
1728
      self.tried_once = False
1729

    
1730
    def __call__(self):
1731
      if iname not in hyper.ListInstances(instance.hvparams):
1732
        return
1733

    
1734
      try:
1735
        hyper.StopInstance(instance, retry=self.tried_once, timeout=timeout)
1736
        if store_reason:
1737
          _StoreInstReasonTrail(instance.name, reason)
1738
      except errors.HypervisorError, err:
1739
        if iname not in hyper.ListInstances(instance.hvparams):
1740
          # if the instance is no longer existing, consider this a
1741
          # success and go to cleanup
1742
          return
1743

    
1744
        _Fail("Failed to stop instance %s: %s", iname, err)
1745

    
1746
      self.tried_once = True
1747

    
1748
      raise utils.RetryAgain()
1749

    
1750
  try:
1751
    utils.Retry(_TryShutdown(), 5, timeout)
1752
  except utils.RetryTimeout:
1753
    # the shutdown did not succeed
1754
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1755

    
1756
    try:
1757
      hyper.StopInstance(instance, force=True)
1758
    except errors.HypervisorError, err:
1759
      if iname in hyper.ListInstances(instance.hvparams):
1760
        # only raise an error if the instance still exists, otherwise
1761
        # the error could simply be "instance ... unknown"!
1762
        _Fail("Failed to force stop instance %s: %s", iname, err)
1763

    
1764
    time.sleep(1)
1765

    
1766
    if iname in hyper.ListInstances(instance.hvparams):
1767
      _Fail("Could not shutdown instance %s even by destroy", iname)
1768

    
1769
  try:
1770
    hyper.CleanupInstance(instance.name)
1771
  except errors.HypervisorError, err:
1772
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1773

    
1774
  _RemoveBlockDevLinks(iname, instance.disks)
1775

    
1776

    
1777
def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1778
  """Reboot an instance.
1779

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

1799
  """
1800
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1801
                                                   instance.hvparams)
1802

    
1803
  if instance.name not in running_instances:
1804
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1805

    
1806
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1807
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1808
    try:
1809
      hyper.RebootInstance(instance)
1810
    except errors.HypervisorError, err:
1811
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1812
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1813
    try:
1814
      InstanceShutdown(instance, shutdown_timeout, reason, store_reason=False)
1815
      result = StartInstance(instance, False, reason, store_reason=False)
1816
      _StoreInstReasonTrail(instance.name, reason)
1817
      return result
1818
    except errors.HypervisorError, err:
1819
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1820
  else:
1821
    _Fail("Invalid reboot_type received: %s", reboot_type)
1822

    
1823

    
1824
def InstanceBalloonMemory(instance, memory):
1825
  """Resize an instance's memory.
1826

1827
  @type instance: L{objects.Instance}
1828
  @param instance: the instance object
1829
  @type memory: int
1830
  @param memory: new memory amount in MB
1831
  @rtype: None
1832

1833
  """
1834
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1835
  running = hyper.ListInstances(instance.hvparams)
1836
  if instance.name not in running:
1837
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1838
    return
1839
  try:
1840
    hyper.BalloonInstanceMemory(instance, memory)
1841
  except errors.HypervisorError, err:
1842
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1843

    
1844

    
1845
def MigrationInfo(instance):
1846
  """Gather information about an instance to be migrated.
1847

1848
  @type instance: L{objects.Instance}
1849
  @param instance: the instance definition
1850

1851
  """
1852
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1853
  try:
1854
    info = hyper.MigrationInfo(instance)
1855
  except errors.HypervisorError, err:
1856
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1857
  return info
1858

    
1859

    
1860
def AcceptInstance(instance, info, target):
1861
  """Prepare the node to accept an instance.
1862

1863
  @type instance: L{objects.Instance}
1864
  @param instance: the instance definition
1865
  @type info: string/data (opaque)
1866
  @param info: migration information, from the source node
1867
  @type target: string
1868
  @param target: target host (usually ip), on this node
1869

1870
  """
1871
  # TODO: why is this required only for DTS_EXT_MIRROR?
1872
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1873
    # Create the symlinks, as the disks are not active
1874
    # in any way
1875
    try:
1876
      _GatherAndLinkBlockDevs(instance)
1877
    except errors.BlockDeviceError, err:
1878
      _Fail("Block device error: %s", err, exc=True)
1879

    
1880
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1881
  try:
1882
    hyper.AcceptInstance(instance, info, target)
1883
  except errors.HypervisorError, err:
1884
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1885
      _RemoveBlockDevLinks(instance.name, instance.disks)
1886
    _Fail("Failed to accept instance: %s", err, exc=True)
1887

    
1888

    
1889
def FinalizeMigrationDst(instance, info, success):
1890
  """Finalize any preparation to accept an instance.
1891

1892
  @type instance: L{objects.Instance}
1893
  @param instance: the instance definition
1894
  @type info: string/data (opaque)
1895
  @param info: migration information, from the source node
1896
  @type success: boolean
1897
  @param success: whether the migration was a success or a failure
1898

1899
  """
1900
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1901
  try:
1902
    hyper.FinalizeMigrationDst(instance, info, success)
1903
  except errors.HypervisorError, err:
1904
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1905

    
1906

    
1907
def MigrateInstance(cluster_name, instance, target, live):
1908
  """Migrates an instance to another node.
1909

1910
  @type cluster_name: string
1911
  @param cluster_name: name of the cluster
1912
  @type instance: L{objects.Instance}
1913
  @param instance: the instance definition
1914
  @type target: string
1915
  @param target: the target node name
1916
  @type live: boolean
1917
  @param live: whether the migration should be done live or not (the
1918
      interpretation of this parameter is left to the hypervisor)
1919
  @raise RPCFail: if migration fails for some reason
1920

1921
  """
1922
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1923

    
1924
  try:
1925
    hyper.MigrateInstance(cluster_name, instance, target, live)
1926
  except errors.HypervisorError, err:
1927
    _Fail("Failed to migrate instance: %s", err, exc=True)
1928

    
1929

    
1930
def FinalizeMigrationSource(instance, success, live):
1931
  """Finalize the instance migration on the source node.
1932

1933
  @type instance: L{objects.Instance}
1934
  @param instance: the instance definition of the migrated instance
1935
  @type success: bool
1936
  @param success: whether the migration succeeded or not
1937
  @type live: bool
1938
  @param live: whether the user requested a live migration or not
1939
  @raise RPCFail: If the execution fails for some reason
1940

1941
  """
1942
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1943

    
1944
  try:
1945
    hyper.FinalizeMigrationSource(instance, success, live)
1946
  except Exception, err:  # pylint: disable=W0703
1947
    _Fail("Failed to finalize the migration on the source node: %s", err,
1948
          exc=True)
1949

    
1950

    
1951
def GetMigrationStatus(instance):
1952
  """Get the migration status
1953

1954
  @type instance: L{objects.Instance}
1955
  @param instance: the instance that is being migrated
1956
  @rtype: L{objects.MigrationStatus}
1957
  @return: the status of the current migration (one of
1958
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1959
           progress info that can be retrieved from the hypervisor
1960
  @raise RPCFail: If the migration status cannot be retrieved
1961

1962
  """
1963
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1964
  try:
1965
    return hyper.GetMigrationStatus(instance)
1966
  except Exception, err:  # pylint: disable=W0703
1967
    _Fail("Failed to get migration status: %s", err, exc=True)
1968

    
1969

    
1970
def HotplugDevice(instance, action, dev_type, device, extra, seq):
1971
  """Hotplug a device
1972

1973
  Hotplug is currently supported only for KVM Hypervisor.
1974
  @type instance: L{objects.Instance}
1975
  @param instance: the instance to which we hotplug a device
1976
  @type action: string
1977
  @param action: the hotplug action to perform
1978
  @type dev_type: string
1979
  @param dev_type: the device type to hotplug
1980
  @type device: either L{objects.NIC} or L{objects.Disk}
1981
  @param device: the device object to hotplug
1982
  @type extra: string
1983
  @param extra: extra info used by hotplug code (e.g. disk link)
1984
  @type seq: int
1985
  @param seq: the index of the device from master perspective
1986
  @raise RPCFail: in case instance does not have KVM hypervisor
1987

1988
  """
1989
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1990
  try:
1991
    hyper.VerifyHotplugSupport(instance, action, dev_type)
1992
  except errors.HotplugError, err:
1993
    _Fail("Hotplug is not supported: %s", err)
1994

    
1995
  if action == constants.HOTPLUG_ACTION_ADD:
1996
    fn = hyper.HotAddDevice
1997
  elif action == constants.HOTPLUG_ACTION_REMOVE:
1998
    fn = hyper.HotDelDevice
1999
  elif action == constants.HOTPLUG_ACTION_MODIFY:
2000
    fn = hyper.HotModDevice
2001
  else:
2002
    assert action in constants.HOTPLUG_ALL_ACTIONS
2003

    
2004
  return fn(instance, dev_type, device, extra, seq)
2005

    
2006

    
2007
def HotplugSupported(instance):
2008
  """Checks if hotplug is generally supported.
2009

2010
  """
2011
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
2012
  try:
2013
    hyper.HotplugSupported(instance)
2014
  except errors.HotplugError, err:
2015
    _Fail("Hotplug is not supported: %s", err)
2016

    
2017

    
2018
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
2019
  """Creates a block device for an instance.
2020

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

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

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

    
2060
  try:
2061
    device = bdev.Create(disk, clist, excl_stor)
2062
  except errors.BlockDeviceError, err:
2063
    _Fail("Can't create block device: %s", err)
2064

    
2065
  if on_primary or disk.AssembleOnSecondary():
2066
    try:
2067
      device.Assemble()
2068
    except errors.BlockDeviceError, err:
2069
      _Fail("Can't assemble device after creation, unusual event: %s", err)
2070
    if on_primary or disk.OpenOnSecondary():
2071
      try:
2072
        device.Open(force=True)
2073
      except errors.BlockDeviceError, err:
2074
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
2075
    DevCacheManager.UpdateCache(device.dev_path, owner,
2076
                                on_primary, disk.iv_name)
2077

    
2078
  device.SetInfo(info)
2079

    
2080
  return device.unique_id
2081

    
2082

    
2083
def _WipeDevice(path, offset, size):
2084
  """This function actually wipes the device.
2085

2086
  @param path: The path to the device to wipe
2087
  @param offset: The offset in MiB in the file
2088
  @param size: The size in MiB to write
2089

2090
  """
2091
  # Internal sizes are always in Mebibytes; if the following "dd" command
2092
  # should use a different block size the offset and size given to this
2093
  # function must be adjusted accordingly before being passed to "dd".
2094
  block_size = 1024 * 1024
2095

    
2096
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
2097
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
2098
         "count=%d" % size]
2099
  result = utils.RunCmd(cmd)
2100

    
2101
  if result.failed:
2102
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
2103
          result.fail_reason, result.output)
2104

    
2105

    
2106
def BlockdevWipe(disk, offset, size):
2107
  """Wipes a block device.
2108

2109
  @type disk: L{objects.Disk}
2110
  @param disk: the disk object we want to wipe
2111
  @type offset: int
2112
  @param offset: The offset in MiB in the file
2113
  @type size: int
2114
  @param size: The size in MiB to write
2115

2116
  """
2117
  try:
2118
    rdev = _RecursiveFindBD(disk)
2119
  except errors.BlockDeviceError:
2120
    rdev = None
2121

    
2122
  if not rdev:
2123
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
2124

    
2125
  # Do cross verify some of the parameters
2126
  if offset < 0:
2127
    _Fail("Negative offset")
2128
  if size < 0:
2129
    _Fail("Negative size")
2130
  if offset > rdev.size:
2131
    _Fail("Offset is bigger than device size")
2132
  if (offset + size) > rdev.size:
2133
    _Fail("The provided offset and size to wipe is bigger than device size")
2134

    
2135
  _WipeDevice(rdev.dev_path, offset, size)
2136

    
2137

    
2138
def BlockdevPauseResumeSync(disks, pause):
2139
  """Pause or resume the sync of the block device.
2140

2141
  @type disks: list of L{objects.Disk}
2142
  @param disks: the disks object we want to pause/resume
2143
  @type pause: bool
2144
  @param pause: Wheater to pause or resume
2145

2146
  """
2147
  success = []
2148
  for disk in disks:
2149
    try:
2150
      rdev = _RecursiveFindBD(disk)
2151
    except errors.BlockDeviceError:
2152
      rdev = None
2153

    
2154
    if not rdev:
2155
      success.append((False, ("Cannot change sync for device %s:"
2156
                              " device not found" % disk.iv_name)))
2157
      continue
2158

    
2159
    result = rdev.PauseResumeSync(pause)
2160

    
2161
    if result:
2162
      success.append((result, None))
2163
    else:
2164
      if pause:
2165
        msg = "Pause"
2166
      else:
2167
        msg = "Resume"
2168
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
2169

    
2170
  return success
2171

    
2172

    
2173
def BlockdevRemove(disk):
2174
  """Remove a block device.
2175

2176
  @note: This is intended to be called recursively.
2177

2178
  @type disk: L{objects.Disk}
2179
  @param disk: the disk object we should remove
2180
  @rtype: boolean
2181
  @return: the success of the operation
2182

2183
  """
2184
  msgs = []
2185
  try:
2186
    rdev = _RecursiveFindBD(disk)
2187
  except errors.BlockDeviceError, err:
2188
    # probably can't attach
2189
    logging.info("Can't attach to device %s in remove", disk)
2190
    rdev = None
2191
  if rdev is not None:
2192
    r_path = rdev.dev_path
2193

    
2194
    def _TryRemove():
2195
      try:
2196
        rdev.Remove()
2197
        return []
2198
      except errors.BlockDeviceError, err:
2199
        return [str(err)]
2200

    
2201
    msgs.extend(utils.SimpleRetry([], _TryRemove,
2202
                                  constants.DISK_REMOVE_RETRY_INTERVAL,
2203
                                  constants.DISK_REMOVE_RETRY_TIMEOUT))
2204

    
2205
    if not msgs:
2206
      DevCacheManager.RemoveCache(r_path)
2207

    
2208
  if disk.children:
2209
    for child in disk.children:
2210
      try:
2211
        BlockdevRemove(child)
2212
      except RPCFail, err:
2213
        msgs.append(str(err))
2214

    
2215
  if msgs:
2216
    _Fail("; ".join(msgs))
2217

    
2218

    
2219
def _RecursiveAssembleBD(disk, owner, as_primary):
2220
  """Activate a block device for an instance.
2221

2222
  This is run on the primary and secondary nodes for an instance.
2223

2224
  @note: this function is called recursively.
2225

2226
  @type disk: L{objects.Disk}
2227
  @param disk: the disk we try to assemble
2228
  @type owner: str
2229
  @param owner: the name of the instance which owns the disk
2230
  @type as_primary: boolean
2231
  @param as_primary: if we should make the block device
2232
      read/write
2233

2234
  @return: the assembled device or None (in case no device
2235
      was assembled)
2236
  @raise errors.BlockDeviceError: in case there is an error
2237
      during the activation of the children or the device
2238
      itself
2239

2240
  """
2241
  children = []
2242
  if disk.children:
2243
    mcn = disk.ChildrenNeeded()
2244
    if mcn == -1:
2245
      mcn = 0 # max number of Nones allowed
2246
    else:
2247
      mcn = len(disk.children) - mcn # max number of Nones
2248
    for chld_disk in disk.children:
2249
      try:
2250
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
2251
      except errors.BlockDeviceError, err:
2252
        if children.count(None) >= mcn:
2253
          raise
2254
        cdev = None
2255
        logging.error("Error in child activation (but continuing): %s",
2256
                      str(err))
2257
      children.append(cdev)
2258

    
2259
  if as_primary or disk.AssembleOnSecondary():
2260
    r_dev = bdev.Assemble(disk, children)
2261
    result = r_dev
2262
    if as_primary or disk.OpenOnSecondary():
2263
      r_dev.Open()
2264
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
2265
                                as_primary, disk.iv_name)
2266

    
2267
  else:
2268
    result = True
2269
  return result
2270

    
2271

    
2272
def BlockdevAssemble(disk, owner, as_primary, idx):
2273
  """Activate a block device for an instance.
2274

2275
  This is a wrapper over _RecursiveAssembleBD.
2276

2277
  @rtype: str or boolean
2278
  @return: a tuple with the C{/dev/...} path and the created symlink
2279
      for primary nodes, and (C{True}, C{True}) for secondary nodes
2280

2281
  """
2282
  try:
2283
    result = _RecursiveAssembleBD(disk, owner, as_primary)
2284
    if isinstance(result, BlockDev):
2285
      # pylint: disable=E1103
2286
      dev_path = result.dev_path
2287
      link_name = None
2288
      if as_primary:
2289
        link_name = _SymlinkBlockDev(owner, dev_path, idx)
2290
    elif result:
2291
      return result, result
2292
    else:
2293
      _Fail("Unexpected result from _RecursiveAssembleBD")
2294
  except errors.BlockDeviceError, err:
2295
    _Fail("Error while assembling disk: %s", err, exc=True)
2296
  except OSError, err:
2297
    _Fail("Error while symlinking disk: %s", err, exc=True)
2298

    
2299
  return dev_path, link_name
2300

    
2301

    
2302
def BlockdevShutdown(disk):
2303
  """Shut down a block device.
2304

2305
  First, if the device is assembled (Attach() is successful), then
2306
  the device is shutdown. Then the children of the device are
2307
  shutdown.
2308

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

2313
  @type disk: L{objects.Disk}
2314
  @param disk: the description of the disk we should
2315
      shutdown
2316
  @rtype: None
2317

2318
  """
2319
  msgs = []
2320
  r_dev = _RecursiveFindBD(disk)
2321
  if r_dev is not None:
2322
    r_path = r_dev.dev_path
2323
    try:
2324
      r_dev.Shutdown()
2325
      DevCacheManager.RemoveCache(r_path)
2326
    except errors.BlockDeviceError, err:
2327
      msgs.append(str(err))
2328

    
2329
  if disk.children:
2330
    for child in disk.children:
2331
      try:
2332
        BlockdevShutdown(child)
2333
      except RPCFail, err:
2334
        msgs.append(str(err))
2335

    
2336
  if msgs:
2337
    _Fail("; ".join(msgs))
2338

    
2339

    
2340
def BlockdevAddchildren(parent_cdev, new_cdevs):
2341
  """Extend a mirrored block device.
2342

2343
  @type parent_cdev: L{objects.Disk}
2344
  @param parent_cdev: the disk to which we should add children
2345
  @type new_cdevs: list of L{objects.Disk}
2346
  @param new_cdevs: the list of children which we should add
2347
  @rtype: None
2348

2349
  """
2350
  parent_bdev = _RecursiveFindBD(parent_cdev)
2351
  if parent_bdev is None:
2352
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
2353
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
2354
  if new_bdevs.count(None) > 0:
2355
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
2356
  parent_bdev.AddChildren(new_bdevs)
2357

    
2358

    
2359
def BlockdevRemovechildren(parent_cdev, new_cdevs):
2360
  """Shrink a mirrored block device.
2361

2362
  @type parent_cdev: L{objects.Disk}
2363
  @param parent_cdev: the disk from which we should remove children
2364
  @type new_cdevs: list of L{objects.Disk}
2365
  @param new_cdevs: the list of children which we should remove
2366
  @rtype: None
2367

2368
  """
2369
  parent_bdev = _RecursiveFindBD(parent_cdev)
2370
  if parent_bdev is None:
2371
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
2372
  devs = []
2373
  for disk in new_cdevs:
2374
    rpath = disk.StaticDevPath()
2375
    if rpath is None:
2376
      bd = _RecursiveFindBD(disk)
2377
      if bd is None:
2378
        _Fail("Can't find device %s while removing children", disk)
2379
      else:
2380
        devs.append(bd.dev_path)
2381
    else:
2382
      if not utils.IsNormAbsPath(rpath):
2383
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
2384
      devs.append(rpath)
2385
  parent_bdev.RemoveChildren(devs)
2386

    
2387

    
2388
def BlockdevGetmirrorstatus(disks):
2389
  """Get the mirroring status of a list of devices.
2390

2391
  @type disks: list of L{objects.Disk}
2392
  @param disks: the list of disks which we should query
2393
  @rtype: disk
2394
  @return: List of L{objects.BlockDevStatus}, one for each disk
2395
  @raise errors.BlockDeviceError: if any of the disks cannot be
2396
      found
2397

2398
  """
2399
  stats = []
2400
  for dsk in disks:
2401
    rbd = _RecursiveFindBD(dsk)
2402
    if rbd is None:
2403
      _Fail("Can't find device %s", dsk)
2404

    
2405
    stats.append(rbd.CombinedSyncStatus())
2406

    
2407
  return stats
2408

    
2409

    
2410
def BlockdevGetmirrorstatusMulti(disks):
2411
  """Get the mirroring status of a list of devices.
2412

2413
  @type disks: list of L{objects.Disk}
2414
  @param disks: the list of disks which we should query
2415
  @rtype: disk
2416
  @return: List of tuples, (bool, status), one for each disk; bool denotes
2417
    success/failure, status is L{objects.BlockDevStatus} on success, string
2418
    otherwise
2419

2420
  """
2421
  result = []
2422
  for disk in disks:
2423
    try:
2424
      rbd = _RecursiveFindBD(disk)
2425
      if rbd is None:
2426
        result.append((False, "Can't find device %s" % disk))
2427
        continue
2428

    
2429
      status = rbd.CombinedSyncStatus()
2430
    except errors.BlockDeviceError, err:
2431
      logging.exception("Error while getting disk status")
2432
      result.append((False, str(err)))
2433
    else:
2434
      result.append((True, status))
2435

    
2436
  assert len(disks) == len(result)
2437

    
2438
  return result
2439

    
2440

    
2441
def _RecursiveFindBD(disk):
2442
  """Check if a device is activated.
2443

2444
  If so, return information about the real device.
2445

2446
  @type disk: L{objects.Disk}
2447
  @param disk: the disk object we need to find
2448

2449
  @return: None if the device can't be found,
2450
      otherwise the device instance
2451

2452
  """
2453
  children = []
2454
  if disk.children:
2455
    for chdisk in disk.children:
2456
      children.append(_RecursiveFindBD(chdisk))
2457

    
2458
  return bdev.FindDevice(disk, children)
2459

    
2460

    
2461
def _OpenRealBD(disk):
2462
  """Opens the underlying block device of a disk.
2463

2464
  @type disk: L{objects.Disk}
2465
  @param disk: the disk object we want to open
2466

2467
  """
2468
  real_disk = _RecursiveFindBD(disk)
2469
  if real_disk is None:
2470
    _Fail("Block device '%s' is not set up", disk)
2471

    
2472
  real_disk.Open()
2473

    
2474
  return real_disk
2475

    
2476

    
2477
def BlockdevFind(disk):
2478
  """Check if a device is activated.
2479

2480
  If it is, return information about the real device.
2481

2482
  @type disk: L{objects.Disk}
2483
  @param disk: the disk to find
2484
  @rtype: None or objects.BlockDevStatus
2485
  @return: None if the disk cannot be found, otherwise a the current
2486
           information
2487

2488
  """
2489
  try:
2490
    rbd = _RecursiveFindBD(disk)
2491
  except errors.BlockDeviceError, err:
2492
    _Fail("Failed to find device: %s", err, exc=True)
2493

    
2494
  if rbd is None:
2495
    return None
2496

    
2497
  return rbd.GetSyncStatus()
2498

    
2499

    
2500
def BlockdevGetdimensions(disks):
2501
  """Computes the size of the given disks.
2502

2503
  If a disk is not found, returns None instead.
2504

2505
  @type disks: list of L{objects.Disk}
2506
  @param disks: the list of disk to compute the size for
2507
  @rtype: list
2508
  @return: list with elements None if the disk cannot be found,
2509
      otherwise the pair (size, spindles), where spindles is None if the
2510
      device doesn't support that
2511

2512
  """
2513
  result = []
2514
  for cf in disks:
2515
    try:
2516
      rbd = _RecursiveFindBD(cf)
2517
    except errors.BlockDeviceError:
2518
      result.append(None)
2519
      continue
2520
    if rbd is None:
2521
      result.append(None)
2522
    else:
2523
      result.append(rbd.GetActualDimensions())
2524
  return result
2525

    
2526

    
2527
def BlockdevExport(disk, dest_node_ip, dest_path, cluster_name):
2528
  """Export a block device to a remote node.
2529

2530
  @type disk: L{objects.Disk}
2531
  @param disk: the description of the disk to export
2532
  @type dest_node_ip: str
2533
  @param dest_node_ip: the destination node IP to export to
2534
  @type dest_path: str
2535
  @param dest_path: the destination path on the target node
2536
  @type cluster_name: str
2537
  @param cluster_name: the cluster name, needed for SSH hostalias
2538
  @rtype: None
2539

2540
  """
2541
  real_disk = _OpenRealBD(disk)
2542

    
2543
  # the block size on the read dd is 1MiB to match our units
2544
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2545
                               "dd if=%s bs=1048576 count=%s",
2546
                               real_disk.dev_path, str(disk.size))
2547

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

    
2557
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node_ip,
2558
                                                   constants.SSH_LOGIN_USER,
2559
                                                   destcmd)
2560

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

    
2564
  result = utils.RunCmd(["bash", "-c", command])
2565

    
2566
  if result.failed:
2567
    _Fail("Disk copy command '%s' returned error: %s"
2568
          " output: %s", command, result.fail_reason, result.output)
2569

    
2570

    
2571
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2572
  """Write a file to the filesystem.
2573

2574
  This allows the master to overwrite(!) a file. It will only perform
2575
  the operation if the file belongs to a list of configuration files.
2576

2577
  @type file_name: str
2578
  @param file_name: the target file name
2579
  @type data: str
2580
  @param data: the new contents of the file
2581
  @type mode: int
2582
  @param mode: the mode to give the file (can be None)
2583
  @type uid: string
2584
  @param uid: the owner of the file
2585
  @type gid: string
2586
  @param gid: the group of the file
2587
  @type atime: float
2588
  @param atime: the atime to set on the file (can be None)
2589
  @type mtime: float
2590
  @param mtime: the mtime to set on the file (can be None)
2591
  @rtype: None
2592

2593
  """
2594
  file_name = vcluster.LocalizeVirtualPath(file_name)
2595

    
2596
  if not os.path.isabs(file_name):
2597
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2598

    
2599
  if file_name not in _ALLOWED_UPLOAD_FILES:
2600
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2601
          file_name)
2602

    
2603
  raw_data = _Decompress(data)
2604

    
2605
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2606
    _Fail("Invalid username/groupname type")
2607

    
2608
  getents = runtime.GetEnts()
2609
  uid = getents.LookupUser(uid)
2610
  gid = getents.LookupGroup(gid)
2611

    
2612
  utils.SafeWriteFile(file_name, None,
2613
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2614
                      atime=atime, mtime=mtime)
2615

    
2616

    
2617
def RunOob(oob_program, command, node, timeout):
2618
  """Executes oob_program with given command on given node.
2619

2620
  @param oob_program: The path to the executable oob_program
2621
  @param command: The command to invoke on oob_program
2622
  @param node: The node given as an argument to the program
2623
  @param timeout: Timeout after which we kill the oob program
2624

2625
  @return: stdout
2626
  @raise RPCFail: If execution fails for some reason
2627

2628
  """
2629
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2630

    
2631
  if result.failed:
2632
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2633
          result.fail_reason, result.output)
2634

    
2635
  return result.stdout
2636

    
2637

    
2638
def _OSOndiskAPIVersion(os_dir):
2639
  """Compute and return the API version of a given OS.
2640

2641
  This function will try to read the API version of the OS residing in
2642
  the 'os_dir' directory.
2643

2644
  @type os_dir: str
2645
  @param os_dir: the directory in which we should look for the OS
2646
  @rtype: tuple
2647
  @return: tuple (status, data) with status denoting the validity and
2648
      data holding either the vaid versions or an error message
2649

2650
  """
2651
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2652

    
2653
  try:
2654
    st = os.stat(api_file)
2655
  except EnvironmentError, err:
2656
    return False, ("Required file '%s' not found under path %s: %s" %
2657
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2658

    
2659
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2660
    return False, ("File '%s' in %s is not a regular file" %
2661
                   (constants.OS_API_FILE, os_dir))
2662

    
2663
  try:
2664
    api_versions = utils.ReadFile(api_file).splitlines()
2665
  except EnvironmentError, err:
2666
    return False, ("Error while reading the API version file at %s: %s" %
2667
                   (api_file, utils.ErrnoOrStr(err)))
2668

    
2669
  try:
2670
    api_versions = [int(version.strip()) for version in api_versions]
2671
  except (TypeError, ValueError), err:
2672
    return False, ("API version(s) can't be converted to integer: %s" %
2673
                   str(err))
2674

    
2675
  return True, api_versions
2676

    
2677

    
2678
def DiagnoseOS(top_dirs=None):
2679
  """Compute the validity for all OSes.
2680

2681
  @type top_dirs: list
2682
  @param top_dirs: the list of directories in which to
2683
      search (if not given defaults to
2684
      L{pathutils.OS_SEARCH_PATH})
2685
  @rtype: list of L{objects.OS}
2686
  @return: a list of tuples (name, path, status, diagnose, variants,
2687
      parameters, api_version) for all (potential) OSes under all
2688
      search paths, where:
2689
          - name is the (potential) OS name
2690
          - path is the full path to the OS
2691
          - status True/False is the validity of the OS
2692
          - diagnose is the error message for an invalid OS, otherwise empty
2693
          - variants is a list of supported OS variants, if any
2694
          - parameters is a list of (name, help) parameters, if any
2695
          - api_version is a list of support OS API versions
2696

2697
  """
2698
  if top_dirs is None:
2699
    top_dirs = pathutils.OS_SEARCH_PATH
2700

    
2701
  result = []
2702
  for dir_name in top_dirs:
2703
    if os.path.isdir(dir_name):
2704
      try:
2705
        f_names = utils.ListVisibleFiles(dir_name)
2706
      except EnvironmentError, err:
2707
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2708
        break
2709
      for name in f_names:
2710
        os_path = utils.PathJoin(dir_name, name)
2711
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2712
        if status:
2713
          diagnose = ""
2714
          variants = os_inst.supported_variants
2715
          parameters = os_inst.supported_parameters
2716
          api_versions = os_inst.api_versions
2717
        else:
2718
          diagnose = os_inst
2719
          variants = parameters = api_versions = []
2720
        result.append((name, os_path, status, diagnose, variants,
2721
                       parameters, api_versions))
2722

    
2723
  return result
2724

    
2725

    
2726
def _TryOSFromDisk(name, base_dir=None):
2727
  """Create an OS instance from disk.
2728

2729
  This function will return an OS instance if the given name is a
2730
  valid OS name.
2731

2732
  @type base_dir: string
2733
  @keyword base_dir: Base directory containing OS installations.
2734
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2735
  @rtype: tuple
2736
  @return: success and either the OS instance if we find a valid one,
2737
      or error message
2738

2739
  """
2740
  if base_dir is None:
2741
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2742
  else:
2743
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2744

    
2745
  if os_dir is None:
2746
    return False, "Directory for OS %s not found in search path" % name
2747

    
2748
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2749
  if not status:
2750
    # push the error up
2751
    return status, api_versions
2752

    
2753
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2754
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2755
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2756

    
2757
  # OS Files dictionary, we will populate it with the absolute path
2758
  # names; if the value is True, then it is a required file, otherwise
2759
  # an optional one
2760
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2761

    
2762
  if max(api_versions) >= constants.OS_API_V15:
2763
    os_files[constants.OS_VARIANTS_FILE] = False
2764

    
2765
  if max(api_versions) >= constants.OS_API_V20:
2766
    os_files[constants.OS_PARAMETERS_FILE] = True
2767
  else:
2768
    del os_files[constants.OS_SCRIPT_VERIFY]
2769

    
2770
  for (filename, required) in os_files.items():
2771
    os_files[filename] = utils.PathJoin(os_dir, filename)
2772

    
2773
    try:
2774
      st = os.stat(os_files[filename])
2775
    except EnvironmentError, err:
2776
      if err.errno == errno.ENOENT and not required:
2777
        del os_files[filename]
2778
        continue
2779
      return False, ("File '%s' under path '%s' is missing (%s)" %
2780
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2781

    
2782
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2783
      return False, ("File '%s' under path '%s' is not a regular file" %
2784
                     (filename, os_dir))
2785

    
2786
    if filename in constants.OS_SCRIPTS:
2787
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2788
        return False, ("File '%s' under path '%s' is not executable" %
2789
                       (filename, os_dir))
2790

    
2791
  variants = []
2792
  if constants.OS_VARIANTS_FILE in os_files:
2793
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2794
    try:
2795
      variants = \
2796
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2797
    except EnvironmentError, err:
2798
      # we accept missing files, but not other errors
2799
      if err.errno != errno.ENOENT:
2800
        return False, ("Error while reading the OS variants file at %s: %s" %
2801
                       (variants_file, utils.ErrnoOrStr(err)))
2802

    
2803
  parameters = []
2804
  if constants.OS_PARAMETERS_FILE in os_files:
2805
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2806
    try:
2807
      parameters = utils.ReadFile(parameters_file).splitlines()
2808
    except EnvironmentError, err:
2809
      return False, ("Error while reading the OS parameters file at %s: %s" %
2810
                     (parameters_file, utils.ErrnoOrStr(err)))
2811
    parameters = [v.split(None, 1) for v in parameters]
2812

    
2813
  os_obj = objects.OS(name=name, path=os_dir,
2814
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2815
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2816
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2817
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2818
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2819
                                                 None),
2820
                      supported_variants=variants,
2821
                      supported_parameters=parameters,
2822
                      api_versions=api_versions)
2823
  return True, os_obj
2824

    
2825

    
2826
def OSFromDisk(name, base_dir=None):
2827
  """Create an OS instance from disk.
2828

2829
  This function will return an OS instance if the given name is a
2830
  valid OS name. Otherwise, it will raise an appropriate
2831
  L{RPCFail} exception, detailing why this is not a valid OS.
2832

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

2836
  @type base_dir: string
2837
  @keyword base_dir: Base directory containing OS installations.
2838
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2839
  @rtype: L{objects.OS}
2840
  @return: the OS instance if we find a valid one
2841
  @raise RPCFail: if we don't find a valid OS
2842

2843
  """
2844
  name_only = objects.OS.GetName(name)
2845
  status, payload = _TryOSFromDisk(name_only, base_dir)
2846

    
2847
  if not status:
2848
    _Fail(payload)
2849

    
2850
  return payload
2851

    
2852

    
2853
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2854
  """Calculate the basic environment for an os script.
2855

2856
  @type os_name: str
2857
  @param os_name: full operating system name (including variant)
2858
  @type inst_os: L{objects.OS}
2859
  @param inst_os: operating system for which the environment is being built
2860
  @type os_params: dict
2861
  @param os_params: the OS parameters
2862
  @type debug: integer
2863
  @param debug: debug level (0 or 1, for OS Api 10)
2864
  @rtype: dict
2865
  @return: dict of environment variables
2866
  @raise errors.BlockDeviceError: if the block device
2867
      cannot be found
2868

2869
  """
2870
  result = {}
2871
  api_version = \
2872
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2873
  result["OS_API_VERSION"] = "%d" % api_version
2874
  result["OS_NAME"] = inst_os.name
2875
  result["DEBUG_LEVEL"] = "%d" % debug
2876

    
2877
  # OS variants
2878
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2879
    variant = objects.OS.GetVariant(os_name)
2880
    if not variant:
2881
      variant = inst_os.supported_variants[0]
2882
  else:
2883
    variant = ""
2884
  result["OS_VARIANT"] = variant
2885

    
2886
  # OS params
2887
  for pname, pvalue in os_params.items():
2888
    result["OSP_%s" % pname.upper()] = pvalue
2889

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

    
2895
  return result
2896

    
2897

    
2898
def OSEnvironment(instance, inst_os, debug=0):
2899
  """Calculate the environment for an os script.
2900

2901
  @type instance: L{objects.Instance}
2902
  @param instance: target instance for the os script run
2903
  @type inst_os: L{objects.OS}
2904
  @param inst_os: operating system for which the environment is being built
2905
  @type debug: integer
2906
  @param debug: debug level (0 or 1, for OS Api 10)
2907
  @rtype: dict
2908
  @return: dict of environment variables
2909
  @raise errors.BlockDeviceError: if the block device
2910
      cannot be found
2911

2912
  """
2913
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2914

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

    
2918
  result["HYPERVISOR"] = instance.hypervisor
2919
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2920
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2921
  result["INSTANCE_SECONDARY_NODES"] = \
2922
      ("%s" % " ".join(instance.secondary_nodes))
2923

    
2924
  # Disks
2925
  for idx, disk in enumerate(instance.disks):
2926
    real_disk = _OpenRealBD(disk)
2927
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2928
    result["DISK_%d_ACCESS" % idx] = disk.mode
2929
    result["DISK_%d_UUID" % idx] = disk.uuid
2930
    if disk.name:
2931
      result["DISK_%d_NAME" % idx] = disk.name
2932
    if constants.HV_DISK_TYPE in instance.hvparams:
2933
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2934
        instance.hvparams[constants.HV_DISK_TYPE]
2935
    if disk.dev_type in constants.DTS_BLOCK:
2936
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2937
    elif disk.dev_type in [constants.DT_FILE, constants.DT_SHARED_FILE]:
2938
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2939
        "file:%s" % disk.logical_id[0]
2940

    
2941
  # NICs
2942
  for idx, nic in enumerate(instance.nics):
2943
    result["NIC_%d_MAC" % idx] = nic.mac
2944
    result["NIC_%d_UUID" % idx] = nic.uuid
2945
    if nic.name:
2946
      result["NIC_%d_NAME" % idx] = nic.name
2947
    if nic.ip:
2948
      result["NIC_%d_IP" % idx] = nic.ip
2949
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2950
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2951
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2952
    if nic.nicparams[constants.NIC_LINK]:
2953
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2954
    if nic.netinfo:
2955
      nobj = objects.Network.FromDict(nic.netinfo)
2956
      result.update(nobj.HooksDict("NIC_%d_" % idx))
2957
    if constants.HV_NIC_TYPE in instance.hvparams:
2958
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2959
        instance.hvparams[constants.HV_NIC_TYPE]
2960

    
2961
  # HV/BE params
2962
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2963
    for key, value in source.items():
2964
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2965

    
2966
  return result
2967

    
2968

    
2969
def DiagnoseExtStorage(top_dirs=None):
2970
  """Compute the validity for all ExtStorage Providers.
2971

2972
  @type top_dirs: list
2973
  @param top_dirs: the list of directories in which to
2974
      search (if not given defaults to
2975
      L{pathutils.ES_SEARCH_PATH})
2976
  @rtype: list of L{objects.ExtStorage}
2977
  @return: a list of tuples (name, path, status, diagnose, parameters)
2978
      for all (potential) ExtStorage Providers under all
2979
      search paths, where:
2980
          - name is the (potential) ExtStorage Provider
2981
          - path is the full path to the ExtStorage Provider
2982
          - status True/False is the validity of the ExtStorage Provider
2983
          - diagnose is the error message for an invalid ExtStorage Provider,
2984
            otherwise empty
2985
          - parameters is a list of (name, help) parameters, if any
2986

2987
  """
2988
  if top_dirs is None:
2989
    top_dirs = pathutils.ES_SEARCH_PATH
2990

    
2991
  result = []
2992
  for dir_name in top_dirs:
2993
    if os.path.isdir(dir_name):
2994
      try:
2995
        f_names = utils.ListVisibleFiles(dir_name)
2996
      except EnvironmentError, err:
2997
        logging.exception("Can't list the ExtStorage directory %s: %s",
2998
                          dir_name, err)
2999
        break
3000
      for name in f_names:
3001
        es_path = utils.PathJoin(dir_name, name)
3002
        status, es_inst = extstorage.ExtStorageFromDisk(name, base_dir=dir_name)
3003
        if status:
3004
          diagnose = ""
3005
          parameters = es_inst.supported_parameters
3006
        else:
3007
          diagnose = es_inst
3008
          parameters = []
3009
        result.append((name, es_path, status, diagnose, parameters))
3010

    
3011
  return result
3012

    
3013

    
3014
def BlockdevGrow(disk, amount, dryrun, backingstore, excl_stor):
3015
  """Grow a stack of block devices.
3016

3017
  This function is called recursively, with the childrens being the
3018
  first ones to resize.
3019

3020
  @type disk: L{objects.Disk}
3021
  @param disk: the disk to be grown
3022
  @type amount: integer
3023
  @param amount: the amount (in mebibytes) to grow with
3024
  @type dryrun: boolean
3025
  @param dryrun: whether to execute the operation in simulation mode
3026
      only, without actually increasing the size
3027
  @param backingstore: whether to execute the operation on backing storage
3028
      only, or on "logical" storage only; e.g. DRBD is logical storage,
3029
      whereas LVM, file, RBD are backing storage
3030
  @rtype: (status, result)
3031
  @type excl_stor: boolean
3032
  @param excl_stor: Whether exclusive_storage is active
3033
  @return: a tuple with the status of the operation (True/False), and
3034
      the errors message if status is False
3035

3036
  """
3037
  r_dev = _RecursiveFindBD(disk)
3038
  if r_dev is None:
3039
    _Fail("Cannot find block device %s", disk)
3040

    
3041
  try:
3042
    r_dev.Grow(amount, dryrun, backingstore, excl_stor)
3043
  except errors.BlockDeviceError, err:
3044
    _Fail("Failed to grow block device: %s", err, exc=True)
3045

    
3046

    
3047
def BlockdevSnapshot(disk, snapshot_name=None):
3048
  """Create a snapshot copy of a block device.
3049

3050
  This function is called recursively, and the snapshot is actually created
3051
  just for the leaf lvm backend device.
3052

3053
  @type disk: L{objects.Disk}
3054
  @param disk: the disk to be snapshotted
3055
  @rtype: string
3056
  @return: snapshot disk ID as (vg, lv)
3057

3058
  """
3059
  if disk.dev_type == constants.DT_DRBD8:
3060
    if not disk.children:
3061
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
3062
            disk.unique_id)
3063
    return BlockdevSnapshot(disk.children[0])
3064
  elif disk.dev_type == constants.DT_PLAIN and not snapshot_name:
3065
    r_dev = _RecursiveFindBD(disk)
3066
    if r_dev is not None:
3067
      # FIXME: choose a saner value for the snapshot size
3068
      # let's stay on the safe side and ask for the full size, for now
3069
      return r_dev.Snapshot(disk.size)
3070
    else:
3071
      _Fail("Cannot find block device %s", disk)
3072
  elif disk.dev_type == constants.DT_EXT:
3073
    r_dev = _RecursiveFindBD(disk)
3074
    if r_dev is not None:
3075
      r_dev.Snapshot(snapshot_name)
3076
    else:
3077
      _Fail("Cannot find block device %s", disk)
3078
  else:
3079
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
3080
          disk.unique_id, disk.dev_type)
3081

    
3082

    
3083
def BlockdevSetInfo(disk, info):
3084
  """Sets 'metadata' information on block devices.
3085

3086
  This function sets 'info' metadata on block devices. Initial
3087
  information is set at device creation; this function should be used
3088
  for example after renames.
3089

3090
  @type disk: L{objects.Disk}
3091
  @param disk: the disk to be grown
3092
  @type info: string
3093
  @param info: new 'info' metadata
3094
  @rtype: (status, result)
3095
  @return: a tuple with the status of the operation (True/False), and
3096
      the errors message if status is False
3097

3098
  """
3099
  r_dev = _RecursiveFindBD(disk)
3100
  if r_dev is None:
3101
    _Fail("Cannot find block device %s", disk)
3102

    
3103
  try:
3104
    r_dev.SetInfo(info)
3105
  except errors.BlockDeviceError, err:
3106
    _Fail("Failed to set information on block device: %s", err, exc=True)
3107

    
3108

    
3109
def FinalizeExport(instance, snap_disks):
3110
  """Write out the export configuration information.
3111

3112
  @type instance: L{objects.Instance}
3113
  @param instance: the instance which we export, used for
3114
      saving configuration
3115
  @type snap_disks: list of L{objects.Disk}
3116
  @param snap_disks: list of snapshot block devices, which
3117
      will be used to get the actual name of the dump file
3118

3119
  @rtype: None
3120

3121
  """
3122
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
3123
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
3124

    
3125
  config = objects.SerializableConfigParser()
3126

    
3127
  config.add_section(constants.INISECT_EXP)
3128
  config.set(constants.INISECT_EXP, "version", "0")
3129
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
3130
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
3131
  config.set(constants.INISECT_EXP, "os", instance.os)
3132
  config.set(constants.INISECT_EXP, "compression", "none")
3133

    
3134
  config.add_section(constants.INISECT_INS)
3135
  config.set(constants.INISECT_INS, "name", instance.name)
3136
  config.set(constants.INISECT_INS, "maxmem", "%d" %
3137
             instance.beparams[constants.BE_MAXMEM])
3138
  config.set(constants.INISECT_INS, "minmem", "%d" %
3139
             instance.beparams[constants.BE_MINMEM])
3140
  # "memory" is deprecated, but useful for exporting to old ganeti versions
3141
  config.set(constants.INISECT_INS, "memory", "%d" %
3142
             instance.beparams[constants.BE_MAXMEM])
3143
  config.set(constants.INISECT_INS, "vcpus", "%d" %
3144
             instance.beparams[constants.BE_VCPUS])
3145
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
3146
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
3147
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
3148

    
3149
  nic_total = 0
3150
  for nic_count, nic in enumerate(instance.nics):
3151
    nic_total += 1
3152
    config.set(constants.INISECT_INS, "nic%d_mac" %
3153
               nic_count, "%s" % nic.mac)
3154
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
3155
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
3156
               "%s" % nic.network)
3157
    config.set(constants.INISECT_INS, "nic%d_name" % nic_count,
3158
               "%s" % nic.name)
3159
    for param in constants.NICS_PARAMETER_TYPES:
3160
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
3161
                 "%s" % nic.nicparams.get(param, None))
3162
  # TODO: redundant: on load can read nics until it doesn't exist
3163
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
3164

    
3165
  disk_total = 0
3166
  for disk_count, disk in enumerate(snap_disks):
3167
    if disk:
3168
      disk_total += 1
3169
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
3170
                 ("%s" % disk.iv_name))
3171
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
3172
                 ("%s" % disk.logical_id[1]))
3173
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
3174
                 ("%d" % disk.size))
3175
      config.set(constants.INISECT_INS, "disk%d_name" % disk_count,
3176
                 "%s" % disk.name)
3177

    
3178
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
3179

    
3180
  # New-style hypervisor/backend parameters
3181

    
3182
  config.add_section(constants.INISECT_HYP)
3183
  for name, value in instance.hvparams.items():
3184
    if name not in constants.HVC_GLOBALS:
3185
      config.set(constants.INISECT_HYP, name, str(value))
3186

    
3187
  config.add_section(constants.INISECT_BEP)
3188
  for name, value in instance.beparams.items():
3189
    config.set(constants.INISECT_BEP, name, str(value))
3190

    
3191
  config.add_section(constants.INISECT_OSP)
3192
  for name, value in instance.osparams.items():
3193
    config.set(constants.INISECT_OSP, name, str(value))
3194

    
3195
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
3196
                  data=config.Dumps())
3197
  shutil.rmtree(finaldestdir, ignore_errors=True)
3198
  shutil.move(destdir, finaldestdir)
3199

    
3200

    
3201
def ExportInfo(dest):
3202
  """Get export configuration information.
3203

3204
  @type dest: str
3205
  @param dest: directory containing the export
3206

3207
  @rtype: L{objects.SerializableConfigParser}
3208
  @return: a serializable config file containing the
3209
      export info
3210

3211
  """
3212
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
3213

    
3214
  config = objects.SerializableConfigParser()
3215
  config.read(cff)
3216

    
3217
  if (not config.has_section(constants.INISECT_EXP) or
3218
      not config.has_section(constants.INISECT_INS)):
3219
    _Fail("Export info file doesn't have the required fields")
3220

    
3221
  return config.Dumps()
3222

    
3223

    
3224
def ListExports():
3225
  """Return a list of exports currently available on this machine.
3226

3227
  @rtype: list
3228
  @return: list of the exports
3229

3230
  """
3231
  if os.path.isdir(pathutils.EXPORT_DIR):
3232
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
3233
  else:
3234
    _Fail("No exports directory")
3235

    
3236

    
3237
def RemoveExport(export):
3238
  """Remove an existing export from the node.
3239

3240
  @type export: str
3241
  @param export: the name of the export to remove
3242
  @rtype: None
3243

3244
  """
3245
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
3246

    
3247
  try:
3248
    shutil.rmtree(target)
3249
  except EnvironmentError, err:
3250
    _Fail("Error while removing the export: %s", err, exc=True)
3251

    
3252

    
3253
def BlockdevRename(devlist):
3254
  """Rename a list of block devices.
3255

3256
  @type devlist: list of tuples
3257
  @param devlist: list of tuples of the form  (disk, new_unique_id); disk is
3258
      an L{objects.Disk} object describing the current disk, and new
3259
      unique_id is the name we rename it to
3260
  @rtype: boolean
3261
  @return: True if all renames succeeded, False otherwise
3262

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

    
3291

    
3292
def _TransformFileStorageDir(fs_dir):
3293
  """Checks whether given file_storage_dir is valid.
3294

3295
  Checks wheter the given fs_dir is within the cluster-wide default
3296
  file_storage_dir or the shared_file_storage_dir, which are stored in
3297
  SimpleStore. Only paths under those directories are allowed.
3298

3299
  @type fs_dir: str
3300
  @param fs_dir: the path to check
3301

3302
  @return: the normalized path if valid, None otherwise
3303

3304
  """
3305
  filestorage.CheckFileStoragePath(fs_dir)
3306

    
3307
  return os.path.normpath(fs_dir)
3308

    
3309

    
3310
def CreateFileStorageDir(file_storage_dir):
3311
  """Create file storage directory.
3312

3313
  @type file_storage_dir: str
3314
  @param file_storage_dir: directory to create
3315

3316
  @rtype: tuple
3317
  @return: tuple with first element a boolean indicating wheter dir
3318
      creation was successful or not
3319

3320
  """
3321
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3322
  if os.path.exists(file_storage_dir):
3323
    if not os.path.isdir(file_storage_dir):
3324
      _Fail("Specified storage dir '%s' is not a directory",
3325
            file_storage_dir)
3326
  else:
3327
    try:
3328
      os.makedirs(file_storage_dir, 0750)
3329
    except OSError, err:
3330
      _Fail("Cannot create file storage directory '%s': %s",
3331
            file_storage_dir, err, exc=True)
3332

    
3333

    
3334
def RemoveFileStorageDir(file_storage_dir):
3335
  """Remove file storage directory.
3336

3337
  Remove it only if it's empty. If not log an error and return.
3338

3339
  @type file_storage_dir: str
3340
  @param file_storage_dir: the directory we should cleanup
3341
  @rtype: tuple (success,)
3342
  @return: tuple of one element, C{success}, denoting
3343
      whether the operation was successful
3344

3345
  """
3346
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3347
  if os.path.exists(file_storage_dir):
3348
    if not os.path.isdir(file_storage_dir):
3349
      _Fail("Specified Storage directory '%s' is not a directory",
3350
            file_storage_dir)
3351
    # deletes dir only if empty, otherwise we want to fail the rpc call
3352
    try:
3353
      os.rmdir(file_storage_dir)
3354
    except OSError, err:
3355
      _Fail("Cannot remove file storage directory '%s': %s",
3356
            file_storage_dir, err)
3357

    
3358

    
3359
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
3360
  """Rename the file storage directory.
3361

3362
  @type old_file_storage_dir: str
3363
  @param old_file_storage_dir: the current path
3364
  @type new_file_storage_dir: str
3365
  @param new_file_storage_dir: the name we should rename to
3366
  @rtype: tuple (success,)
3367
  @return: tuple of one element, C{success}, denoting
3368
      whether the operation was successful
3369

3370
  """
3371
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
3372
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
3373
  if not os.path.exists(new_file_storage_dir):
3374
    if os.path.isdir(old_file_storage_dir):
3375
      try:
3376
        os.rename(old_file_storage_dir, new_file_storage_dir)
3377
      except OSError, err:
3378
        _Fail("Cannot rename '%s' to '%s': %s",
3379
              old_file_storage_dir, new_file_storage_dir, err)
3380
    else:
3381
      _Fail("Specified storage dir '%s' is not a directory",
3382
            old_file_storage_dir)
3383
  else:
3384
    if os.path.exists(old_file_storage_dir):
3385
      _Fail("Cannot rename '%s' to '%s': both locations exist",
3386
            old_file_storage_dir, new_file_storage_dir)
3387

    
3388

    
3389
def _EnsureJobQueueFile(file_name):
3390
  """Checks whether the given filename is in the queue directory.
3391

3392
  @type file_name: str
3393
  @param file_name: the file name we should check
3394
  @rtype: None
3395
  @raises RPCFail: if the file is not valid
3396

3397
  """
3398
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
3399
    _Fail("Passed job queue file '%s' does not belong to"
3400
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
3401

    
3402

    
3403
def JobQueueUpdate(file_name, content):
3404
  """Updates a file in the queue directory.
3405

3406
  This is just a wrapper over L{utils.io.WriteFile}, with proper
3407
  checking.
3408

3409
  @type file_name: str
3410
  @param file_name: the job file name
3411
  @type content: str
3412
  @param content: the new job contents
3413
  @rtype: boolean
3414
  @return: the success of the operation
3415

3416
  """
3417
  file_name = vcluster.LocalizeVirtualPath(file_name)
3418

    
3419
  _EnsureJobQueueFile(file_name)
3420
  getents = runtime.GetEnts()
3421

    
3422
  # Write and replace the file atomically
3423
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3424
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3425

    
3426

    
3427
def JobQueueRename(old, new):
3428
  """Renames a job queue file.
3429

3430
  This is just a wrapper over os.rename with proper checking.
3431

3432
  @type old: str
3433
  @param old: the old (actual) file name
3434
  @type new: str
3435
  @param new: the desired file name
3436
  @rtype: tuple
3437
  @return: the success of the operation and payload
3438

3439
  """
3440
  old = vcluster.LocalizeVirtualPath(old)
3441
  new = vcluster.LocalizeVirtualPath(new)
3442

    
3443
  _EnsureJobQueueFile(old)
3444
  _EnsureJobQueueFile(new)
3445

    
3446
  getents = runtime.GetEnts()
3447

    
3448
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3449
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3450

    
3451

    
3452
def BlockdevClose(instance_name, disks):
3453
  """Closes the given block devices.
3454

3455
  This means they will be switched to secondary mode (in case of
3456
  DRBD).
3457

3458
  @param instance_name: if the argument is not empty, the symlinks
3459
      of this instance will be removed
3460
  @type disks: list of L{objects.Disk}
3461
  @param disks: the list of disks to be closed
3462
  @rtype: tuple (success, message)
3463
  @return: a tuple of success and message, where success
3464
      indicates the succes of the operation, and message
3465
      which will contain the error details in case we
3466
      failed
3467

3468
  """
3469
  bdevs = []
3470
  for cf in disks:
3471
    rd = _RecursiveFindBD(cf)
3472
    if rd is None:
3473
      _Fail("Can't find device %s", cf)
3474
    bdevs.append(rd)
3475

    
3476
  msg = []
3477
  for rd in bdevs:
3478
    try:
3479
      rd.Close()
3480
    except errors.BlockDeviceError, err:
3481
      msg.append(str(err))
3482
  if msg:
3483
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3484
  else:
3485
    if instance_name:
3486
      _RemoveBlockDevLinks(instance_name, disks)
3487

    
3488

    
3489
def ValidateHVParams(hvname, hvparams):
3490
  """Validates the given hypervisor parameters.
3491

3492
  @type hvname: string
3493
  @param hvname: the hypervisor name
3494
  @type hvparams: dict
3495
  @param hvparams: the hypervisor parameters to be validated
3496
  @rtype: None
3497

3498
  """
3499
  try:
3500
    hv_type = hypervisor.GetHypervisor(hvname)
3501
    hv_type.ValidateParameters(hvparams)
3502
  except errors.HypervisorError, err:
3503
    _Fail(str(err), log=False)
3504

    
3505

    
3506
def _CheckOSPList(os_obj, parameters):
3507
  """Check whether a list of parameters is supported by the OS.
3508

3509
  @type os_obj: L{objects.OS}
3510
  @param os_obj: OS object to check
3511
  @type parameters: list
3512
  @param parameters: the list of parameters to check
3513

3514
  """
3515
  supported = [v[0] for v in os_obj.supported_parameters]
3516
  delta = frozenset(parameters).difference(supported)
3517
  if delta:
3518
    _Fail("The following parameters are not supported"
3519
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3520

    
3521

    
3522
def ValidateOS(required, osname, checks, osparams):
3523
  """Validate the given OS' parameters.
3524

3525
  @type required: boolean
3526
  @param required: whether absence of the OS should translate into
3527
      failure or not
3528
  @type osname: string
3529
  @param osname: the OS to be validated
3530
  @type checks: list
3531
  @param checks: list of the checks to run (currently only 'parameters')
3532
  @type osparams: dict
3533
  @param osparams: dictionary with OS parameters
3534
  @rtype: boolean
3535
  @return: True if the validation passed, or False if the OS was not
3536
      found and L{required} was false
3537

3538
  """
3539
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3540
    _Fail("Unknown checks required for OS %s: %s", osname,
3541
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3542

    
3543
  name_only = objects.OS.GetName(osname)
3544
  status, tbv = _TryOSFromDisk(name_only, None)
3545

    
3546
  if not status:
3547
    if required:
3548
      _Fail(tbv)
3549
    else:
3550
      return False
3551

    
3552
  if max(tbv.api_versions) < constants.OS_API_V20:
3553
    return True
3554

    
3555
  if constants.OS_VALIDATE_PARAMETERS in checks:
3556
    _CheckOSPList(tbv, osparams.keys())
3557

    
3558
  validate_env = OSCoreEnv(osname, tbv, osparams)
3559
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3560
                        cwd=tbv.path, reset_env=True)
3561
  if result.failed:
3562
    logging.error("os validate command '%s' returned error: %s output: %s",
3563
                  result.cmd, result.fail_reason, result.output)
3564
    _Fail("OS validation script failed (%s), output: %s",
3565
          result.fail_reason, result.output, log=False)
3566

    
3567
  return True
3568

    
3569

    
3570
def DemoteFromMC():
3571
  """Demotes the current node from master candidate role.
3572

3573
  """
3574
  # try to ensure we're not the master by mistake
3575
  master, myself = ssconf.GetMasterAndMyself()
3576
  if master == myself:
3577
    _Fail("ssconf status shows I'm the master node, will not demote")
3578

    
3579
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3580
  if not result.failed:
3581
    _Fail("The master daemon is running, will not demote")
3582

    
3583
  try:
3584
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3585
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3586
  except EnvironmentError, err:
3587
    if err.errno != errno.ENOENT:
3588
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3589

    
3590
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3591

    
3592

    
3593
def _GetX509Filenames(cryptodir, name):
3594
  """Returns the full paths for the private key and certificate.
3595

3596
  """
3597
  return (utils.PathJoin(cryptodir, name),
3598
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3599
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3600

    
3601

    
3602
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3603
  """Creates a new X509 certificate for SSL/TLS.
3604

3605
  @type validity: int
3606
  @param validity: Validity in seconds
3607
  @rtype: tuple; (string, string)
3608
  @return: Certificate name and public part
3609

3610
  """
3611
  (key_pem, cert_pem) = \
3612
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3613
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3614

    
3615
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3616
                              prefix="x509-%s-" % utils.TimestampForFilename())
3617
  try:
3618
    name = os.path.basename(cert_dir)
3619
    assert len(name) > 5
3620

    
3621
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3622

    
3623
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3624
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3625

    
3626
    # Never return private key as it shouldn't leave the node
3627
    return (name, cert_pem)
3628
  except Exception:
3629
    shutil.rmtree(cert_dir, ignore_errors=True)
3630
    raise
3631

    
3632

    
3633
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3634
  """Removes a X509 certificate.
3635

3636
  @type name: string
3637
  @param name: Certificate name
3638

3639
  """
3640
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3641

    
3642
  utils.RemoveFile(key_file)
3643
  utils.RemoveFile(cert_file)
3644

    
3645
  try:
3646
    os.rmdir(cert_dir)
3647
  except EnvironmentError, err:
3648
    _Fail("Cannot remove certificate directory '%s': %s",
3649
          cert_dir, err)
3650

    
3651

    
3652
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3653
  """Returns the command for the requested input/output.
3654

3655
  @type instance: L{objects.Instance}
3656
  @param instance: The instance object
3657
  @param mode: Import/export mode
3658
  @param ieio: Input/output type
3659
  @param ieargs: Input/output arguments
3660

3661
  """
3662
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3663

    
3664
  env = None
3665
  prefix = None
3666
  suffix = None
3667
  exp_size = None
3668

    
3669
  if ieio == constants.IEIO_FILE:
3670
    (filename, ) = ieargs
3671

    
3672
    if not utils.IsNormAbsPath(filename):
3673
      _Fail("Path '%s' is not normalized or absolute", filename)
3674

    
3675
    real_filename = os.path.realpath(filename)
3676
    directory = os.path.dirname(real_filename)
3677

    
3678
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3679
      _Fail("File '%s' is not under exports directory '%s': %s",
3680
            filename, pathutils.EXPORT_DIR, real_filename)
3681

    
3682
    # Create directory
3683
    utils.Makedirs(directory, mode=0750)
3684

    
3685
    quoted_filename = utils.ShellQuote(filename)
3686

    
3687
    if mode == constants.IEM_IMPORT:
3688
      suffix = "> %s" % quoted_filename
3689
    elif mode == constants.IEM_EXPORT:
3690
      suffix = "< %s" % quoted_filename
3691

    
3692
      # Retrieve file size
3693
      try:
3694
        st = os.stat(filename)
3695
      except EnvironmentError, err:
3696
        logging.error("Can't stat(2) %s: %s", filename, err)
3697
      else:
3698
        exp_size = utils.BytesToMebibyte(st.st_size)
3699

    
3700
  elif ieio == constants.IEIO_RAW_DISK:
3701
    (disk, ) = ieargs
3702

    
3703
    real_disk = _OpenRealBD(disk)
3704

    
3705
    if mode == constants.IEM_IMPORT:
3706
      # we set here a smaller block size as, due to transport buffering, more
3707
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3708
      # is not already there or we pass a wrong path; we use notrunc to no
3709
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3710
      # much memory; this means that at best, we flush every 64k, which will
3711
      # not be very fast
3712
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3713
                                    " bs=%s oflag=dsync"),
3714
                                    real_disk.dev_path,
3715
                                    str(64 * 1024))
3716

    
3717
    elif mode == constants.IEM_EXPORT:
3718
      # the block size on the read dd is 1MiB to match our units
3719
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3720
                                   real_disk.dev_path,
3721
                                   str(1024 * 1024), # 1 MB
3722
                                   str(disk.size))
3723
      exp_size = disk.size
3724

    
3725
  elif ieio == constants.IEIO_SCRIPT:
3726
    (disk, disk_index, ) = ieargs
3727

    
3728
    assert isinstance(disk_index, (int, long))
3729

    
3730
    inst_os = OSFromDisk(instance.os)
3731
    env = OSEnvironment(instance, inst_os)
3732

    
3733
    if mode == constants.IEM_IMPORT:
3734
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3735
      env["IMPORT_INDEX"] = str(disk_index)
3736
      script = inst_os.import_script
3737

    
3738
    elif mode == constants.IEM_EXPORT:
3739
      real_disk = _OpenRealBD(disk)
3740
      env["EXPORT_DEVICE"] = real_disk.dev_path
3741
      env["EXPORT_INDEX"] = str(disk_index)
3742
      script = inst_os.export_script
3743

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

    
3747
    if mode == constants.IEM_IMPORT:
3748
      suffix = "| %s" % script_cmd
3749

    
3750
    elif mode == constants.IEM_EXPORT:
3751
      prefix = "%s |" % script_cmd
3752

    
3753
    # Let script predict size
3754
    exp_size = constants.IE_CUSTOM_SIZE
3755

    
3756
  else:
3757
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3758

    
3759
  return (env, prefix, suffix, exp_size)
3760

    
3761

    
3762
def _CreateImportExportStatusDir(prefix):
3763
  """Creates status directory for import/export.
3764

3765
  """
3766
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3767
                          prefix=("%s-%s-" %
3768
                                  (prefix, utils.TimestampForFilename())))
3769

    
3770

    
3771
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3772
                            ieio, ieioargs):
3773
  """Starts an import or export daemon.
3774

3775
  @param mode: Import/output mode
3776
  @type opts: L{objects.ImportExportOptions}
3777
  @param opts: Daemon options
3778
  @type host: string
3779
  @param host: Remote host for export (None for import)
3780
  @type port: int
3781
  @param port: Remote port for export (None for import)
3782
  @type instance: L{objects.Instance}
3783
  @param instance: Instance object
3784
  @type component: string
3785
  @param component: which part of the instance is transferred now,
3786
      e.g. 'disk/0'
3787
  @param ieio: Input/output type
3788
  @param ieioargs: Input/output arguments
3789

3790
  """
3791
  if mode == constants.IEM_IMPORT:
3792
    prefix = "import"
3793

    
3794
    if not (host is None and port is None):
3795
      _Fail("Can not specify host or port on import")
3796

    
3797
  elif mode == constants.IEM_EXPORT:
3798
    prefix = "export"
3799

    
3800
    if host is None or port is None:
3801
      _Fail("Host and port must be specified for an export")
3802

    
3803
  else:
3804
    _Fail("Invalid mode %r", mode)
3805

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

    
3809
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3810
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3811

    
3812
  if opts.key_name is None:
3813
    # Use server.pem
3814
    key_path = pathutils.NODED_CERT_FILE
3815
    cert_path = pathutils.NODED_CERT_FILE
3816
    assert opts.ca_pem is None
3817
  else:
3818
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3819
                                                 opts.key_name)
3820
    assert opts.ca_pem is not None
3821

    
3822
  for i in [key_path, cert_path]:
3823
    if not os.path.exists(i):
3824
      _Fail("File '%s' does not exist" % i)
3825

    
3826
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3827
  try:
3828
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3829
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3830
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3831

    
3832
    if opts.ca_pem is None:
3833
      # Use server.pem
3834
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3835
    else:
3836
      ca = opts.ca_pem
3837

    
3838
    # Write CA file
3839
    utils.WriteFile(ca_file, data=ca, mode=0400)
3840

    
3841
    cmd = [
3842
      pathutils.IMPORT_EXPORT_DAEMON,
3843
      status_file, mode,
3844
      "--key=%s" % key_path,
3845
      "--cert=%s" % cert_path,
3846
      "--ca=%s" % ca_file,
3847
      ]
3848

    
3849
    if host:
3850
      cmd.append("--host=%s" % host)
3851

    
3852
    if port:
3853
      cmd.append("--port=%s" % port)
3854

    
3855
    if opts.ipv6:
3856
      cmd.append("--ipv6")
3857
    else:
3858
      cmd.append("--ipv4")
3859

    
3860
    if opts.compress:
3861
      cmd.append("--compress=%s" % opts.compress)
3862

    
3863
    if opts.magic:
3864
      cmd.append("--magic=%s" % opts.magic)
3865

    
3866
    if exp_size is not None:
3867
      cmd.append("--expected-size=%s" % exp_size)
3868

    
3869
    if cmd_prefix:
3870
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3871

    
3872
    if cmd_suffix:
3873
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3874

    
3875
    if mode == constants.IEM_EXPORT:
3876
      # Retry connection a few times when connecting to remote peer
3877
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3878
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3879
    elif opts.connect_timeout is not None:
3880
      assert mode == constants.IEM_IMPORT
3881
      # Overall timeout for establishing connection while listening
3882
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3883

    
3884
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3885

    
3886
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3887
    # support for receiving a file descriptor for output
3888
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3889
                      output=logfile)
3890

    
3891
    # The import/export name is simply the status directory name
3892
    return os.path.basename(status_dir)
3893

    
3894
  except Exception:
3895
    shutil.rmtree(status_dir, ignore_errors=True)
3896
    raise
3897

    
3898

    
3899
def GetImportExportStatus(names):
3900
  """Returns import/export daemon status.
3901

3902
  @type names: sequence
3903
  @param names: List of names
3904
  @rtype: List of dicts
3905
  @return: Returns a list of the state of each named import/export or None if a
3906
           status couldn't be read
3907

3908
  """
3909
  result = []
3910

    
3911
  for name in names:
3912
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3913
                                 _IES_STATUS_FILE)
3914

    
3915
    try:
3916
      data = utils.ReadFile(status_file)
3917
    except EnvironmentError, err:
3918
      if err.errno != errno.ENOENT:
3919
        raise
3920
      data = None
3921

    
3922
    if not data:
3923
      result.append(None)
3924
      continue
3925

    
3926
    result.append(serializer.LoadJson(data))
3927

    
3928
  return result
3929

    
3930

    
3931
def AbortImportExport(name):
3932
  """Sends SIGTERM to a running import/export daemon.
3933

3934
  """
3935
  logging.info("Abort import/export %s", name)
3936

    
3937
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3938
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3939

    
3940
  if pid:
3941
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3942
                 name, pid)
3943
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3944

    
3945

    
3946
def CleanupImportExport(name):
3947
  """Cleanup after an import or export.
3948

3949
  If the import/export daemon is still running it's killed. Afterwards the
3950
  whole status directory is removed.
3951

3952
  """
3953
  logging.info("Finalizing import/export %s", name)
3954

    
3955
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3956

    
3957
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3958

    
3959
  if pid:
3960
    logging.info("Import/export %s is still running with PID %s",
3961
                 name, pid)
3962
    utils.KillProcess(pid, waitpid=False)
3963

    
3964
  shutil.rmtree(status_dir, ignore_errors=True)
3965

    
3966

    
3967
def _FindDisks(disks):
3968
  """Finds attached L{BlockDev}s for the given disks.
3969

3970
  @type disks: list of L{objects.Disk}
3971
  @param disks: the disk objects we need to find
3972

3973
  @return: list of L{BlockDev} objects or C{None} if a given disk
3974
           was not found or was no attached.
3975

3976
  """
3977
  bdevs = []
3978

    
3979
  for disk in disks:
3980
    rd = _RecursiveFindBD(disk)
3981
    if rd is None:
3982
      _Fail("Can't find device %s", disk)
3983
    bdevs.append(rd)
3984
  return bdevs
3985

    
3986

    
3987
def DrbdDisconnectNet(disks):
3988
  """Disconnects the network on a list of drbd devices.
3989

3990
  """
3991
  bdevs = _FindDisks(disks)
3992

    
3993
  # disconnect disks
3994
  for rd in bdevs:
3995
    try:
3996
      rd.DisconnectNet()
3997
    except errors.BlockDeviceError, err:
3998
      _Fail("Can't change network configuration to standalone mode: %s",
3999
            err, exc=True)
4000

    
4001

    
4002
def DrbdAttachNet(disks, instance_name, multimaster):
4003
  """Attaches the network on a list of drbd devices.
4004

4005
  """
4006
  bdevs = _FindDisks(disks)
4007

    
4008
  if multimaster:
4009
    for idx, rd in enumerate(bdevs):
4010
      try:
4011
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
4012
      except EnvironmentError, err:
4013
        _Fail("Can't create symlink: %s", err)
4014
  # reconnect disks, switch to new master configuration and if
4015
  # needed primary mode
4016
  for rd in bdevs:
4017
    try:
4018
      rd.AttachNet(multimaster)
4019
    except errors.BlockDeviceError, err:
4020
      _Fail("Can't change network configuration: %s", err)
4021

    
4022
  # wait until the disks are connected; we need to retry the re-attach
4023
  # if the device becomes standalone, as this might happen if the one
4024
  # node disconnects and reconnects in a different mode before the
4025
  # other node reconnects; in this case, one or both of the nodes will
4026
  # decide it has wrong configuration and switch to standalone
4027

    
4028
  def _Attach():
4029
    all_connected = True
4030

    
4031
    for rd in bdevs:
4032
      stats = rd.GetProcStatus()
4033

    
4034
      if multimaster:
4035
        # In the multimaster case we have to wait explicitly until
4036
        # the resource is Connected and UpToDate/UpToDate, because
4037
        # we promote *both nodes* to primary directly afterwards.
4038
        # Being in resync is not enough, since there is a race during which we
4039
        # may promote a node with an Outdated disk to primary, effectively
4040
        # tearing down the connection.
4041
        all_connected = (all_connected and
4042
                         stats.is_connected and
4043
                         stats.is_disk_uptodate and
4044
                         stats.peer_disk_uptodate)
4045
      else:
4046
        all_connected = (all_connected and
4047
                         (stats.is_connected or stats.is_in_resync))
4048

    
4049
      if stats.is_standalone:
4050
        # peer had different config info and this node became
4051
        # standalone, even though this should not happen with the
4052
        # new staged way of changing disk configs
4053
        try:
4054
          rd.AttachNet(multimaster)
4055
        except errors.BlockDeviceError, err:
4056
          _Fail("Can't change network configuration: %s", err)
4057

    
4058
    if not all_connected:
4059
      raise utils.RetryAgain()
4060

    
4061
  try:
4062
    # Start with a delay of 100 miliseconds and go up to 5 seconds
4063
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
4064
  except utils.RetryTimeout:
4065
    _Fail("Timeout in disk reconnecting")
4066

    
4067
  if multimaster:
4068
    # change to primary mode
4069
    for rd in bdevs:
4070
      try:
4071
        rd.Open()
4072
      except errors.BlockDeviceError, err:
4073
        _Fail("Can't change to primary mode: %s", err)
4074

    
4075

    
4076
def DrbdWaitSync(disks):
4077
  """Wait until DRBDs have synchronized.
4078

4079
  """
4080
  def _helper(rd):
4081
    stats = rd.GetProcStatus()
4082
    if not (stats.is_connected or stats.is_in_resync):
4083
      raise utils.RetryAgain()
4084
    return stats
4085

    
4086
  bdevs = _FindDisks(disks)
4087

    
4088
  min_resync = 100
4089
  alldone = True
4090
  for rd in bdevs:
4091
    try:
4092
      # poll each second for 15 seconds
4093
      stats = utils.Retry(_helper, 1, 15, args=[rd])
4094
    except utils.RetryTimeout:
4095
      stats = rd.GetProcStatus()
4096
      # last check
4097
      if not (stats.is_connected or stats.is_in_resync):
4098
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
4099
    alldone = alldone and (not stats.is_in_resync)
4100
    if stats.sync_percent is not None:
4101
      min_resync = min(min_resync, stats.sync_percent)
4102

    
4103
  return (alldone, min_resync)
4104

    
4105

    
4106
def DrbdNeedsActivation(disks):
4107
  """Checks which of the passed disks needs activation and returns their UUIDs.
4108

4109
  """
4110
  faulty_disks = []
4111

    
4112
  for disk in disks:
4113
    rd = _RecursiveFindBD(disk)
4114
    if rd is None:
4115
      faulty_disks.append(disk)
4116
      continue
4117

    
4118
    stats = rd.GetProcStatus()
4119
    if stats.is_standalone or stats.is_diskless:
4120
      faulty_disks.append(disk)
4121

    
4122
  return [disk.uuid for disk in faulty_disks]
4123

    
4124

    
4125
def GetDrbdUsermodeHelper():
4126
  """Returns DRBD usermode helper currently configured.
4127

4128
  """
4129
  try:
4130
    return drbd.DRBD8.GetUsermodeHelper()
4131
  except errors.BlockDeviceError, err:
4132
    _Fail(str(err))
4133

    
4134

    
4135
def PowercycleNode(hypervisor_type, hvparams=None):
4136
  """Hard-powercycle the node.
4137

4138
  Because we need to return first, and schedule the powercycle in the
4139
  background, we won't be able to report failures nicely.
4140

4141
  """
4142
  hyper = hypervisor.GetHypervisor(hypervisor_type)
4143
  try:
4144
    pid = os.fork()
4145
  except OSError:
4146
    # if we can't fork, we'll pretend that we're in the child process
4147
    pid = 0
4148
  if pid > 0:
4149
    return "Reboot scheduled in 5 seconds"
4150
  # ensure the child is running on ram
4151
  try:
4152
    utils.Mlockall()
4153
  except Exception: # pylint: disable=W0703
4154
    pass
4155
  time.sleep(5)
4156
  hyper.PowercycleNode(hvparams=hvparams)
4157

    
4158

    
4159
def _VerifyRestrictedCmdName(cmd):
4160
  """Verifies a restricted command name.
4161

4162
  @type cmd: string
4163
  @param cmd: Command name
4164
  @rtype: tuple; (boolean, string or None)
4165
  @return: The tuple's first element is the status; if C{False}, the second
4166
    element is an error message string, otherwise it's C{None}
4167

4168
  """
4169
  if not cmd.strip():
4170
    return (False, "Missing command name")
4171

    
4172
  if os.path.basename(cmd) != cmd:
4173
    return (False, "Invalid command name")
4174

    
4175
  if not constants.EXT_PLUGIN_MASK.match(cmd):
4176
    return (False, "Command name contains forbidden characters")
4177

    
4178
  return (True, None)
4179

    
4180

    
4181
def _CommonRestrictedCmdCheck(path, owner):
4182
  """Common checks for restricted command file system directories and files.
4183

4184
  @type path: string
4185
  @param path: Path to check
4186
  @param owner: C{None} or tuple containing UID and GID
4187
  @rtype: tuple; (boolean, string or C{os.stat} result)
4188
  @return: The tuple's first element is the status; if C{False}, the second
4189
    element is an error message string, otherwise it's the result of C{os.stat}
4190

4191
  """
4192
  if owner is None:
4193
    # Default to root as owner
4194
    owner = (0, 0)
4195

    
4196
  try:
4197
    st = os.stat(path)
4198
  except EnvironmentError, err:
4199
    return (False, "Can't stat(2) '%s': %s" % (path, err))
4200

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

    
4204
  if (st.st_uid, st.st_gid) != owner:
4205
    (owner_uid, owner_gid) = owner
4206
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
4207

    
4208
  return (True, st)
4209

    
4210

    
4211
def _VerifyRestrictedCmdDirectory(path, _owner=None):
4212
  """Verifies restricted command directory.
4213

4214
  @type path: string
4215
  @param path: Path to check
4216
  @rtype: tuple; (boolean, string or None)
4217
  @return: The tuple's first element is the status; if C{False}, the second
4218
    element is an error message string, otherwise it's C{None}
4219

4220
  """
4221
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
4222

    
4223
  if not status:
4224
    return (False, value)
4225

    
4226
  if not stat.S_ISDIR(value.st_mode):
4227
    return (False, "Path '%s' is not a directory" % path)
4228

    
4229
  return (True, None)
4230

    
4231

    
4232
def _VerifyRestrictedCmd(path, cmd, _owner=None):
4233
  """Verifies a whole restricted command and returns its executable filename.
4234

4235
  @type path: string
4236
  @param path: Directory containing restricted commands
4237
  @type cmd: string
4238
  @param cmd: Command name
4239
  @rtype: tuple; (boolean, string)
4240
  @return: The tuple's first element is the status; if C{False}, the second
4241
    element is an error message string, otherwise the second element is the
4242
    absolute path to the executable
4243

4244
  """
4245
  executable = utils.PathJoin(path, cmd)
4246

    
4247
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
4248

    
4249
  if not status:
4250
    return (False, msg)
4251

    
4252
  if not utils.IsExecutable(executable):
4253
    return (False, "access(2) thinks '%s' can't be executed" % executable)
4254

    
4255
  return (True, executable)
4256

    
4257

    
4258
def _PrepareRestrictedCmd(path, cmd,
4259
                          _verify_dir=_VerifyRestrictedCmdDirectory,
4260
                          _verify_name=_VerifyRestrictedCmdName,
4261
                          _verify_cmd=_VerifyRestrictedCmd):
4262
  """Performs a number of tests on a restricted command.
4263

4264
  @type path: string
4265
  @param path: Directory containing restricted commands
4266
  @type cmd: string
4267
  @param cmd: Command name
4268
  @return: Same as L{_VerifyRestrictedCmd}
4269

4270
  """
4271
  # Verify the directory first
4272
  (status, msg) = _verify_dir(path)
4273
  if status:
4274
    # Check command if everything was alright
4275
    (status, msg) = _verify_name(cmd)
4276

    
4277
  if not status:
4278
    return (False, msg)
4279

    
4280
  # Check actual executable
4281
  return _verify_cmd(path, cmd)
4282

    
4283

    
4284
def RunRestrictedCmd(cmd,
4285
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
4286
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
4287
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
4288
                     _sleep_fn=time.sleep,
4289
                     _prepare_fn=_PrepareRestrictedCmd,
4290
                     _runcmd_fn=utils.RunCmd,
4291
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
4292
  """Executes a restricted command after performing strict tests.
4293

4294
  @type cmd: string
4295
  @param cmd: Command name
4296
  @rtype: string
4297
  @return: Command output
4298
  @raise RPCFail: In case of an error
4299

4300
  """
4301
  logging.info("Preparing to run restricted command '%s'", cmd)
4302

    
4303
  if not _enabled:
4304
    _Fail("Restricted commands disabled at configure time")
4305

    
4306
  lock = None
4307
  try:
4308
    cmdresult = None
4309
    try:
4310
      lock = utils.FileLock.Open(_lock_file)
4311
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
4312

    
4313
      (status, value) = _prepare_fn(_path, cmd)
4314

    
4315
      if status:
4316
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
4317
                               postfork_fn=lambda _: lock.Unlock())
4318
      else:
4319
        logging.error(value)
4320
    except Exception: # pylint: disable=W0703
4321
      # Keep original error in log
4322
      logging.exception("Caught exception")
4323

    
4324
    if cmdresult is None:
4325
      logging.info("Sleeping for %0.1f seconds before returning",
4326
                   _RCMD_INVALID_DELAY)
4327
      _sleep_fn(_RCMD_INVALID_DELAY)
4328

    
4329
      # Do not include original error message in returned error
4330
      _Fail("Executing command '%s' failed" % cmd)
4331
    elif cmdresult.failed or cmdresult.fail_reason:
4332
      _Fail("Restricted command '%s' failed: %s; output: %s",
4333
            cmd, cmdresult.fail_reason, cmdresult.output)
4334
    else:
4335
      return cmdresult.output
4336
  finally:
4337
    if lock is not None:
4338
      # Release lock at last
4339
      lock.Close()
4340
      lock = None
4341

    
4342

    
4343
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
4344
  """Creates or removes the watcher pause file.
4345

4346
  @type until: None or number
4347
  @param until: Unix timestamp saying until when the watcher shouldn't run
4348

4349
  """
4350
  if until is None:
4351
    logging.info("Received request to no longer pause watcher")
4352
    utils.RemoveFile(_filename)
4353
  else:
4354
    logging.info("Received request to pause watcher until %s", until)
4355

    
4356
    if not ht.TNumber(until):
4357
      _Fail("Duration must be numeric")
4358

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

    
4361

    
4362
def ConfigureOVS(ovs_name, ovs_link):
4363
  """Creates a OpenvSwitch on the node.
4364

4365
  This function sets up a OpenvSwitch on the node with given name nad
4366
  connects it via a given eth device.
4367

4368
  @type ovs_name: string
4369
  @param ovs_name: Name of the OpenvSwitch to create.
4370
  @type ovs_link: None or string
4371
  @param ovs_link: Ethernet device for outside connection (can be missing)
4372

4373
  """
4374
  # Initialize the OpenvSwitch
4375
  result = utils.RunCmd(["ovs-vsctl", "add-br", ovs_name])
4376
  if result.failed:
4377
    _Fail("Failed to create openvswitch. Script return value: %s, output: '%s'"
4378
          % (result.exit_code, result.output), log=True)
4379

    
4380
  # And connect it to a physical interface, if given
4381
  if ovs_link:
4382
    result = utils.RunCmd(["ovs-vsctl", "add-port", ovs_name, ovs_link])
4383
    if result.failed:
4384
      _Fail("Failed to connect openvswitch to  interface %s. Script return"
4385
            " value: %s, output: '%s'" % (ovs_link, result.exit_code,
4386
            result.output), log=True)
4387

    
4388

    
4389
class HooksRunner(object):
4390
  """Hook runner.
4391

4392
  This class is instantiated on the node side (ganeti-noded) and not
4393
  on the master side.
4394

4395
  """
4396
  def __init__(self, hooks_base_dir=None):
4397
    """Constructor for hooks runner.
4398

4399
    @type hooks_base_dir: str or None
4400
    @param hooks_base_dir: if not None, this overrides the
4401
        L{pathutils.HOOKS_BASE_DIR} (useful for unittests)
4402

4403
    """
4404
    if hooks_base_dir is None:
4405
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
4406
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
4407
    # constant
4408
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
4409

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

4413
    """
4414
    assert len(node_list) == 1
4415
    node = node_list[0]
4416
    _, myself = ssconf.GetMasterAndMyself()
4417
    assert node == myself
4418

    
4419
    results = self.RunHooks(hpath, phase, env)
4420

    
4421
    # Return values in the form expected by HooksMaster
4422
    return {node: (None, False, results)}
4423

    
4424
  def RunHooks(self, hpath, phase, env):
4425
    """Run the scripts in the hooks directory.
4426

4427
    @type hpath: str
4428
    @param hpath: the path to the hooks directory which
4429
        holds the scripts
4430
    @type phase: str
4431
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
4432
        L{constants.HOOKS_PHASE_POST}
4433
    @type env: dict
4434
    @param env: dictionary with the environment for the hook
4435
    @rtype: list
4436
    @return: list of 3-element tuples:
4437
      - script path
4438
      - script result, either L{constants.HKR_SUCCESS} or
4439
        L{constants.HKR_FAIL}
4440
      - output of the script
4441

4442
    @raise errors.ProgrammerError: for invalid input
4443
        parameters
4444

4445
    """
4446
    if phase == constants.HOOKS_PHASE_PRE:
4447
      suffix = "pre"
4448
    elif phase == constants.HOOKS_PHASE_POST:
4449
      suffix = "post"
4450
    else:
4451
      _Fail("Unknown hooks phase '%s'", phase)
4452

    
4453
    subdir = "%s-%s.d" % (hpath, suffix)
4454
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
4455

    
4456
    results = []
4457

    
4458
    if not os.path.isdir(dir_name):
4459
      # for non-existing/non-dirs, we simply exit instead of logging a
4460
      # warning at every operation
4461
      return results
4462

    
4463
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
4464

    
4465
    for (relname, relstatus, runresult) in runparts_results:
4466
      if relstatus == constants.RUNPARTS_SKIP:
4467
        rrval = constants.HKR_SKIP
4468
        output = ""
4469
      elif relstatus == constants.RUNPARTS_ERR:
4470
        rrval = constants.HKR_FAIL
4471
        output = "Hook script execution error: %s" % runresult
4472
      elif relstatus == constants.RUNPARTS_RUN:
4473
        if runresult.failed:
4474
          rrval = constants.HKR_FAIL
4475
        else:
4476
          rrval = constants.HKR_SUCCESS
4477
        output = utils.SafeEncode(runresult.output.strip())
4478
      results.append(("%s/%s" % (subdir, relname), rrval, output))
4479

    
4480
    return results
4481

    
4482

    
4483
class IAllocatorRunner(object):
4484
  """IAllocator runner.
4485

4486
  This class is instantiated on the node side (ganeti-noded) and not on
4487
  the master side.
4488

4489
  """
4490
  @staticmethod
4491
  def Run(name, idata):
4492
    """Run an iallocator script.
4493

4494
    @type name: str
4495
    @param name: the iallocator script name
4496
    @type idata: str
4497
    @param idata: the allocator input data
4498

4499
    @rtype: tuple
4500
    @return: two element tuple of:
4501
       - status
4502
       - either error message or stdout of allocator (for success)
4503

4504
    """
4505
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
4506
                                  os.path.isfile)
4507
    if alloc_script is None:
4508
      _Fail("iallocator module '%s' not found in the search path", name)
4509

    
4510
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
4511
    try:
4512
      os.write(fd, idata)
4513
      os.close(fd)
4514
      result = utils.RunCmd([alloc_script, fin_name])
4515
      if result.failed:
4516
        _Fail("iallocator module '%s' failed: %s, output '%s'",
4517
              name, result.fail_reason, result.output)
4518
    finally:
4519
      os.unlink(fin_name)
4520

    
4521
    return result.stdout
4522

    
4523

    
4524
class DevCacheManager(object):
4525
  """Simple class for managing a cache of block device information.
4526

4527
  """
4528
  _DEV_PREFIX = "/dev/"
4529
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4530

    
4531
  @classmethod
4532
  def _ConvertPath(cls, dev_path):
4533
    """Converts a /dev/name path to the cache file name.
4534

4535
    This replaces slashes with underscores and strips the /dev
4536
    prefix. It then returns the full path to the cache file.
4537

4538
    @type dev_path: str
4539
    @param dev_path: the C{/dev/} path name
4540
    @rtype: str
4541
    @return: the converted path name
4542

4543
    """
4544
    if dev_path.startswith(cls._DEV_PREFIX):
4545
      dev_path = dev_path[len(cls._DEV_PREFIX):]
4546
    dev_path = dev_path.replace("/", "_")
4547
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4548
    return fpath
4549

    
4550
  @classmethod
4551
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4552
    """Updates the cache information for a given device.
4553

4554
    @type dev_path: str
4555
    @param dev_path: the pathname of the device
4556
    @type owner: str
4557
    @param owner: the owner (instance name) of the device
4558
    @type on_primary: bool
4559
    @param on_primary: whether this is the primary
4560
        node nor not
4561
    @type iv_name: str
4562
    @param iv_name: the instance-visible name of the
4563
        device, as in objects.Disk.iv_name
4564

4565
    @rtype: None
4566

4567
    """
4568
    if dev_path is None:
4569
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
4570
      return
4571
    fpath = cls._ConvertPath(dev_path)
4572
    if on_primary:
4573
      state = "primary"
4574
    else:
4575
      state = "secondary"
4576
    if iv_name is None:
4577
      iv_name = "not_visible"
4578
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4579
    try:
4580
      utils.WriteFile(fpath, data=fdata)
4581
    except EnvironmentError, err:
4582
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4583

    
4584
  @classmethod
4585
  def RemoveCache(cls, dev_path):
4586
    """Remove data for a dev_path.
4587

4588
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
4589
    path name and logging.
4590

4591
    @type dev_path: str
4592
    @param dev_path: the pathname of the device
4593

4594
    @rtype: None
4595

4596
    """
4597
    if dev_path is None:
4598
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
4599
      return
4600
    fpath = cls._ConvertPath(dev_path)
4601
    try:
4602
      utils.RemoveFile(fpath)
4603
    except EnvironmentError, err:
4604
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)