Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ bc57fa8d

History | View | Annotate | Download (142 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 filestorage
62
from ganeti import objects
63
from ganeti import ssconf
64
from ganeti import serializer
65
from ganeti import netutils
66
from ganeti import runtime
67
from ganeti import compat
68
from ganeti import pathutils
69
from ganeti import vcluster
70
from ganeti import ht
71
from ganeti.storage.base import BlockDev
72
from ganeti.storage.drbd import DRBD8
73
from ganeti import hooksmaster
74

    
75

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

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

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

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

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

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

    
110

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

114
  Its argument is the error message.
115

116
  """
117

    
118

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

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

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

    
130

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

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

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

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

    
146

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

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

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

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

    
169

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

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

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

    
179

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

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

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

    
192

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

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

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

    
212

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

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

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

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

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

    
242

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

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

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

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

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

    
269
  return frozenset(allowed_files)
270

    
271

    
272
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
273

    
274

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

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

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

    
285

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

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

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

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

    
310

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

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

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

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

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

    
342
      return result
343
    return wrapper
344
  return decorator
345

    
346

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

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

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

    
367
  return env
368

    
369

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

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

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

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

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

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

    
398

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

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

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

    
415

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

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

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

426
  """
427

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

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

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

    
443

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

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

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

    
460

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

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

466
  @rtype: None
467

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

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

    
478

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

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

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

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

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

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

    
509

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

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

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

    
531

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

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

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

542
  @param modify_ssh_setup: boolean
543

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

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

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

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

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

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

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

    
577

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

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

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

    
598

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

602
  @see: C{_CheckStorageParams}
603

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

    
612

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

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

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

    
626

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

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

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

    
648

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

652
  @see: C{_GetLvmVgSpaceInfo}
653

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

    
658

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

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

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

    
684

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

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

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

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

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

    
703

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

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

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

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

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

    
721

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

725
  @rtype: None or dict
726

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

    
733

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

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

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

    
757

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

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

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

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

    
772

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

    
784

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

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

    
810

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

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

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

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

    
827

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

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

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

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

    
858

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

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

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

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

    
886

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

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

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

    
910

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

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

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

    
931

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

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

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

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

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

949
  @type what: C{dict}
950
  @param what: a dictionary of things to check:
951
      - filelist: list of files for which to compute checksums
952
      - nodelist: list of nodes we should check ssh communication with
953
      - node-net-test: list of nodes we should check node daemon port
954
        connectivity with
955
      - hypervisor: list with hypervisors to run the verify for
956
  @type cluster_name: string
957
  @param cluster_name: the cluster's name
958
  @type all_hvparams: dict of dict of strings
959
  @param all_hvparams: a dictionary mapping hypervisor names to hvparams
960
  @type node_groups: a dict of strings
961
  @param node_groups: node _names_ mapped to their group uuids (it's enough to
962
      have only those nodes that are in `what["nodelist"]`)
963
  @type groups_cfg: a dict of dict of strings
964
  @param groups_cfg: a dictionary mapping group uuids to their configuration
965
  @rtype: dict
966
  @return: a dictionary with the same keys as the input dict, and
967
      values representing the result of the checks
968

969
  """
970
  result = {}
971
  my_name = netutils.Hostname.GetSysName()
972
  port = netutils.GetDaemonPort(constants.NODED)
973
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
974

    
975
  _VerifyHypervisors(what, vm_capable, result, all_hvparams)
976
  _VerifyHvparams(what, vm_capable, result)
977

    
978
  if constants.NV_FILELIST in what:
979
    fingerprints = utils.FingerprintFiles(map(vcluster.LocalizeVirtualPath,
980
                                              what[constants.NV_FILELIST]))
981
    result[constants.NV_FILELIST] = \
982
      dict((vcluster.MakeVirtualPath(key), value)
983
           for (key, value) in fingerprints.items())
984

    
985
  if constants.NV_NODELIST in what:
986
    (nodes, bynode) = what[constants.NV_NODELIST]
987

    
988
    # Add nodes from other groups (different for each node)
989
    try:
990
      nodes.extend(bynode[my_name])
991
    except KeyError:
992
      pass
993

    
994
    # Use a random order
995
    random.shuffle(nodes)
996

    
997
    # Try to contact all nodes
998
    val = {}
999
    for node in nodes:
1000
      params = groups_cfg.get(node_groups.get(node))
1001
      ssh_port = params["ndparams"].get(constants.ND_SSH_PORT)
1002
      logging.debug("Ssh port %s (None = default) for node %s",
1003
                    str(ssh_port), node)
1004
      success, message = _GetSshRunner(cluster_name). \
1005
                            VerifyNodeHostname(node, ssh_port)
1006
      if not success:
1007
        val[node] = message
1008

    
1009
    result[constants.NV_NODELIST] = val
1010

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1161
  return result
1162

    
1163

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

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

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

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

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

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

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

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

    
1201

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

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

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

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

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

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

    
1245
  return lvs
1246

    
1247

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

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

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

    
1258

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

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

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

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

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

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

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

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

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

    
1304

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

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

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

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

    
1320

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

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

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

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

    
1349

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

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

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

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

    
1376

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

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

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

1394
  """
1395
  output = {}
1396

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

    
1405
  return output
1406

    
1407

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

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

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

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

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

    
1431

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

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

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

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

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

    
1474
  return output
1475

    
1476

    
1477
def GetInstanceConsoleInfo(instance_param_dict,
1478
                           get_hv_fn=hypervisor.GetHypervisor):
1479
  """Gather data about the console access of a set of instances of this node.
1480

1481
  This function assumes that the caller already knows which instances are on
1482
  this node, by calling a function such as L{GetAllInstancesInfo} or
1483
  L{GetInstanceList}.
1484

1485
  For every instance, a large amount of configuration data needs to be
1486
  provided to the hypervisor interface in order to receive the console
1487
  information. Whether this could or should be cut down can be discussed.
1488
  The information is provided in a dictionary indexed by instance name,
1489
  allowing any number of instance queries to be done.
1490

1491
  @type instance_param_dict: dict of string to tuple of dictionaries, where the
1492
    dictionaries represent: L{objects.Instance}, L{objects.Node},
1493
    L{objects.NodeGroup}, HvParams, BeParams
1494
  @param instance_param_dict: mapping of instance name to parameters necessary
1495
    for console information retrieval
1496

1497
  @rtype: dict
1498
  @return: dictionary of instance: data, with data having the following keys:
1499
      - instance: instance name
1500
      - kind: console kind
1501
      - message: used with kind == CONS_MESSAGE, indicates console to be
1502
                 unavailable, supplies error message
1503
      - host: host to connect to
1504
      - port: port to use
1505
      - user: user for login
1506
      - command: the command, broken into parts as an array
1507
      - display: unknown, potentially unused?
1508

1509
  """
1510

    
1511
  output = {}
1512
  for inst_name in instance_param_dict:
1513
    instance = instance_param_dict[inst_name]["instance"]
1514
    pnode = instance_param_dict[inst_name]["node"]
1515
    group = instance_param_dict[inst_name]["group"]
1516
    hvparams = instance_param_dict[inst_name]["hvParams"]
1517
    beparams = instance_param_dict[inst_name]["beParams"]
1518

    
1519
    instance = objects.Instance.FromDict(instance)
1520
    pnode = objects.Node.FromDict(pnode)
1521
    group = objects.NodeGroup.FromDict(group)
1522

    
1523
    h = get_hv_fn(instance.hypervisor)
1524
    output[inst_name] = h.GetInstanceConsole(instance, pnode, group,
1525
                                             hvparams, beparams).ToDict()
1526

    
1527
  return output
1528

    
1529

    
1530
def _InstanceLogName(kind, os_name, instance, component):
1531
  """Compute the OS log filename for a given instance and operation.
1532

1533
  The instance name and os name are passed in as strings since not all
1534
  operations have these as part of an instance object.
1535

1536
  @type kind: string
1537
  @param kind: the operation type (e.g. add, import, etc.)
1538
  @type os_name: string
1539
  @param os_name: the os name
1540
  @type instance: string
1541
  @param instance: the name of the instance being imported/added/etc.
1542
  @type component: string or None
1543
  @param component: the name of the component of the instance being
1544
      transferred
1545

1546
  """
1547
  # TODO: Use tempfile.mkstemp to create unique filename
1548
  if component:
1549
    assert "/" not in component
1550
    c_msg = "-%s" % component
1551
  else:
1552
    c_msg = ""
1553
  base = ("%s-%s-%s%s-%s.log" %
1554
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1555
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1556

    
1557

    
1558
def InstanceOsAdd(instance, reinstall, debug):
1559
  """Add an OS to an instance.
1560

1561
  @type instance: L{objects.Instance}
1562
  @param instance: Instance whose OS is to be installed
1563
  @type reinstall: boolean
1564
  @param reinstall: whether this is an instance reinstall
1565
  @type debug: integer
1566
  @param debug: debug level, passed to the OS scripts
1567
  @rtype: None
1568

1569
  """
1570
  inst_os = OSFromDisk(instance.os)
1571

    
1572
  create_env = OSEnvironment(instance, inst_os, debug)
1573
  if reinstall:
1574
    create_env["INSTANCE_REINSTALL"] = "1"
1575

    
1576
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1577

    
1578
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1579
                        cwd=inst_os.path, output=logfile, reset_env=True)
1580
  if result.failed:
1581
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1582
                  " output: %s", result.cmd, result.fail_reason, logfile,
1583
                  result.output)
1584
    lines = [utils.SafeEncode(val)
1585
             for val in utils.TailFile(logfile, lines=20)]
1586
    _Fail("OS create script failed (%s), last lines in the"
1587
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1588

    
1589

    
1590
def RunRenameInstance(instance, old_name, debug):
1591
  """Run the OS rename script for an instance.
1592

1593
  @type instance: L{objects.Instance}
1594
  @param instance: Instance whose OS is to be installed
1595
  @type old_name: string
1596
  @param old_name: previous instance name
1597
  @type debug: integer
1598
  @param debug: debug level, passed to the OS scripts
1599
  @rtype: boolean
1600
  @return: the success of the operation
1601

1602
  """
1603
  inst_os = OSFromDisk(instance.os)
1604

    
1605
  rename_env = OSEnvironment(instance, inst_os, debug)
1606
  rename_env["OLD_INSTANCE_NAME"] = old_name
1607

    
1608
  logfile = _InstanceLogName("rename", instance.os,
1609
                             "%s-%s" % (old_name, instance.name), None)
1610

    
1611
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1612
                        cwd=inst_os.path, output=logfile, reset_env=True)
1613

    
1614
  if result.failed:
1615
    logging.error("os create command '%s' returned error: %s output: %s",
1616
                  result.cmd, result.fail_reason, result.output)
1617
    lines = [utils.SafeEncode(val)
1618
             for val in utils.TailFile(logfile, lines=20)]
1619
    _Fail("OS rename script failed (%s), last lines in the"
1620
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1621

    
1622

    
1623
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1624
  """Returns symlink path for block device.
1625

1626
  """
1627
  if _dir is None:
1628
    _dir = pathutils.DISK_LINKS_DIR
1629

    
1630
  return utils.PathJoin(_dir,
1631
                        ("%s%s%s" %
1632
                         (instance_name, constants.DISK_SEPARATOR, idx)))
1633

    
1634

    
1635
def _SymlinkBlockDev(instance_name, device_path, idx):
1636
  """Set up symlinks to a instance's block device.
1637

1638
  This is an auxiliary function run when an instance is start (on the primary
1639
  node) or when an instance is migrated (on the target node).
1640

1641

1642
  @param instance_name: the name of the target instance
1643
  @param device_path: path of the physical block device, on the node
1644
  @param idx: the disk index
1645
  @return: absolute path to the disk's symlink
1646

1647
  """
1648
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1649
  try:
1650
    os.symlink(device_path, link_name)
1651
  except OSError, err:
1652
    if err.errno == errno.EEXIST:
1653
      if (not os.path.islink(link_name) or
1654
          os.readlink(link_name) != device_path):
1655
        os.remove(link_name)
1656
        os.symlink(device_path, link_name)
1657
    else:
1658
      raise
1659

    
1660
  return link_name
1661

    
1662

    
1663
def _RemoveBlockDevLinks(instance_name, disks):
1664
  """Remove the block device symlinks belonging to the given instance.
1665

1666
  """
1667
  for idx, _ in enumerate(disks):
1668
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1669
    if os.path.islink(link_name):
1670
      try:
1671
        os.remove(link_name)
1672
      except OSError:
1673
        logging.exception("Can't remove symlink '%s'", link_name)
1674

    
1675

    
1676
def _CalculateDeviceURI(instance, disk, device):
1677
  """Get the URI for the device.
1678

1679
  @type instance: L{objects.Instance}
1680
  @param instance: the instance which disk belongs to
1681
  @type disk: L{objects.Disk}
1682
  @param disk: the target disk object
1683
  @type device: L{bdev.BlockDev}
1684
  @param device: the corresponding BlockDevice
1685
  @rtype: string
1686
  @return: the device uri if any else None
1687

1688
  """
1689
  access_mode = disk.params.get(constants.LDP_ACCESS,
1690
                                constants.DISK_KERNELSPACE)
1691
  if access_mode == constants.DISK_USERSPACE:
1692
    # This can raise errors.BlockDeviceError
1693
    return device.GetUserspaceAccessUri(instance.hypervisor)
1694
  else:
1695
    return None
1696

    
1697

    
1698
def _GatherAndLinkBlockDevs(instance):
1699
  """Set up an instance's block device(s).
1700

1701
  This is run on the primary node at instance startup. The block
1702
  devices must be already assembled.
1703

1704
  @type instance: L{objects.Instance}
1705
  @param instance: the instance whose disks we should assemble
1706
  @rtype: list
1707
  @return: list of (disk_object, link_name, drive_uri)
1708

1709
  """
1710
  block_devices = []
1711
  for idx, disk in enumerate(instance.disks):
1712
    device = _RecursiveFindBD(disk)
1713
    if device is None:
1714
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1715
                                    str(disk))
1716
    device.Open()
1717
    try:
1718
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1719
    except OSError, e:
1720
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1721
                                    e.strerror)
1722
    uri = _CalculateDeviceURI(instance, disk, device)
1723

    
1724
    block_devices.append((disk, link_name, uri))
1725

    
1726
  return block_devices
1727

    
1728

    
1729
def StartInstance(instance, startup_paused, reason, store_reason=True):
1730
  """Start an instance.
1731

1732
  @type instance: L{objects.Instance}
1733
  @param instance: the instance object
1734
  @type startup_paused: bool
1735
  @param instance: pause instance at startup?
1736
  @type reason: list of reasons
1737
  @param reason: the reason trail for this startup
1738
  @type store_reason: boolean
1739
  @param store_reason: whether to store the shutdown reason trail on file
1740
  @rtype: None
1741

1742
  """
1743
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1744
                                                   instance.hvparams)
1745

    
1746
  if instance.name in running_instances:
1747
    logging.info("Instance %s already running, not starting", instance.name)
1748
    return
1749

    
1750
  try:
1751
    block_devices = _GatherAndLinkBlockDevs(instance)
1752
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1753
    hyper.StartInstance(instance, block_devices, startup_paused)
1754
    if store_reason:
1755
      _StoreInstReasonTrail(instance.name, reason)
1756
  except errors.BlockDeviceError, err:
1757
    _Fail("Block device error: %s", err, exc=True)
1758
  except errors.HypervisorError, err:
1759
    _RemoveBlockDevLinks(instance.name, instance.disks)
1760
    _Fail("Hypervisor error: %s", err, exc=True)
1761

    
1762

    
1763
def InstanceShutdown(instance, timeout, reason, store_reason=True):
1764
  """Shut an instance down.
1765

1766
  @note: this functions uses polling with a hardcoded timeout.
1767

1768
  @type instance: L{objects.Instance}
1769
  @param instance: the instance object
1770
  @type timeout: integer
1771
  @param timeout: maximum timeout for soft shutdown
1772
  @type reason: list of reasons
1773
  @param reason: the reason trail for this shutdown
1774
  @type store_reason: boolean
1775
  @param store_reason: whether to store the shutdown reason trail on file
1776
  @rtype: None
1777

1778
  """
1779
  hv_name = instance.hypervisor
1780
  hyper = hypervisor.GetHypervisor(hv_name)
1781
  iname = instance.name
1782

    
1783
  if instance.name not in hyper.ListInstances(instance.hvparams):
1784
    logging.info("Instance %s not running, doing nothing", iname)
1785
    return
1786

    
1787
  class _TryShutdown:
1788
    def __init__(self):
1789
      self.tried_once = False
1790

    
1791
    def __call__(self):
1792
      if iname not in hyper.ListInstances(instance.hvparams):
1793
        return
1794

    
1795
      try:
1796
        hyper.StopInstance(instance, retry=self.tried_once)
1797
        if store_reason:
1798
          _StoreInstReasonTrail(instance.name, reason)
1799
      except errors.HypervisorError, err:
1800
        if iname not in hyper.ListInstances(instance.hvparams):
1801
          # if the instance is no longer existing, consider this a
1802
          # success and go to cleanup
1803
          return
1804

    
1805
        _Fail("Failed to stop instance %s: %s", iname, err)
1806

    
1807
      self.tried_once = True
1808

    
1809
      raise utils.RetryAgain()
1810

    
1811
  try:
1812
    utils.Retry(_TryShutdown(), 5, timeout)
1813
  except utils.RetryTimeout:
1814
    # the shutdown did not succeed
1815
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1816

    
1817
    try:
1818
      hyper.StopInstance(instance, force=True)
1819
    except errors.HypervisorError, err:
1820
      if iname in hyper.ListInstances(instance.hvparams):
1821
        # only raise an error if the instance still exists, otherwise
1822
        # the error could simply be "instance ... unknown"!
1823
        _Fail("Failed to force stop instance %s: %s", iname, err)
1824

    
1825
    time.sleep(1)
1826

    
1827
    if iname in hyper.ListInstances(instance.hvparams):
1828
      _Fail("Could not shutdown instance %s even by destroy", iname)
1829

    
1830
  try:
1831
    hyper.CleanupInstance(instance.name)
1832
  except errors.HypervisorError, err:
1833
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1834

    
1835
  _RemoveBlockDevLinks(iname, instance.disks)
1836

    
1837

    
1838
def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1839
  """Reboot an instance.
1840

1841
  @type instance: L{objects.Instance}
1842
  @param instance: the instance object to reboot
1843
  @type reboot_type: str
1844
  @param reboot_type: the type of reboot, one the following
1845
    constants:
1846
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1847
        instance OS, do not recreate the VM
1848
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1849
        restart the VM (at the hypervisor level)
1850
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1851
        not accepted here, since that mode is handled differently, in
1852
        cmdlib, and translates into full stop and start of the
1853
        instance (instead of a call_instance_reboot RPC)
1854
  @type shutdown_timeout: integer
1855
  @param shutdown_timeout: maximum timeout for soft shutdown
1856
  @type reason: list of reasons
1857
  @param reason: the reason trail for this reboot
1858
  @rtype: None
1859

1860
  """
1861
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1862
                                                   instance.hvparams)
1863

    
1864
  if instance.name not in running_instances:
1865
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1866

    
1867
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1868
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1869
    try:
1870
      hyper.RebootInstance(instance)
1871
    except errors.HypervisorError, err:
1872
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1873
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1874
    try:
1875
      InstanceShutdown(instance, shutdown_timeout, reason, store_reason=False)
1876
      result = StartInstance(instance, False, reason, store_reason=False)
1877
      _StoreInstReasonTrail(instance.name, reason)
1878
      return result
1879
    except errors.HypervisorError, err:
1880
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1881
  else:
1882
    _Fail("Invalid reboot_type received: %s", reboot_type)
1883

    
1884

    
1885
def InstanceBalloonMemory(instance, memory):
1886
  """Resize an instance's memory.
1887

1888
  @type instance: L{objects.Instance}
1889
  @param instance: the instance object
1890
  @type memory: int
1891
  @param memory: new memory amount in MB
1892
  @rtype: None
1893

1894
  """
1895
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1896
  running = hyper.ListInstances(instance.hvparams)
1897
  if instance.name not in running:
1898
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1899
    return
1900
  try:
1901
    hyper.BalloonInstanceMemory(instance, memory)
1902
  except errors.HypervisorError, err:
1903
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1904

    
1905

    
1906
def MigrationInfo(instance):
1907
  """Gather information about an instance to be migrated.
1908

1909
  @type instance: L{objects.Instance}
1910
  @param instance: the instance definition
1911

1912
  """
1913
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1914
  try:
1915
    info = hyper.MigrationInfo(instance)
1916
  except errors.HypervisorError, err:
1917
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1918
  return info
1919

    
1920

    
1921
def AcceptInstance(instance, info, target):
1922
  """Prepare the node to accept an instance.
1923

1924
  @type instance: L{objects.Instance}
1925
  @param instance: the instance definition
1926
  @type info: string/data (opaque)
1927
  @param info: migration information, from the source node
1928
  @type target: string
1929
  @param target: target host (usually ip), on this node
1930

1931
  """
1932
  # TODO: why is this required only for DTS_EXT_MIRROR?
1933
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1934
    # Create the symlinks, as the disks are not active
1935
    # in any way
1936
    try:
1937
      _GatherAndLinkBlockDevs(instance)
1938
    except errors.BlockDeviceError, err:
1939
      _Fail("Block device error: %s", err, exc=True)
1940

    
1941
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1942
  try:
1943
    hyper.AcceptInstance(instance, info, target)
1944
  except errors.HypervisorError, err:
1945
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1946
      _RemoveBlockDevLinks(instance.name, instance.disks)
1947
    _Fail("Failed to accept instance: %s", err, exc=True)
1948

    
1949

    
1950
def FinalizeMigrationDst(instance, info, success):
1951
  """Finalize any preparation to accept an instance.
1952

1953
  @type instance: L{objects.Instance}
1954
  @param instance: the instance definition
1955
  @type info: string/data (opaque)
1956
  @param info: migration information, from the source node
1957
  @type success: boolean
1958
  @param success: whether the migration was a success or a failure
1959

1960
  """
1961
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1962
  try:
1963
    hyper.FinalizeMigrationDst(instance, info, success)
1964
  except errors.HypervisorError, err:
1965
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1966

    
1967

    
1968
def MigrateInstance(cluster_name, instance, target, live):
1969
  """Migrates an instance to another node.
1970

1971
  @type cluster_name: string
1972
  @param cluster_name: name of the cluster
1973
  @type instance: L{objects.Instance}
1974
  @param instance: the instance definition
1975
  @type target: string
1976
  @param target: the target node name
1977
  @type live: boolean
1978
  @param live: whether the migration should be done live or not (the
1979
      interpretation of this parameter is left to the hypervisor)
1980
  @raise RPCFail: if migration fails for some reason
1981

1982
  """
1983
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1984

    
1985
  try:
1986
    hyper.MigrateInstance(cluster_name, instance, target, live)
1987
  except errors.HypervisorError, err:
1988
    _Fail("Failed to migrate instance: %s", err, exc=True)
1989

    
1990

    
1991
def FinalizeMigrationSource(instance, success, live):
1992
  """Finalize the instance migration on the source node.
1993

1994
  @type instance: L{objects.Instance}
1995
  @param instance: the instance definition of the migrated instance
1996
  @type success: bool
1997
  @param success: whether the migration succeeded or not
1998
  @type live: bool
1999
  @param live: whether the user requested a live migration or not
2000
  @raise RPCFail: If the execution fails for some reason
2001

2002
  """
2003
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
2004

    
2005
  try:
2006
    hyper.FinalizeMigrationSource(instance, success, live)
2007
  except Exception, err:  # pylint: disable=W0703
2008
    _Fail("Failed to finalize the migration on the source node: %s", err,
2009
          exc=True)
2010

    
2011

    
2012
def GetMigrationStatus(instance):
2013
  """Get the migration status
2014

2015
  @type instance: L{objects.Instance}
2016
  @param instance: the instance that is being migrated
2017
  @rtype: L{objects.MigrationStatus}
2018
  @return: the status of the current migration (one of
2019
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
2020
           progress info that can be retrieved from the hypervisor
2021
  @raise RPCFail: If the migration status cannot be retrieved
2022

2023
  """
2024
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
2025
  try:
2026
    return hyper.GetMigrationStatus(instance)
2027
  except Exception, err:  # pylint: disable=W0703
2028
    _Fail("Failed to get migration status: %s", err, exc=True)
2029

    
2030

    
2031
def HotplugDevice(instance, action, dev_type, device, extra, seq):
2032
  """Hotplug a device
2033

2034
  Hotplug is currently supported only for KVM Hypervisor.
2035
  @type instance: L{objects.Instance}
2036
  @param instance: the instance to which we hotplug a device
2037
  @type action: string
2038
  @param action: the hotplug action to perform
2039
  @type dev_type: string
2040
  @param dev_type: the device type to hotplug
2041
  @type device: either L{objects.NIC} or L{objects.Disk}
2042
  @param device: the device object to hotplug
2043
  @type extra: string
2044
  @param extra: extra info used by hotplug code (e.g. disk link)
2045
  @type seq: int
2046
  @param seq: the index of the device from master perspective
2047
  @raise RPCFail: in case instance does not have KVM hypervisor
2048

2049
  """
2050
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
2051
  try:
2052
    hyper.VerifyHotplugSupport(instance, action, dev_type)
2053
  except errors.HotplugError, err:
2054
    _Fail("Hotplug is not supported: %s", err)
2055

    
2056
  if action == constants.HOTPLUG_ACTION_ADD:
2057
    fn = hyper.HotAddDevice
2058
  elif action == constants.HOTPLUG_ACTION_REMOVE:
2059
    fn = hyper.HotDelDevice
2060
  elif action == constants.HOTPLUG_ACTION_MODIFY:
2061
    fn = hyper.HotModDevice
2062
  else:
2063
    assert action in constants.HOTPLUG_ALL_ACTIONS
2064

    
2065
  return fn(instance, dev_type, device, extra, seq)
2066

    
2067

    
2068
def HotplugSupported(instance):
2069
  """Checks if hotplug is generally supported.
2070

2071
  """
2072
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
2073
  try:
2074
    hyper.HotplugSupported(instance)
2075
  except errors.HotplugError, err:
2076
    _Fail("Hotplug is not supported: %s", err)
2077

    
2078

    
2079
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
2080
  """Creates a block device for an instance.
2081

2082
  @type disk: L{objects.Disk}
2083
  @param disk: the object describing the disk we should create
2084
  @type size: int
2085
  @param size: the size of the physical underlying device, in MiB
2086
  @type owner: str
2087
  @param owner: the name of the instance for which disk is created,
2088
      used for device cache data
2089
  @type on_primary: boolean
2090
  @param on_primary:  indicates if it is the primary node or not
2091
  @type info: string
2092
  @param info: string that will be sent to the physical device
2093
      creation, used for example to set (LVM) tags on LVs
2094
  @type excl_stor: boolean
2095
  @param excl_stor: Whether exclusive_storage is active
2096

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

2101
  """
2102
  # TODO: remove the obsolete "size" argument
2103
  # pylint: disable=W0613
2104
  clist = []
2105
  if disk.children:
2106
    for child in disk.children:
2107
      try:
2108
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
2109
      except errors.BlockDeviceError, err:
2110
        _Fail("Can't assemble device %s: %s", child, err)
2111
      if on_primary or disk.AssembleOnSecondary():
2112
        # we need the children open in case the device itself has to
2113
        # be assembled
2114
        try:
2115
          # pylint: disable=E1103
2116
          crdev.Open()
2117
        except errors.BlockDeviceError, err:
2118
          _Fail("Can't make child '%s' read-write: %s", child, err)
2119
      clist.append(crdev)
2120

    
2121
  try:
2122
    device = bdev.Create(disk, clist, excl_stor)
2123
  except errors.BlockDeviceError, err:
2124
    _Fail("Can't create block device: %s", err)
2125

    
2126
  if on_primary or disk.AssembleOnSecondary():
2127
    try:
2128
      device.Assemble()
2129
    except errors.BlockDeviceError, err:
2130
      _Fail("Can't assemble device after creation, unusual event: %s", err)
2131
    if on_primary or disk.OpenOnSecondary():
2132
      try:
2133
        device.Open(force=True)
2134
      except errors.BlockDeviceError, err:
2135
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
2136
    DevCacheManager.UpdateCache(device.dev_path, owner,
2137
                                on_primary, disk.iv_name)
2138

    
2139
  device.SetInfo(info)
2140

    
2141
  return device.unique_id
2142

    
2143

    
2144
def _WipeDevice(path, offset, size):
2145
  """This function actually wipes the device.
2146

2147
  @param path: The path to the device to wipe
2148
  @param offset: The offset in MiB in the file
2149
  @param size: The size in MiB to write
2150

2151
  """
2152
  # Internal sizes are always in Mebibytes; if the following "dd" command
2153
  # should use a different block size the offset and size given to this
2154
  # function must be adjusted accordingly before being passed to "dd".
2155
  block_size = 1024 * 1024
2156

    
2157
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
2158
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
2159
         "count=%d" % size]
2160
  result = utils.RunCmd(cmd)
2161

    
2162
  if result.failed:
2163
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
2164
          result.fail_reason, result.output)
2165

    
2166

    
2167
def BlockdevWipe(disk, offset, size):
2168
  """Wipes a block device.
2169

2170
  @type disk: L{objects.Disk}
2171
  @param disk: the disk object we want to wipe
2172
  @type offset: int
2173
  @param offset: The offset in MiB in the file
2174
  @type size: int
2175
  @param size: The size in MiB to write
2176

2177
  """
2178
  try:
2179
    rdev = _RecursiveFindBD(disk)
2180
  except errors.BlockDeviceError:
2181
    rdev = None
2182

    
2183
  if not rdev:
2184
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
2185

    
2186
  # Do cross verify some of the parameters
2187
  if offset < 0:
2188
    _Fail("Negative offset")
2189
  if size < 0:
2190
    _Fail("Negative size")
2191
  if offset > rdev.size:
2192
    _Fail("Offset is bigger than device size")
2193
  if (offset + size) > rdev.size:
2194
    _Fail("The provided offset and size to wipe is bigger than device size")
2195

    
2196
  _WipeDevice(rdev.dev_path, offset, size)
2197

    
2198

    
2199
def BlockdevPauseResumeSync(disks, pause):
2200
  """Pause or resume the sync of the block device.
2201

2202
  @type disks: list of L{objects.Disk}
2203
  @param disks: the disks object we want to pause/resume
2204
  @type pause: bool
2205
  @param pause: Wheater to pause or resume
2206

2207
  """
2208
  success = []
2209
  for disk in disks:
2210
    try:
2211
      rdev = _RecursiveFindBD(disk)
2212
    except errors.BlockDeviceError:
2213
      rdev = None
2214

    
2215
    if not rdev:
2216
      success.append((False, ("Cannot change sync for device %s:"
2217
                              " device not found" % disk.iv_name)))
2218
      continue
2219

    
2220
    result = rdev.PauseResumeSync(pause)
2221

    
2222
    if result:
2223
      success.append((result, None))
2224
    else:
2225
      if pause:
2226
        msg = "Pause"
2227
      else:
2228
        msg = "Resume"
2229
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
2230

    
2231
  return success
2232

    
2233

    
2234
def BlockdevRemove(disk):
2235
  """Remove a block device.
2236

2237
  @note: This is intended to be called recursively.
2238

2239
  @type disk: L{objects.Disk}
2240
  @param disk: the disk object we should remove
2241
  @rtype: boolean
2242
  @return: the success of the operation
2243

2244
  """
2245
  msgs = []
2246
  try:
2247
    rdev = _RecursiveFindBD(disk)
2248
  except errors.BlockDeviceError, err:
2249
    # probably can't attach
2250
    logging.info("Can't attach to device %s in remove", disk)
2251
    rdev = None
2252
  if rdev is not None:
2253
    r_path = rdev.dev_path
2254

    
2255
    def _TryRemove():
2256
      try:
2257
        rdev.Remove()
2258
        return []
2259
      except errors.BlockDeviceError, err:
2260
        return [str(err)]
2261

    
2262
    msgs.extend(utils.SimpleRetry([], _TryRemove,
2263
                                  constants.DISK_REMOVE_RETRY_INTERVAL,
2264
                                  constants.DISK_REMOVE_RETRY_TIMEOUT))
2265

    
2266
    if not msgs:
2267
      DevCacheManager.RemoveCache(r_path)
2268

    
2269
  if disk.children:
2270
    for child in disk.children:
2271
      try:
2272
        BlockdevRemove(child)
2273
      except RPCFail, err:
2274
        msgs.append(str(err))
2275

    
2276
  if msgs:
2277
    _Fail("; ".join(msgs))
2278

    
2279

    
2280
def _RecursiveAssembleBD(disk, owner, as_primary):
2281
  """Activate a block device for an instance.
2282

2283
  This is run on the primary and secondary nodes for an instance.
2284

2285
  @note: this function is called recursively.
2286

2287
  @type disk: L{objects.Disk}
2288
  @param disk: the disk we try to assemble
2289
  @type owner: str
2290
  @param owner: the name of the instance which owns the disk
2291
  @type as_primary: boolean
2292
  @param as_primary: if we should make the block device
2293
      read/write
2294

2295
  @return: the assembled device or None (in case no device
2296
      was assembled)
2297
  @raise errors.BlockDeviceError: in case there is an error
2298
      during the activation of the children or the device
2299
      itself
2300

2301
  """
2302
  children = []
2303
  if disk.children:
2304
    mcn = disk.ChildrenNeeded()
2305
    if mcn == -1:
2306
      mcn = 0 # max number of Nones allowed
2307
    else:
2308
      mcn = len(disk.children) - mcn # max number of Nones
2309
    for chld_disk in disk.children:
2310
      try:
2311
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
2312
      except errors.BlockDeviceError, err:
2313
        if children.count(None) >= mcn:
2314
          raise
2315
        cdev = None
2316
        logging.error("Error in child activation (but continuing): %s",
2317
                      str(err))
2318
      children.append(cdev)
2319

    
2320
  if as_primary or disk.AssembleOnSecondary():
2321
    r_dev = bdev.Assemble(disk, children)
2322
    result = r_dev
2323
    if as_primary or disk.OpenOnSecondary():
2324
      r_dev.Open()
2325
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
2326
                                as_primary, disk.iv_name)
2327

    
2328
  else:
2329
    result = True
2330
  return result
2331

    
2332

    
2333
def BlockdevAssemble(disk, owner, as_primary, idx):
2334
  """Activate a block device for an instance.
2335

2336
  This is a wrapper over _RecursiveAssembleBD.
2337

2338
  @rtype: str or boolean
2339
  @return: a tuple with the C{/dev/...} path and the created symlink
2340
      for primary nodes, and (C{True}, C{True}) for secondary nodes
2341

2342
  """
2343
  try:
2344
    result = _RecursiveAssembleBD(disk, owner, as_primary)
2345
    if isinstance(result, BlockDev):
2346
      # pylint: disable=E1103
2347
      dev_path = result.dev_path
2348
      link_name = None
2349
      if as_primary:
2350
        link_name = _SymlinkBlockDev(owner, dev_path, idx)
2351
    elif result:
2352
      return result, result
2353
    else:
2354
      _Fail("Unexpected result from _RecursiveAssembleBD")
2355
  except errors.BlockDeviceError, err:
2356
    _Fail("Error while assembling disk: %s", err, exc=True)
2357
  except OSError, err:
2358
    _Fail("Error while symlinking disk: %s", err, exc=True)
2359

    
2360
  return dev_path, link_name
2361

    
2362

    
2363
def BlockdevShutdown(disk):
2364
  """Shut down a block device.
2365

2366
  First, if the device is assembled (Attach() is successful), then
2367
  the device is shutdown. Then the children of the device are
2368
  shutdown.
2369

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

2374
  @type disk: L{objects.Disk}
2375
  @param disk: the description of the disk we should
2376
      shutdown
2377
  @rtype: None
2378

2379
  """
2380
  msgs = []
2381
  r_dev = _RecursiveFindBD(disk)
2382
  if r_dev is not None:
2383
    r_path = r_dev.dev_path
2384
    try:
2385
      r_dev.Shutdown()
2386
      DevCacheManager.RemoveCache(r_path)
2387
    except errors.BlockDeviceError, err:
2388
      msgs.append(str(err))
2389

    
2390
  if disk.children:
2391
    for child in disk.children:
2392
      try:
2393
        BlockdevShutdown(child)
2394
      except RPCFail, err:
2395
        msgs.append(str(err))
2396

    
2397
  if msgs:
2398
    _Fail("; ".join(msgs))
2399

    
2400

    
2401
def BlockdevAddchildren(parent_cdev, new_cdevs):
2402
  """Extend a mirrored block device.
2403

2404
  @type parent_cdev: L{objects.Disk}
2405
  @param parent_cdev: the disk to which we should add children
2406
  @type new_cdevs: list of L{objects.Disk}
2407
  @param new_cdevs: the list of children which we should add
2408
  @rtype: None
2409

2410
  """
2411
  parent_bdev = _RecursiveFindBD(parent_cdev)
2412
  if parent_bdev is None:
2413
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
2414
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
2415
  if new_bdevs.count(None) > 0:
2416
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
2417
  parent_bdev.AddChildren(new_bdevs)
2418

    
2419

    
2420
def BlockdevRemovechildren(parent_cdev, new_cdevs):
2421
  """Shrink a mirrored block device.
2422

2423
  @type parent_cdev: L{objects.Disk}
2424
  @param parent_cdev: the disk from which we should remove children
2425
  @type new_cdevs: list of L{objects.Disk}
2426
  @param new_cdevs: the list of children which we should remove
2427
  @rtype: None
2428

2429
  """
2430
  parent_bdev = _RecursiveFindBD(parent_cdev)
2431
  if parent_bdev is None:
2432
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
2433
  devs = []
2434
  for disk in new_cdevs:
2435
    rpath = disk.StaticDevPath()
2436
    if rpath is None:
2437
      bd = _RecursiveFindBD(disk)
2438
      if bd is None:
2439
        _Fail("Can't find device %s while removing children", disk)
2440
      else:
2441
        devs.append(bd.dev_path)
2442
    else:
2443
      if not utils.IsNormAbsPath(rpath):
2444
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
2445
      devs.append(rpath)
2446
  parent_bdev.RemoveChildren(devs)
2447

    
2448

    
2449
def BlockdevGetmirrorstatus(disks):
2450
  """Get the mirroring status of a list of devices.
2451

2452
  @type disks: list of L{objects.Disk}
2453
  @param disks: the list of disks which we should query
2454
  @rtype: disk
2455
  @return: List of L{objects.BlockDevStatus}, one for each disk
2456
  @raise errors.BlockDeviceError: if any of the disks cannot be
2457
      found
2458

2459
  """
2460
  stats = []
2461
  for dsk in disks:
2462
    rbd = _RecursiveFindBD(dsk)
2463
    if rbd is None:
2464
      _Fail("Can't find device %s", dsk)
2465

    
2466
    stats.append(rbd.CombinedSyncStatus())
2467

    
2468
  return stats
2469

    
2470

    
2471
def BlockdevGetmirrorstatusMulti(disks):
2472
  """Get the mirroring status of a list of devices.
2473

2474
  @type disks: list of L{objects.Disk}
2475
  @param disks: the list of disks which we should query
2476
  @rtype: disk
2477
  @return: List of tuples, (bool, status), one for each disk; bool denotes
2478
    success/failure, status is L{objects.BlockDevStatus} on success, string
2479
    otherwise
2480

2481
  """
2482
  result = []
2483
  for disk in disks:
2484
    try:
2485
      rbd = _RecursiveFindBD(disk)
2486
      if rbd is None:
2487
        result.append((False, "Can't find device %s" % disk))
2488
        continue
2489

    
2490
      status = rbd.CombinedSyncStatus()
2491
    except errors.BlockDeviceError, err:
2492
      logging.exception("Error while getting disk status")
2493
      result.append((False, str(err)))
2494
    else:
2495
      result.append((True, status))
2496

    
2497
  assert len(disks) == len(result)
2498

    
2499
  return result
2500

    
2501

    
2502
def _RecursiveFindBD(disk):
2503
  """Check if a device is activated.
2504

2505
  If so, return information about the real device.
2506

2507
  @type disk: L{objects.Disk}
2508
  @param disk: the disk object we need to find
2509

2510
  @return: None if the device can't be found,
2511
      otherwise the device instance
2512

2513
  """
2514
  children = []
2515
  if disk.children:
2516
    for chdisk in disk.children:
2517
      children.append(_RecursiveFindBD(chdisk))
2518

    
2519
  return bdev.FindDevice(disk, children)
2520

    
2521

    
2522
def _OpenRealBD(disk):
2523
  """Opens the underlying block device of a disk.
2524

2525
  @type disk: L{objects.Disk}
2526
  @param disk: the disk object we want to open
2527

2528
  """
2529
  real_disk = _RecursiveFindBD(disk)
2530
  if real_disk is None:
2531
    _Fail("Block device '%s' is not set up", disk)
2532

    
2533
  real_disk.Open()
2534

    
2535
  return real_disk
2536

    
2537

    
2538
def BlockdevFind(disk):
2539
  """Check if a device is activated.
2540

2541
  If it is, return information about the real device.
2542

2543
  @type disk: L{objects.Disk}
2544
  @param disk: the disk to find
2545
  @rtype: None or objects.BlockDevStatus
2546
  @return: None if the disk cannot be found, otherwise a the current
2547
           information
2548

2549
  """
2550
  try:
2551
    rbd = _RecursiveFindBD(disk)
2552
  except errors.BlockDeviceError, err:
2553
    _Fail("Failed to find device: %s", err, exc=True)
2554

    
2555
  if rbd is None:
2556
    return None
2557

    
2558
  return rbd.GetSyncStatus()
2559

    
2560

    
2561
def BlockdevGetdimensions(disks):
2562
  """Computes the size of the given disks.
2563

2564
  If a disk is not found, returns None instead.
2565

2566
  @type disks: list of L{objects.Disk}
2567
  @param disks: the list of disk to compute the size for
2568
  @rtype: list
2569
  @return: list with elements None if the disk cannot be found,
2570
      otherwise the pair (size, spindles), where spindles is None if the
2571
      device doesn't support that
2572

2573
  """
2574
  result = []
2575
  for cf in disks:
2576
    try:
2577
      rbd = _RecursiveFindBD(cf)
2578
    except errors.BlockDeviceError:
2579
      result.append(None)
2580
      continue
2581
    if rbd is None:
2582
      result.append(None)
2583
    else:
2584
      result.append(rbd.GetActualDimensions())
2585
  return result
2586

    
2587

    
2588
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2589
  """Write a file to the filesystem.
2590

2591
  This allows the master to overwrite(!) a file. It will only perform
2592
  the operation if the file belongs to a list of configuration files.
2593

2594
  @type file_name: str
2595
  @param file_name: the target file name
2596
  @type data: str
2597
  @param data: the new contents of the file
2598
  @type mode: int
2599
  @param mode: the mode to give the file (can be None)
2600
  @type uid: string
2601
  @param uid: the owner of the file
2602
  @type gid: string
2603
  @param gid: the group of the file
2604
  @type atime: float
2605
  @param atime: the atime to set on the file (can be None)
2606
  @type mtime: float
2607
  @param mtime: the mtime to set on the file (can be None)
2608
  @rtype: None
2609

2610
  """
2611
  file_name = vcluster.LocalizeVirtualPath(file_name)
2612

    
2613
  if not os.path.isabs(file_name):
2614
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2615

    
2616
  if file_name not in _ALLOWED_UPLOAD_FILES:
2617
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2618
          file_name)
2619

    
2620
  raw_data = _Decompress(data)
2621

    
2622
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2623
    _Fail("Invalid username/groupname type")
2624

    
2625
  getents = runtime.GetEnts()
2626
  uid = getents.LookupUser(uid)
2627
  gid = getents.LookupGroup(gid)
2628

    
2629
  utils.SafeWriteFile(file_name, None,
2630
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2631
                      atime=atime, mtime=mtime)
2632

    
2633

    
2634
def RunOob(oob_program, command, node, timeout):
2635
  """Executes oob_program with given command on given node.
2636

2637
  @param oob_program: The path to the executable oob_program
2638
  @param command: The command to invoke on oob_program
2639
  @param node: The node given as an argument to the program
2640
  @param timeout: Timeout after which we kill the oob program
2641

2642
  @return: stdout
2643
  @raise RPCFail: If execution fails for some reason
2644

2645
  """
2646
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2647

    
2648
  if result.failed:
2649
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2650
          result.fail_reason, result.output)
2651

    
2652
  return result.stdout
2653

    
2654

    
2655
def _OSOndiskAPIVersion(os_dir):
2656
  """Compute and return the API version of a given OS.
2657

2658
  This function will try to read the API version of the OS residing in
2659
  the 'os_dir' directory.
2660

2661
  @type os_dir: str
2662
  @param os_dir: the directory in which we should look for the OS
2663
  @rtype: tuple
2664
  @return: tuple (status, data) with status denoting the validity and
2665
      data holding either the vaid versions or an error message
2666

2667
  """
2668
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2669

    
2670
  try:
2671
    st = os.stat(api_file)
2672
  except EnvironmentError, err:
2673
    return False, ("Required file '%s' not found under path %s: %s" %
2674
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2675

    
2676
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2677
    return False, ("File '%s' in %s is not a regular file" %
2678
                   (constants.OS_API_FILE, os_dir))
2679

    
2680
  try:
2681
    api_versions = utils.ReadFile(api_file).splitlines()
2682
  except EnvironmentError, err:
2683
    return False, ("Error while reading the API version file at %s: %s" %
2684
                   (api_file, utils.ErrnoOrStr(err)))
2685

    
2686
  try:
2687
    api_versions = [int(version.strip()) for version in api_versions]
2688
  except (TypeError, ValueError), err:
2689
    return False, ("API version(s) can't be converted to integer: %s" %
2690
                   str(err))
2691

    
2692
  return True, api_versions
2693

    
2694

    
2695
def DiagnoseOS(top_dirs=None):
2696
  """Compute the validity for all OSes.
2697

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

2714
  """
2715
  if top_dirs is None:
2716
    top_dirs = pathutils.OS_SEARCH_PATH
2717

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

    
2740
  return result
2741

    
2742

    
2743
def _TryOSFromDisk(name, base_dir=None):
2744
  """Create an OS instance from disk.
2745

2746
  This function will return an OS instance if the given name is a
2747
  valid OS name.
2748

2749
  @type base_dir: string
2750
  @keyword base_dir: Base directory containing OS installations.
2751
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2752
  @rtype: tuple
2753
  @return: success and either the OS instance if we find a valid one,
2754
      or error message
2755

2756
  """
2757
  if base_dir is None:
2758
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2759
  else:
2760
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2761

    
2762
  if os_dir is None:
2763
    return False, "Directory for OS %s not found in search path" % name
2764

    
2765
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2766
  if not status:
2767
    # push the error up
2768
    return status, api_versions
2769

    
2770
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2771
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2772
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2773

    
2774
  # OS Files dictionary, we will populate it with the absolute path
2775
  # names; if the value is True, then it is a required file, otherwise
2776
  # an optional one
2777
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2778

    
2779
  if max(api_versions) >= constants.OS_API_V15:
2780
    os_files[constants.OS_VARIANTS_FILE] = False
2781

    
2782
  if max(api_versions) >= constants.OS_API_V20:
2783
    os_files[constants.OS_PARAMETERS_FILE] = True
2784
  else:
2785
    del os_files[constants.OS_SCRIPT_VERIFY]
2786

    
2787
  for (filename, required) in os_files.items():
2788
    os_files[filename] = utils.PathJoin(os_dir, filename)
2789

    
2790
    try:
2791
      st = os.stat(os_files[filename])
2792
    except EnvironmentError, err:
2793
      if err.errno == errno.ENOENT and not required:
2794
        del os_files[filename]
2795
        continue
2796
      return False, ("File '%s' under path '%s' is missing (%s)" %
2797
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2798

    
2799
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2800
      return False, ("File '%s' under path '%s' is not a regular file" %
2801
                     (filename, os_dir))
2802

    
2803
    if filename in constants.OS_SCRIPTS:
2804
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2805
        return False, ("File '%s' under path '%s' is not executable" %
2806
                       (filename, os_dir))
2807

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

    
2820
  parameters = []
2821
  if constants.OS_PARAMETERS_FILE in os_files:
2822
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2823
    try:
2824
      parameters = utils.ReadFile(parameters_file).splitlines()
2825
    except EnvironmentError, err:
2826
      return False, ("Error while reading the OS parameters file at %s: %s" %
2827
                     (parameters_file, utils.ErrnoOrStr(err)))
2828
    parameters = [v.split(None, 1) for v in parameters]
2829

    
2830
  os_obj = objects.OS(name=name, path=os_dir,
2831
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2832
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2833
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2834
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2835
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2836
                                                 None),
2837
                      supported_variants=variants,
2838
                      supported_parameters=parameters,
2839
                      api_versions=api_versions)
2840
  return True, os_obj
2841

    
2842

    
2843
def OSFromDisk(name, base_dir=None):
2844
  """Create an OS instance from disk.
2845

2846
  This function will return an OS instance if the given name is a
2847
  valid OS name. Otherwise, it will raise an appropriate
2848
  L{RPCFail} exception, detailing why this is not a valid OS.
2849

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

2853
  @type base_dir: string
2854
  @keyword base_dir: Base directory containing OS installations.
2855
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2856
  @rtype: L{objects.OS}
2857
  @return: the OS instance if we find a valid one
2858
  @raise RPCFail: if we don't find a valid OS
2859

2860
  """
2861
  name_only = objects.OS.GetName(name)
2862
  status, payload = _TryOSFromDisk(name_only, base_dir)
2863

    
2864
  if not status:
2865
    _Fail(payload)
2866

    
2867
  return payload
2868

    
2869

    
2870
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2871
  """Calculate the basic environment for an os script.
2872

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

2886
  """
2887
  result = {}
2888
  api_version = \
2889
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2890
  result["OS_API_VERSION"] = "%d" % api_version
2891
  result["OS_NAME"] = inst_os.name
2892
  result["DEBUG_LEVEL"] = "%d" % debug
2893

    
2894
  # OS variants
2895
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2896
    variant = objects.OS.GetVariant(os_name)
2897
    if not variant:
2898
      variant = inst_os.supported_variants[0]
2899
  else:
2900
    variant = ""
2901
  result["OS_VARIANT"] = variant
2902

    
2903
  # OS params
2904
  for pname, pvalue in os_params.items():
2905
    result["OSP_%s" % pname.upper()] = pvalue
2906

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

    
2912
  return result
2913

    
2914

    
2915
def OSEnvironment(instance, inst_os, debug=0):
2916
  """Calculate the environment for an os script.
2917

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

2929
  """
2930
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2931

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

    
2935
  result["HYPERVISOR"] = instance.hypervisor
2936
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2937
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2938
  result["INSTANCE_SECONDARY_NODES"] = \
2939
      ("%s" % " ".join(instance.secondary_nodes))
2940

    
2941
  # Disks
2942
  for idx, disk in enumerate(instance.disks):
2943
    real_disk = _OpenRealBD(disk)
2944
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2945
    result["DISK_%d_ACCESS" % idx] = disk.mode
2946
    result["DISK_%d_UUID" % idx] = disk.uuid
2947
    if disk.name:
2948
      result["DISK_%d_NAME" % idx] = disk.name
2949
    if constants.HV_DISK_TYPE in instance.hvparams:
2950
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2951
        instance.hvparams[constants.HV_DISK_TYPE]
2952
    if disk.dev_type in constants.DTS_BLOCK:
2953
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2954
    elif disk.dev_type in constants.DTS_FILEBASED:
2955
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2956
        "file:%s" % disk.logical_id[0]
2957

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

    
2978
  # HV/BE params
2979
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2980
    for key, value in source.items():
2981
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2982

    
2983
  return result
2984

    
2985

    
2986
def DiagnoseExtStorage(top_dirs=None):
2987
  """Compute the validity for all ExtStorage Providers.
2988

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

3004
  """
3005
  if top_dirs is None:
3006
    top_dirs = pathutils.ES_SEARCH_PATH
3007

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

    
3028
  return result
3029

    
3030

    
3031
def BlockdevGrow(disk, amount, dryrun, backingstore, excl_stor):
3032
  """Grow a stack of block devices.
3033

3034
  This function is called recursively, with the childrens being the
3035
  first ones to resize.
3036

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

3053
  """
3054
  r_dev = _RecursiveFindBD(disk)
3055
  if r_dev is None:
3056
    _Fail("Cannot find block device %s", disk)
3057

    
3058
  try:
3059
    r_dev.Grow(amount, dryrun, backingstore, excl_stor)
3060
  except errors.BlockDeviceError, err:
3061
    _Fail("Failed to grow block device: %s", err, exc=True)
3062

    
3063

    
3064
def BlockdevSnapshot(disk):
3065
  """Create a snapshot copy of a block device.
3066

3067
  This function is called recursively, and the snapshot is actually created
3068
  just for the leaf lvm backend device.
3069

3070
  @type disk: L{objects.Disk}
3071
  @param disk: the disk to be snapshotted
3072
  @rtype: string
3073
  @return: snapshot disk ID as (vg, lv)
3074

3075
  """
3076
  if disk.dev_type == constants.DT_DRBD8:
3077
    if not disk.children:
3078
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
3079
            disk.unique_id)
3080
    return BlockdevSnapshot(disk.children[0])
3081
  elif disk.dev_type == constants.DT_PLAIN:
3082
    r_dev = _RecursiveFindBD(disk)
3083
    if r_dev is not None:
3084
      # FIXME: choose a saner value for the snapshot size
3085
      # let's stay on the safe side and ask for the full size, for now
3086
      return r_dev.Snapshot(disk.size)
3087
    else:
3088
      _Fail("Cannot find block device %s", disk)
3089
  else:
3090
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
3091
          disk.unique_id, disk.dev_type)
3092

    
3093

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

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

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

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

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

    
3119

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

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

3130
  @rtype: None
3131

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

    
3136
  config = objects.SerializableConfigParser()
3137

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

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

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

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

    
3185
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
3186

    
3187
  # New-style hypervisor/backend parameters
3188

    
3189
  config.add_section(constants.INISECT_HYP)
3190
  for name, value in instance.hvparams.items():
3191
    if name not in constants.HVC_GLOBALS:
3192
      config.set(constants.INISECT_HYP, name, str(value))
3193

    
3194
  config.add_section(constants.INISECT_BEP)
3195
  for name, value in instance.beparams.items():
3196
    config.set(constants.INISECT_BEP, name, str(value))
3197

    
3198
  config.add_section(constants.INISECT_OSP)
3199
  for name, value in instance.osparams.items():
3200
    config.set(constants.INISECT_OSP, name, str(value))
3201

    
3202
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
3203
                  data=config.Dumps())
3204
  shutil.rmtree(finaldestdir, ignore_errors=True)
3205
  shutil.move(destdir, finaldestdir)
3206

    
3207

    
3208
def ExportInfo(dest):
3209
  """Get export configuration information.
3210

3211
  @type dest: str
3212
  @param dest: directory containing the export
3213

3214
  @rtype: L{objects.SerializableConfigParser}
3215
  @return: a serializable config file containing the
3216
      export info
3217

3218
  """
3219
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
3220

    
3221
  config = objects.SerializableConfigParser()
3222
  config.read(cff)
3223

    
3224
  if (not config.has_section(constants.INISECT_EXP) or
3225
      not config.has_section(constants.INISECT_INS)):
3226
    _Fail("Export info file doesn't have the required fields")
3227

    
3228
  return config.Dumps()
3229

    
3230

    
3231
def ListExports():
3232
  """Return a list of exports currently available on this machine.
3233

3234
  @rtype: list
3235
  @return: list of the exports
3236

3237
  """
3238
  if os.path.isdir(pathutils.EXPORT_DIR):
3239
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
3240
  else:
3241
    _Fail("No exports directory")
3242

    
3243

    
3244
def RemoveExport(export):
3245
  """Remove an existing export from the node.
3246

3247
  @type export: str
3248
  @param export: the name of the export to remove
3249
  @rtype: None
3250

3251
  """
3252
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
3253

    
3254
  try:
3255
    shutil.rmtree(target)
3256
  except EnvironmentError, err:
3257
    _Fail("Error while removing the export: %s", err, exc=True)
3258

    
3259

    
3260
def BlockdevRename(devlist):
3261
  """Rename a list of block devices.
3262

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

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

    
3298

    
3299
def _TransformFileStorageDir(fs_dir):
3300
  """Checks whether given file_storage_dir is valid.
3301

3302
  Checks wheter the given fs_dir is within the cluster-wide default
3303
  file_storage_dir or the shared_file_storage_dir, which are stored in
3304
  SimpleStore. Only paths under those directories are allowed.
3305

3306
  @type fs_dir: str
3307
  @param fs_dir: the path to check
3308

3309
  @return: the normalized path if valid, None otherwise
3310

3311
  """
3312
  filestorage.CheckFileStoragePath(fs_dir)
3313

    
3314
  return os.path.normpath(fs_dir)
3315

    
3316

    
3317
def CreateFileStorageDir(file_storage_dir):
3318
  """Create file storage directory.
3319

3320
  @type file_storage_dir: str
3321
  @param file_storage_dir: directory to create
3322

3323
  @rtype: tuple
3324
  @return: tuple with first element a boolean indicating wheter dir
3325
      creation was successful or not
3326

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

    
3340

    
3341
def RemoveFileStorageDir(file_storage_dir):
3342
  """Remove file storage directory.
3343

3344
  Remove it only if it's empty. If not log an error and return.
3345

3346
  @type file_storage_dir: str
3347
  @param file_storage_dir: the directory we should cleanup
3348
  @rtype: tuple (success,)
3349
  @return: tuple of one element, C{success}, denoting
3350
      whether the operation was successful
3351

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

    
3365

    
3366
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
3367
  """Rename the file storage directory.
3368

3369
  @type old_file_storage_dir: str
3370
  @param old_file_storage_dir: the current path
3371
  @type new_file_storage_dir: str
3372
  @param new_file_storage_dir: the name we should rename to
3373
  @rtype: tuple (success,)
3374
  @return: tuple of one element, C{success}, denoting
3375
      whether the operation was successful
3376

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

    
3395

    
3396
def _EnsureJobQueueFile(file_name):
3397
  """Checks whether the given filename is in the queue directory.
3398

3399
  @type file_name: str
3400
  @param file_name: the file name we should check
3401
  @rtype: None
3402
  @raises RPCFail: if the file is not valid
3403

3404
  """
3405
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
3406
    _Fail("Passed job queue file '%s' does not belong to"
3407
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
3408

    
3409

    
3410
def JobQueueUpdate(file_name, content):
3411
  """Updates a file in the queue directory.
3412

3413
  This is just a wrapper over L{utils.io.WriteFile}, with proper
3414
  checking.
3415

3416
  @type file_name: str
3417
  @param file_name: the job file name
3418
  @type content: str
3419
  @param content: the new job contents
3420
  @rtype: boolean
3421
  @return: the success of the operation
3422

3423
  """
3424
  file_name = vcluster.LocalizeVirtualPath(file_name)
3425

    
3426
  _EnsureJobQueueFile(file_name)
3427
  getents = runtime.GetEnts()
3428

    
3429
  # Write and replace the file atomically
3430
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3431
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3432

    
3433

    
3434
def JobQueueRename(old, new):
3435
  """Renames a job queue file.
3436

3437
  This is just a wrapper over os.rename with proper checking.
3438

3439
  @type old: str
3440
  @param old: the old (actual) file name
3441
  @type new: str
3442
  @param new: the desired file name
3443
  @rtype: tuple
3444
  @return: the success of the operation and payload
3445

3446
  """
3447
  old = vcluster.LocalizeVirtualPath(old)
3448
  new = vcluster.LocalizeVirtualPath(new)
3449

    
3450
  _EnsureJobQueueFile(old)
3451
  _EnsureJobQueueFile(new)
3452

    
3453
  getents = runtime.GetEnts()
3454

    
3455
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3456
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3457

    
3458

    
3459
def BlockdevClose(instance_name, disks):
3460
  """Closes the given block devices.
3461

3462
  This means they will be switched to secondary mode (in case of
3463
  DRBD).
3464

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

3475
  """
3476
  bdevs = []
3477
  for cf in disks:
3478
    rd = _RecursiveFindBD(cf)
3479
    if rd is None:
3480
      _Fail("Can't find device %s", cf)
3481
    bdevs.append(rd)
3482

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

    
3495

    
3496
def ValidateHVParams(hvname, hvparams):
3497
  """Validates the given hypervisor parameters.
3498

3499
  @type hvname: string
3500
  @param hvname: the hypervisor name
3501
  @type hvparams: dict
3502
  @param hvparams: the hypervisor parameters to be validated
3503
  @rtype: None
3504

3505
  """
3506
  try:
3507
    hv_type = hypervisor.GetHypervisor(hvname)
3508
    hv_type.ValidateParameters(hvparams)
3509
  except errors.HypervisorError, err:
3510
    _Fail(str(err), log=False)
3511

    
3512

    
3513
def _CheckOSPList(os_obj, parameters):
3514
  """Check whether a list of parameters is supported by the OS.
3515

3516
  @type os_obj: L{objects.OS}
3517
  @param os_obj: OS object to check
3518
  @type parameters: list
3519
  @param parameters: the list of parameters to check
3520

3521
  """
3522
  supported = [v[0] for v in os_obj.supported_parameters]
3523
  delta = frozenset(parameters).difference(supported)
3524
  if delta:
3525
    _Fail("The following parameters are not supported"
3526
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3527

    
3528

    
3529
def ValidateOS(required, osname, checks, osparams):
3530
  """Validate the given OS' parameters.
3531

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

3545
  """
3546
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3547
    _Fail("Unknown checks required for OS %s: %s", osname,
3548
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3549

    
3550
  name_only = objects.OS.GetName(osname)
3551
  status, tbv = _TryOSFromDisk(name_only, None)
3552

    
3553
  if not status:
3554
    if required:
3555
      _Fail(tbv)
3556
    else:
3557
      return False
3558

    
3559
  if max(tbv.api_versions) < constants.OS_API_V20:
3560
    return True
3561

    
3562
  if constants.OS_VALIDATE_PARAMETERS in checks:
3563
    _CheckOSPList(tbv, osparams.keys())
3564

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

    
3574
  return True
3575

    
3576

    
3577
def DemoteFromMC():
3578
  """Demotes the current node from master candidate role.
3579

3580
  """
3581
  # try to ensure we're not the master by mistake
3582
  master, myself = ssconf.GetMasterAndMyself()
3583
  if master == myself:
3584
    _Fail("ssconf status shows I'm the master node, will not demote")
3585

    
3586
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3587
  if not result.failed:
3588
    _Fail("The master daemon is running, will not demote")
3589

    
3590
  try:
3591
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3592
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3593
  except EnvironmentError, err:
3594
    if err.errno != errno.ENOENT:
3595
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3596

    
3597
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3598

    
3599

    
3600
def _GetX509Filenames(cryptodir, name):
3601
  """Returns the full paths for the private key and certificate.
3602

3603
  """
3604
  return (utils.PathJoin(cryptodir, name),
3605
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3606
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3607

    
3608

    
3609
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3610
  """Creates a new X509 certificate for SSL/TLS.
3611

3612
  @type validity: int
3613
  @param validity: Validity in seconds
3614
  @rtype: tuple; (string, string)
3615
  @return: Certificate name and public part
3616

3617
  """
3618
  (key_pem, cert_pem) = \
3619
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3620
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3621

    
3622
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3623
                              prefix="x509-%s-" % utils.TimestampForFilename())
3624
  try:
3625
    name = os.path.basename(cert_dir)
3626
    assert len(name) > 5
3627

    
3628
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3629

    
3630
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3631
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3632

    
3633
    # Never return private key as it shouldn't leave the node
3634
    return (name, cert_pem)
3635
  except Exception:
3636
    shutil.rmtree(cert_dir, ignore_errors=True)
3637
    raise
3638

    
3639

    
3640
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3641
  """Removes a X509 certificate.
3642

3643
  @type name: string
3644
  @param name: Certificate name
3645

3646
  """
3647
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3648

    
3649
  utils.RemoveFile(key_file)
3650
  utils.RemoveFile(cert_file)
3651

    
3652
  try:
3653
    os.rmdir(cert_dir)
3654
  except EnvironmentError, err:
3655
    _Fail("Cannot remove certificate directory '%s': %s",
3656
          cert_dir, err)
3657

    
3658

    
3659
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3660
  """Returns the command for the requested input/output.
3661

3662
  @type instance: L{objects.Instance}
3663
  @param instance: The instance object
3664
  @param mode: Import/export mode
3665
  @param ieio: Input/output type
3666
  @param ieargs: Input/output arguments
3667

3668
  """
3669
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3670

    
3671
  env = None
3672
  prefix = None
3673
  suffix = None
3674
  exp_size = None
3675

    
3676
  if ieio == constants.IEIO_FILE:
3677
    (filename, ) = ieargs
3678

    
3679
    if not utils.IsNormAbsPath(filename):
3680
      _Fail("Path '%s' is not normalized or absolute", filename)
3681

    
3682
    real_filename = os.path.realpath(filename)
3683
    directory = os.path.dirname(real_filename)
3684

    
3685
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3686
      _Fail("File '%s' is not under exports directory '%s': %s",
3687
            filename, pathutils.EXPORT_DIR, real_filename)
3688

    
3689
    # Create directory
3690
    utils.Makedirs(directory, mode=0750)
3691

    
3692
    quoted_filename = utils.ShellQuote(filename)
3693

    
3694
    if mode == constants.IEM_IMPORT:
3695
      suffix = "> %s" % quoted_filename
3696
    elif mode == constants.IEM_EXPORT:
3697
      suffix = "< %s" % quoted_filename
3698

    
3699
      # Retrieve file size
3700
      try:
3701
        st = os.stat(filename)
3702
      except EnvironmentError, err:
3703
        logging.error("Can't stat(2) %s: %s", filename, err)
3704
      else:
3705
        exp_size = utils.BytesToMebibyte(st.st_size)
3706

    
3707
  elif ieio == constants.IEIO_RAW_DISK:
3708
    (disk, ) = ieargs
3709

    
3710
    real_disk = _OpenRealBD(disk)
3711

    
3712
    if mode == constants.IEM_IMPORT:
3713
      # we use nocreat to fail if the device is not already there or we pass a
3714
      # wrong path; we use notrunc to no attempt truncate on an LV device
3715
      suffix = utils.BuildShellCmd("| dd of=%s conv=nocreat,notrunc bs=%s",
3716
                                   real_disk.dev_path,
3717
                                   str(1024 * 1024)) # 1 MB
3718

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

    
3727
  elif ieio == constants.IEIO_SCRIPT:
3728
    (disk, disk_index, ) = ieargs
3729

    
3730
    assert isinstance(disk_index, (int, long))
3731

    
3732
    inst_os = OSFromDisk(instance.os)
3733
    env = OSEnvironment(instance, inst_os)
3734

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

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

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

    
3749
    if mode == constants.IEM_IMPORT:
3750
      suffix = "| %s" % script_cmd
3751

    
3752
    elif mode == constants.IEM_EXPORT:
3753
      prefix = "%s |" % script_cmd
3754

    
3755
    # Let script predict size
3756
    exp_size = constants.IE_CUSTOM_SIZE
3757

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

    
3761
  return (env, prefix, suffix, exp_size)
3762

    
3763

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

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

    
3772

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

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

3792
  """
3793
  if mode == constants.IEM_IMPORT:
3794
    prefix = "import"
3795

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

    
3799
  elif mode == constants.IEM_EXPORT:
3800
    prefix = "export"
3801

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

    
3805
  else:
3806
    _Fail("Invalid mode %r", mode)
3807

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

    
3811
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3812
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3813

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

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

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

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

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

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

    
3851
    if host:
3852
      cmd.append("--host=%s" % host)
3853

    
3854
    if port:
3855
      cmd.append("--port=%s" % port)
3856

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

    
3862
    if opts.compress:
3863
      cmd.append("--compress=%s" % opts.compress)
3864

    
3865
    if opts.magic:
3866
      cmd.append("--magic=%s" % opts.magic)
3867

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

    
3871
    if cmd_prefix:
3872
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3873

    
3874
    if cmd_suffix:
3875
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3876

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

    
3886
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3887

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

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

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

    
3900

    
3901
def GetImportExportStatus(names):
3902
  """Returns import/export daemon status.
3903

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

3910
  """
3911
  result = []
3912

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

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

    
3924
    if not data:
3925
      result.append(None)
3926
      continue
3927

    
3928
    result.append(serializer.LoadJson(data))
3929

    
3930
  return result
3931

    
3932

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

3936
  """
3937
  logging.info("Abort import/export %s", name)
3938

    
3939
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3940
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3941

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

    
3947

    
3948
def CleanupImportExport(name):
3949
  """Cleanup after an import or export.
3950

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

3954
  """
3955
  logging.info("Finalizing import/export %s", name)
3956

    
3957
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3958

    
3959
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3960

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

    
3966
  shutil.rmtree(status_dir, ignore_errors=True)
3967

    
3968

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

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

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

3978
  """
3979
  bdevs = []
3980

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

    
3988

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

3992
  """
3993
  bdevs = _FindDisks(disks)
3994

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

    
4003

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

4007
  """
4008
  bdevs = _FindDisks(disks)
4009

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

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

    
4030
  def _Attach():
4031
    all_connected = True
4032

    
4033
    for rd in bdevs:
4034
      stats = rd.GetProcStatus()
4035

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

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

    
4060
    if not all_connected:
4061
      raise utils.RetryAgain()
4062

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

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

    
4077

    
4078
def DrbdWaitSync(disks):
4079
  """Wait until DRBDs have synchronized.
4080

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

    
4088
  bdevs = _FindDisks(disks)
4089

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

    
4105
  return (alldone, min_resync)
4106

    
4107

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

4111
  """
4112
  faulty_disks = []
4113

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

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

    
4124
  return [disk.uuid for disk in faulty_disks]
4125

    
4126

    
4127
def GetDrbdUsermodeHelper():
4128
  """Returns DRBD usermode helper currently configured.
4129

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

    
4136

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

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

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

    
4160

    
4161
def _VerifyRestrictedCmdName(cmd):
4162
  """Verifies a restricted command name.
4163

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

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

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

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

    
4180
  return (True, None)
4181

    
4182

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

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

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

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

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

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

    
4210
  return (True, st)
4211

    
4212

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

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

4222
  """
4223
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
4224

    
4225
  if not status:
4226
    return (False, value)
4227

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

    
4231
  return (True, None)
4232

    
4233

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

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

4246
  """
4247
  executable = utils.PathJoin(path, cmd)
4248

    
4249
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
4250

    
4251
  if not status:
4252
    return (False, msg)
4253

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

    
4257
  return (True, executable)
4258

    
4259

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

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

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

    
4279
  if not status:
4280
    return (False, msg)
4281

    
4282
  # Check actual executable
4283
  return _verify_cmd(path, cmd)
4284

    
4285

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

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

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

    
4305
  if not _enabled:
4306
    _Fail("Restricted commands disabled at configure time")
4307

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

    
4315
      (status, value) = _prepare_fn(_path, cmd)
4316

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

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

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

    
4344

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

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

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

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

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

    
4363

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

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

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

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

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

    
4390

    
4391
class HooksRunner(object):
4392
  """Hook runner.
4393

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

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

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

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

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

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

    
4421
    results = self.RunHooks(hpath, phase, env)
4422

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

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

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

4444
    @raise errors.ProgrammerError: for invalid input
4445
        parameters
4446

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

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

    
4458
    results = []
4459

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

    
4465
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
4466

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

    
4482
    return results
4483

    
4484

    
4485
class IAllocatorRunner(object):
4486
  """IAllocator runner.
4487

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

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

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

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

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

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

    
4523
    return result.stdout
4524

    
4525

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

4529
  """
4530
  _DEV_PREFIX = "/dev/"
4531
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4532

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

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

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

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

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

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

4567
    @rtype: None
4568

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

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

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

4593
    @type dev_path: str
4594
    @param dev_path: the pathname of the device
4595

4596
    @rtype: None
4597

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