Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 24711492

History | View | Annotate | Download (140.8 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):
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
  @rtype: dict
961
  @return: a dictionary with the same keys as the input dict, and
962
      values representing the result of the checks
963

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

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

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

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

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

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

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

    
999
    result[constants.NV_NODELIST] = val
1000

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1151
  return result
1152

    
1153

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

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

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

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

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

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

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

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

    
1191

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

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

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

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

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

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

    
1235
  return lvs
1236

    
1237

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

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

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

    
1248

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

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

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

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

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

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

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

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

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

    
1294

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

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

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

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

    
1310

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

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

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

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

    
1339

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

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

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

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

    
1366

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

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

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

1384
  """
1385
  output = {}
1386

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

    
1395
  return output
1396

    
1397

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

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

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

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

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

    
1421

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

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

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

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

1441
  """
1442
  output = {}
1443

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

    
1465
  return output
1466

    
1467

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

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

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

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

    
1495

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

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

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

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

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

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

    
1527

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

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

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

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

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

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

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

    
1560

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

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

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

    
1572

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

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

1579

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

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

    
1598
  return link_name
1599

    
1600

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

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

    
1613

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

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

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

    
1635

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

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

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

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

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

    
1664
  return block_devices
1665

    
1666

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

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

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

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

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

    
1700

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

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

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

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

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

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

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

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

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

    
1745
      self.tried_once = True
1746

    
1747
      raise utils.RetryAgain()
1748

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

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

    
1763
    time.sleep(1)
1764

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

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

    
1773
  _RemoveBlockDevLinks(iname, instance.disks)
1774

    
1775

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

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

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

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

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

    
1822

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

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

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

    
1843

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

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

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

    
1858

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

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

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

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

    
1887

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

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

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

    
1905

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

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

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

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

    
1928

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

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

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

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

    
1949

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

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

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

    
1968

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

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

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

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

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

    
2005

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

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

    
2016

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

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

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

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

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

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

    
2077
  device.SetInfo(info)
2078

    
2079
  return device.unique_id
2080

    
2081

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

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

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

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

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

    
2104

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

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

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

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

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

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

    
2136

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

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

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

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

    
2158
    result = rdev.PauseResumeSync(pause)
2159

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

    
2169
  return success
2170

    
2171

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

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

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

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

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

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

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

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

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

    
2217

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

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

2223
  @note: this function is called recursively.
2224

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

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

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

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

    
2266
  else:
2267
    result = True
2268
  return result
2269

    
2270

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

2274
  This is a wrapper over _RecursiveAssembleBD.
2275

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

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

    
2298
  return dev_path, link_name
2299

    
2300

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

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

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

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

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

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

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

    
2338

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

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

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

    
2357

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

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

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

    
2386

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

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

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

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

    
2406
  return stats
2407

    
2408

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

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

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

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

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

    
2437
  return result
2438

    
2439

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

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

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

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

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

    
2457
  return bdev.FindDevice(disk, children)
2458

    
2459

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

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

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

    
2471
  real_disk.Open()
2472

    
2473
  return real_disk
2474

    
2475

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

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

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

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

    
2493
  if rbd is None:
2494
    return None
2495

    
2496
  return rbd.GetSyncStatus()
2497

    
2498

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

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

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

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

    
2525

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

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

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

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

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

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

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

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

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

    
2569

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

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

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

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

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

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

    
2602
  raw_data = _Decompress(data)
2603

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

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

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

    
2615

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

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

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

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

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

    
2634
  return result.stdout
2635

    
2636

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

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

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

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

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

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

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

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

    
2674
  return True, api_versions
2675

    
2676

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

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

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

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

    
2722
  return result
2723

    
2724

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2824

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

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

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

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

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

    
2846
  if not status:
2847
    _Fail(payload)
2848

    
2849
  return payload
2850

    
2851

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

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

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

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

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

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

    
2894
  return result
2895

    
2896

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

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

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

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

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

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

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

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

    
2965
  return result
2966

    
2967

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

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

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

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

    
3010
  return result
3011

    
3012

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

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

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

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

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

    
3045

    
3046
def BlockdevSnapshot(disk):
3047
  """Create a snapshot copy of a block device.
3048

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

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

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

    
3075

    
3076
def BlockdevSetInfo(disk, info):
3077
  """Sets 'metadata' information on block devices.
3078

3079
  This function sets 'info' metadata on block devices. Initial
3080
  information is set at device creation; this function should be used
3081
  for example after renames.
3082

3083
  @type disk: L{objects.Disk}
3084
  @param disk: the disk to be grown
3085
  @type info: string
3086
  @param info: new 'info' metadata
3087
  @rtype: (status, result)
3088
  @return: a tuple with the status of the operation (True/False), and
3089
      the errors message if status is False
3090

3091
  """
3092
  r_dev = _RecursiveFindBD(disk)
3093
  if r_dev is None:
3094
    _Fail("Cannot find block device %s", disk)
3095

    
3096
  try:
3097
    r_dev.SetInfo(info)
3098
  except errors.BlockDeviceError, err:
3099
    _Fail("Failed to set information on block device: %s", err, exc=True)
3100

    
3101

    
3102
def FinalizeExport(instance, snap_disks):
3103
  """Write out the export configuration information.
3104

3105
  @type instance: L{objects.Instance}
3106
  @param instance: the instance which we export, used for
3107
      saving configuration
3108
  @type snap_disks: list of L{objects.Disk}
3109
  @param snap_disks: list of snapshot block devices, which
3110
      will be used to get the actual name of the dump file
3111

3112
  @rtype: None
3113

3114
  """
3115
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
3116
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
3117

    
3118
  config = objects.SerializableConfigParser()
3119

    
3120
  config.add_section(constants.INISECT_EXP)
3121
  config.set(constants.INISECT_EXP, "version", "0")
3122
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
3123
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
3124
  config.set(constants.INISECT_EXP, "os", instance.os)
3125
  config.set(constants.INISECT_EXP, "compression", "none")
3126

    
3127
  config.add_section(constants.INISECT_INS)
3128
  config.set(constants.INISECT_INS, "name", instance.name)
3129
  config.set(constants.INISECT_INS, "maxmem", "%d" %
3130
             instance.beparams[constants.BE_MAXMEM])
3131
  config.set(constants.INISECT_INS, "minmem", "%d" %
3132
             instance.beparams[constants.BE_MINMEM])
3133
  # "memory" is deprecated, but useful for exporting to old ganeti versions
3134
  config.set(constants.INISECT_INS, "memory", "%d" %
3135
             instance.beparams[constants.BE_MAXMEM])
3136
  config.set(constants.INISECT_INS, "vcpus", "%d" %
3137
             instance.beparams[constants.BE_VCPUS])
3138
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
3139
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
3140
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
3141

    
3142
  nic_total = 0
3143
  for nic_count, nic in enumerate(instance.nics):
3144
    nic_total += 1
3145
    config.set(constants.INISECT_INS, "nic%d_mac" %
3146
               nic_count, "%s" % nic.mac)
3147
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
3148
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
3149
               "%s" % nic.network)
3150
    for param in constants.NICS_PARAMETER_TYPES:
3151
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
3152
                 "%s" % nic.nicparams.get(param, None))
3153
  # TODO: redundant: on load can read nics until it doesn't exist
3154
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
3155

    
3156
  disk_total = 0
3157
  for disk_count, disk in enumerate(snap_disks):
3158
    if disk:
3159
      disk_total += 1
3160
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
3161
                 ("%s" % disk.iv_name))
3162
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
3163
                 ("%s" % disk.logical_id[1]))
3164
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
3165
                 ("%d" % disk.size))
3166

    
3167
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
3168

    
3169
  # New-style hypervisor/backend parameters
3170

    
3171
  config.add_section(constants.INISECT_HYP)
3172
  for name, value in instance.hvparams.items():
3173
    if name not in constants.HVC_GLOBALS:
3174
      config.set(constants.INISECT_HYP, name, str(value))
3175

    
3176
  config.add_section(constants.INISECT_BEP)
3177
  for name, value in instance.beparams.items():
3178
    config.set(constants.INISECT_BEP, name, str(value))
3179

    
3180
  config.add_section(constants.INISECT_OSP)
3181
  for name, value in instance.osparams.items():
3182
    config.set(constants.INISECT_OSP, name, str(value))
3183

    
3184
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
3185
                  data=config.Dumps())
3186
  shutil.rmtree(finaldestdir, ignore_errors=True)
3187
  shutil.move(destdir, finaldestdir)
3188

    
3189

    
3190
def ExportInfo(dest):
3191
  """Get export configuration information.
3192

3193
  @type dest: str
3194
  @param dest: directory containing the export
3195

3196
  @rtype: L{objects.SerializableConfigParser}
3197
  @return: a serializable config file containing the
3198
      export info
3199

3200
  """
3201
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
3202

    
3203
  config = objects.SerializableConfigParser()
3204
  config.read(cff)
3205

    
3206
  if (not config.has_section(constants.INISECT_EXP) or
3207
      not config.has_section(constants.INISECT_INS)):
3208
    _Fail("Export info file doesn't have the required fields")
3209

    
3210
  return config.Dumps()
3211

    
3212

    
3213
def ListExports():
3214
  """Return a list of exports currently available on this machine.
3215

3216
  @rtype: list
3217
  @return: list of the exports
3218

3219
  """
3220
  if os.path.isdir(pathutils.EXPORT_DIR):
3221
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
3222
  else:
3223
    _Fail("No exports directory")
3224

    
3225

    
3226
def RemoveExport(export):
3227
  """Remove an existing export from the node.
3228

3229
  @type export: str
3230
  @param export: the name of the export to remove
3231
  @rtype: None
3232

3233
  """
3234
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
3235

    
3236
  try:
3237
    shutil.rmtree(target)
3238
  except EnvironmentError, err:
3239
    _Fail("Error while removing the export: %s", err, exc=True)
3240

    
3241

    
3242
def BlockdevRename(devlist):
3243
  """Rename a list of block devices.
3244

3245
  @type devlist: list of tuples
3246
  @param devlist: list of tuples of the form  (disk, new_unique_id); disk is
3247
      an L{objects.Disk} object describing the current disk, and new
3248
      unique_id is the name we rename it to
3249
  @rtype: boolean
3250
  @return: True if all renames succeeded, False otherwise
3251

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

    
3280

    
3281
def _TransformFileStorageDir(fs_dir):
3282
  """Checks whether given file_storage_dir is valid.
3283

3284
  Checks wheter the given fs_dir is within the cluster-wide default
3285
  file_storage_dir or the shared_file_storage_dir, which are stored in
3286
  SimpleStore. Only paths under those directories are allowed.
3287

3288
  @type fs_dir: str
3289
  @param fs_dir: the path to check
3290

3291
  @return: the normalized path if valid, None otherwise
3292

3293
  """
3294
  filestorage.CheckFileStoragePath(fs_dir)
3295

    
3296
  return os.path.normpath(fs_dir)
3297

    
3298

    
3299
def CreateFileStorageDir(file_storage_dir):
3300
  """Create file storage directory.
3301

3302
  @type file_storage_dir: str
3303
  @param file_storage_dir: directory to create
3304

3305
  @rtype: tuple
3306
  @return: tuple with first element a boolean indicating wheter dir
3307
      creation was successful or not
3308

3309
  """
3310
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3311
  if os.path.exists(file_storage_dir):
3312
    if not os.path.isdir(file_storage_dir):
3313
      _Fail("Specified storage dir '%s' is not a directory",
3314
            file_storage_dir)
3315
  else:
3316
    try:
3317
      os.makedirs(file_storage_dir, 0750)
3318
    except OSError, err:
3319
      _Fail("Cannot create file storage directory '%s': %s",
3320
            file_storage_dir, err, exc=True)
3321

    
3322

    
3323
def RemoveFileStorageDir(file_storage_dir):
3324
  """Remove file storage directory.
3325

3326
  Remove it only if it's empty. If not log an error and return.
3327

3328
  @type file_storage_dir: str
3329
  @param file_storage_dir: the directory we should cleanup
3330
  @rtype: tuple (success,)
3331
  @return: tuple of one element, C{success}, denoting
3332
      whether the operation was successful
3333

3334
  """
3335
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3336
  if os.path.exists(file_storage_dir):
3337
    if not os.path.isdir(file_storage_dir):
3338
      _Fail("Specified Storage directory '%s' is not a directory",
3339
            file_storage_dir)
3340
    # deletes dir only if empty, otherwise we want to fail the rpc call
3341
    try:
3342
      os.rmdir(file_storage_dir)
3343
    except OSError, err:
3344
      _Fail("Cannot remove file storage directory '%s': %s",
3345
            file_storage_dir, err)
3346

    
3347

    
3348
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
3349
  """Rename the file storage directory.
3350

3351
  @type old_file_storage_dir: str
3352
  @param old_file_storage_dir: the current path
3353
  @type new_file_storage_dir: str
3354
  @param new_file_storage_dir: the name we should rename to
3355
  @rtype: tuple (success,)
3356
  @return: tuple of one element, C{success}, denoting
3357
      whether the operation was successful
3358

3359
  """
3360
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
3361
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
3362
  if not os.path.exists(new_file_storage_dir):
3363
    if os.path.isdir(old_file_storage_dir):
3364
      try:
3365
        os.rename(old_file_storage_dir, new_file_storage_dir)
3366
      except OSError, err:
3367
        _Fail("Cannot rename '%s' to '%s': %s",
3368
              old_file_storage_dir, new_file_storage_dir, err)
3369
    else:
3370
      _Fail("Specified storage dir '%s' is not a directory",
3371
            old_file_storage_dir)
3372
  else:
3373
    if os.path.exists(old_file_storage_dir):
3374
      _Fail("Cannot rename '%s' to '%s': both locations exist",
3375
            old_file_storage_dir, new_file_storage_dir)
3376

    
3377

    
3378
def _EnsureJobQueueFile(file_name):
3379
  """Checks whether the given filename is in the queue directory.
3380

3381
  @type file_name: str
3382
  @param file_name: the file name we should check
3383
  @rtype: None
3384
  @raises RPCFail: if the file is not valid
3385

3386
  """
3387
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
3388
    _Fail("Passed job queue file '%s' does not belong to"
3389
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
3390

    
3391

    
3392
def JobQueueUpdate(file_name, content):
3393
  """Updates a file in the queue directory.
3394

3395
  This is just a wrapper over L{utils.io.WriteFile}, with proper
3396
  checking.
3397

3398
  @type file_name: str
3399
  @param file_name: the job file name
3400
  @type content: str
3401
  @param content: the new job contents
3402
  @rtype: boolean
3403
  @return: the success of the operation
3404

3405
  """
3406
  file_name = vcluster.LocalizeVirtualPath(file_name)
3407

    
3408
  _EnsureJobQueueFile(file_name)
3409
  getents = runtime.GetEnts()
3410

    
3411
  # Write and replace the file atomically
3412
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3413
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3414

    
3415

    
3416
def JobQueueRename(old, new):
3417
  """Renames a job queue file.
3418

3419
  This is just a wrapper over os.rename with proper checking.
3420

3421
  @type old: str
3422
  @param old: the old (actual) file name
3423
  @type new: str
3424
  @param new: the desired file name
3425
  @rtype: tuple
3426
  @return: the success of the operation and payload
3427

3428
  """
3429
  old = vcluster.LocalizeVirtualPath(old)
3430
  new = vcluster.LocalizeVirtualPath(new)
3431

    
3432
  _EnsureJobQueueFile(old)
3433
  _EnsureJobQueueFile(new)
3434

    
3435
  getents = runtime.GetEnts()
3436

    
3437
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3438
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3439

    
3440

    
3441
def BlockdevClose(instance_name, disks):
3442
  """Closes the given block devices.
3443

3444
  This means they will be switched to secondary mode (in case of
3445
  DRBD).
3446

3447
  @param instance_name: if the argument is not empty, the symlinks
3448
      of this instance will be removed
3449
  @type disks: list of L{objects.Disk}
3450
  @param disks: the list of disks to be closed
3451
  @rtype: tuple (success, message)
3452
  @return: a tuple of success and message, where success
3453
      indicates the succes of the operation, and message
3454
      which will contain the error details in case we
3455
      failed
3456

3457
  """
3458
  bdevs = []
3459
  for cf in disks:
3460
    rd = _RecursiveFindBD(cf)
3461
    if rd is None:
3462
      _Fail("Can't find device %s", cf)
3463
    bdevs.append(rd)
3464

    
3465
  msg = []
3466
  for rd in bdevs:
3467
    try:
3468
      rd.Close()
3469
    except errors.BlockDeviceError, err:
3470
      msg.append(str(err))
3471
  if msg:
3472
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3473
  else:
3474
    if instance_name:
3475
      _RemoveBlockDevLinks(instance_name, disks)
3476

    
3477

    
3478
def ValidateHVParams(hvname, hvparams):
3479
  """Validates the given hypervisor parameters.
3480

3481
  @type hvname: string
3482
  @param hvname: the hypervisor name
3483
  @type hvparams: dict
3484
  @param hvparams: the hypervisor parameters to be validated
3485
  @rtype: None
3486

3487
  """
3488
  try:
3489
    hv_type = hypervisor.GetHypervisor(hvname)
3490
    hv_type.ValidateParameters(hvparams)
3491
  except errors.HypervisorError, err:
3492
    _Fail(str(err), log=False)
3493

    
3494

    
3495
def _CheckOSPList(os_obj, parameters):
3496
  """Check whether a list of parameters is supported by the OS.
3497

3498
  @type os_obj: L{objects.OS}
3499
  @param os_obj: OS object to check
3500
  @type parameters: list
3501
  @param parameters: the list of parameters to check
3502

3503
  """
3504
  supported = [v[0] for v in os_obj.supported_parameters]
3505
  delta = frozenset(parameters).difference(supported)
3506
  if delta:
3507
    _Fail("The following parameters are not supported"
3508
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3509

    
3510

    
3511
def ValidateOS(required, osname, checks, osparams):
3512
  """Validate the given OS' parameters.
3513

3514
  @type required: boolean
3515
  @param required: whether absence of the OS should translate into
3516
      failure or not
3517
  @type osname: string
3518
  @param osname: the OS to be validated
3519
  @type checks: list
3520
  @param checks: list of the checks to run (currently only 'parameters')
3521
  @type osparams: dict
3522
  @param osparams: dictionary with OS parameters
3523
  @rtype: boolean
3524
  @return: True if the validation passed, or False if the OS was not
3525
      found and L{required} was false
3526

3527
  """
3528
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3529
    _Fail("Unknown checks required for OS %s: %s", osname,
3530
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3531

    
3532
  name_only = objects.OS.GetName(osname)
3533
  status, tbv = _TryOSFromDisk(name_only, None)
3534

    
3535
  if not status:
3536
    if required:
3537
      _Fail(tbv)
3538
    else:
3539
      return False
3540

    
3541
  if max(tbv.api_versions) < constants.OS_API_V20:
3542
    return True
3543

    
3544
  if constants.OS_VALIDATE_PARAMETERS in checks:
3545
    _CheckOSPList(tbv, osparams.keys())
3546

    
3547
  validate_env = OSCoreEnv(osname, tbv, osparams)
3548
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3549
                        cwd=tbv.path, reset_env=True)
3550
  if result.failed:
3551
    logging.error("os validate command '%s' returned error: %s output: %s",
3552
                  result.cmd, result.fail_reason, result.output)
3553
    _Fail("OS validation script failed (%s), output: %s",
3554
          result.fail_reason, result.output, log=False)
3555

    
3556
  return True
3557

    
3558

    
3559
def DemoteFromMC():
3560
  """Demotes the current node from master candidate role.
3561

3562
  """
3563
  # try to ensure we're not the master by mistake
3564
  master, myself = ssconf.GetMasterAndMyself()
3565
  if master == myself:
3566
    _Fail("ssconf status shows I'm the master node, will not demote")
3567

    
3568
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3569
  if not result.failed:
3570
    _Fail("The master daemon is running, will not demote")
3571

    
3572
  try:
3573
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3574
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3575
  except EnvironmentError, err:
3576
    if err.errno != errno.ENOENT:
3577
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3578

    
3579
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3580

    
3581

    
3582
def _GetX509Filenames(cryptodir, name):
3583
  """Returns the full paths for the private key and certificate.
3584

3585
  """
3586
  return (utils.PathJoin(cryptodir, name),
3587
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3588
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3589

    
3590

    
3591
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3592
  """Creates a new X509 certificate for SSL/TLS.
3593

3594
  @type validity: int
3595
  @param validity: Validity in seconds
3596
  @rtype: tuple; (string, string)
3597
  @return: Certificate name and public part
3598

3599
  """
3600
  (key_pem, cert_pem) = \
3601
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3602
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3603

    
3604
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3605
                              prefix="x509-%s-" % utils.TimestampForFilename())
3606
  try:
3607
    name = os.path.basename(cert_dir)
3608
    assert len(name) > 5
3609

    
3610
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3611

    
3612
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3613
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3614

    
3615
    # Never return private key as it shouldn't leave the node
3616
    return (name, cert_pem)
3617
  except Exception:
3618
    shutil.rmtree(cert_dir, ignore_errors=True)
3619
    raise
3620

    
3621

    
3622
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3623
  """Removes a X509 certificate.
3624

3625
  @type name: string
3626
  @param name: Certificate name
3627

3628
  """
3629
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3630

    
3631
  utils.RemoveFile(key_file)
3632
  utils.RemoveFile(cert_file)
3633

    
3634
  try:
3635
    os.rmdir(cert_dir)
3636
  except EnvironmentError, err:
3637
    _Fail("Cannot remove certificate directory '%s': %s",
3638
          cert_dir, err)
3639

    
3640

    
3641
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3642
  """Returns the command for the requested input/output.
3643

3644
  @type instance: L{objects.Instance}
3645
  @param instance: The instance object
3646
  @param mode: Import/export mode
3647
  @param ieio: Input/output type
3648
  @param ieargs: Input/output arguments
3649

3650
  """
3651
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3652

    
3653
  env = None
3654
  prefix = None
3655
  suffix = None
3656
  exp_size = None
3657

    
3658
  if ieio == constants.IEIO_FILE:
3659
    (filename, ) = ieargs
3660

    
3661
    if not utils.IsNormAbsPath(filename):
3662
      _Fail("Path '%s' is not normalized or absolute", filename)
3663

    
3664
    real_filename = os.path.realpath(filename)
3665
    directory = os.path.dirname(real_filename)
3666

    
3667
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3668
      _Fail("File '%s' is not under exports directory '%s': %s",
3669
            filename, pathutils.EXPORT_DIR, real_filename)
3670

    
3671
    # Create directory
3672
    utils.Makedirs(directory, mode=0750)
3673

    
3674
    quoted_filename = utils.ShellQuote(filename)
3675

    
3676
    if mode == constants.IEM_IMPORT:
3677
      suffix = "> %s" % quoted_filename
3678
    elif mode == constants.IEM_EXPORT:
3679
      suffix = "< %s" % quoted_filename
3680

    
3681
      # Retrieve file size
3682
      try:
3683
        st = os.stat(filename)
3684
      except EnvironmentError, err:
3685
        logging.error("Can't stat(2) %s: %s", filename, err)
3686
      else:
3687
        exp_size = utils.BytesToMebibyte(st.st_size)
3688

    
3689
  elif ieio == constants.IEIO_RAW_DISK:
3690
    (disk, ) = ieargs
3691

    
3692
    real_disk = _OpenRealBD(disk)
3693

    
3694
    if mode == constants.IEM_IMPORT:
3695
      # we set here a smaller block size as, due to transport buffering, more
3696
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3697
      # is not already there or we pass a wrong path; we use notrunc to no
3698
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3699
      # much memory; this means that at best, we flush every 64k, which will
3700
      # not be very fast
3701
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3702
                                    " bs=%s oflag=dsync"),
3703
                                    real_disk.dev_path,
3704
                                    str(64 * 1024))
3705

    
3706
    elif mode == constants.IEM_EXPORT:
3707
      # the block size on the read dd is 1MiB to match our units
3708
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3709
                                   real_disk.dev_path,
3710
                                   str(1024 * 1024), # 1 MB
3711
                                   str(disk.size))
3712
      exp_size = disk.size
3713

    
3714
  elif ieio == constants.IEIO_SCRIPT:
3715
    (disk, disk_index, ) = ieargs
3716

    
3717
    assert isinstance(disk_index, (int, long))
3718

    
3719
    inst_os = OSFromDisk(instance.os)
3720
    env = OSEnvironment(instance, inst_os)
3721

    
3722
    if mode == constants.IEM_IMPORT:
3723
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3724
      env["IMPORT_INDEX"] = str(disk_index)
3725
      script = inst_os.import_script
3726

    
3727
    elif mode == constants.IEM_EXPORT:
3728
      real_disk = _OpenRealBD(disk)
3729
      env["EXPORT_DEVICE"] = real_disk.dev_path
3730
      env["EXPORT_INDEX"] = str(disk_index)
3731
      script = inst_os.export_script
3732

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

    
3736
    if mode == constants.IEM_IMPORT:
3737
      suffix = "| %s" % script_cmd
3738

    
3739
    elif mode == constants.IEM_EXPORT:
3740
      prefix = "%s |" % script_cmd
3741

    
3742
    # Let script predict size
3743
    exp_size = constants.IE_CUSTOM_SIZE
3744

    
3745
  else:
3746
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3747

    
3748
  return (env, prefix, suffix, exp_size)
3749

    
3750

    
3751
def _CreateImportExportStatusDir(prefix):
3752
  """Creates status directory for import/export.
3753

3754
  """
3755
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3756
                          prefix=("%s-%s-" %
3757
                                  (prefix, utils.TimestampForFilename())))
3758

    
3759

    
3760
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3761
                            ieio, ieioargs):
3762
  """Starts an import or export daemon.
3763

3764
  @param mode: Import/output mode
3765
  @type opts: L{objects.ImportExportOptions}
3766
  @param opts: Daemon options
3767
  @type host: string
3768
  @param host: Remote host for export (None for import)
3769
  @type port: int
3770
  @param port: Remote port for export (None for import)
3771
  @type instance: L{objects.Instance}
3772
  @param instance: Instance object
3773
  @type component: string
3774
  @param component: which part of the instance is transferred now,
3775
      e.g. 'disk/0'
3776
  @param ieio: Input/output type
3777
  @param ieioargs: Input/output arguments
3778

3779
  """
3780
  if mode == constants.IEM_IMPORT:
3781
    prefix = "import"
3782

    
3783
    if not (host is None and port is None):
3784
      _Fail("Can not specify host or port on import")
3785

    
3786
  elif mode == constants.IEM_EXPORT:
3787
    prefix = "export"
3788

    
3789
    if host is None or port is None:
3790
      _Fail("Host and port must be specified for an export")
3791

    
3792
  else:
3793
    _Fail("Invalid mode %r", mode)
3794

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

    
3798
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3799
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3800

    
3801
  if opts.key_name is None:
3802
    # Use server.pem
3803
    key_path = pathutils.NODED_CERT_FILE
3804
    cert_path = pathutils.NODED_CERT_FILE
3805
    assert opts.ca_pem is None
3806
  else:
3807
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3808
                                                 opts.key_name)
3809
    assert opts.ca_pem is not None
3810

    
3811
  for i in [key_path, cert_path]:
3812
    if not os.path.exists(i):
3813
      _Fail("File '%s' does not exist" % i)
3814

    
3815
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3816
  try:
3817
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3818
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3819
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3820

    
3821
    if opts.ca_pem is None:
3822
      # Use server.pem
3823
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3824
    else:
3825
      ca = opts.ca_pem
3826

    
3827
    # Write CA file
3828
    utils.WriteFile(ca_file, data=ca, mode=0400)
3829

    
3830
    cmd = [
3831
      pathutils.IMPORT_EXPORT_DAEMON,
3832
      status_file, mode,
3833
      "--key=%s" % key_path,
3834
      "--cert=%s" % cert_path,
3835
      "--ca=%s" % ca_file,
3836
      ]
3837

    
3838
    if host:
3839
      cmd.append("--host=%s" % host)
3840

    
3841
    if port:
3842
      cmd.append("--port=%s" % port)
3843

    
3844
    if opts.ipv6:
3845
      cmd.append("--ipv6")
3846
    else:
3847
      cmd.append("--ipv4")
3848

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

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

    
3855
    if exp_size is not None:
3856
      cmd.append("--expected-size=%s" % exp_size)
3857

    
3858
    if cmd_prefix:
3859
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3860

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

    
3864
    if mode == constants.IEM_EXPORT:
3865
      # Retry connection a few times when connecting to remote peer
3866
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3867
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3868
    elif opts.connect_timeout is not None:
3869
      assert mode == constants.IEM_IMPORT
3870
      # Overall timeout for establishing connection while listening
3871
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3872

    
3873
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3874

    
3875
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3876
    # support for receiving a file descriptor for output
3877
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3878
                      output=logfile)
3879

    
3880
    # The import/export name is simply the status directory name
3881
    return os.path.basename(status_dir)
3882

    
3883
  except Exception:
3884
    shutil.rmtree(status_dir, ignore_errors=True)
3885
    raise
3886

    
3887

    
3888
def GetImportExportStatus(names):
3889
  """Returns import/export daemon status.
3890

3891
  @type names: sequence
3892
  @param names: List of names
3893
  @rtype: List of dicts
3894
  @return: Returns a list of the state of each named import/export or None if a
3895
           status couldn't be read
3896

3897
  """
3898
  result = []
3899

    
3900
  for name in names:
3901
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3902
                                 _IES_STATUS_FILE)
3903

    
3904
    try:
3905
      data = utils.ReadFile(status_file)
3906
    except EnvironmentError, err:
3907
      if err.errno != errno.ENOENT:
3908
        raise
3909
      data = None
3910

    
3911
    if not data:
3912
      result.append(None)
3913
      continue
3914

    
3915
    result.append(serializer.LoadJson(data))
3916

    
3917
  return result
3918

    
3919

    
3920
def AbortImportExport(name):
3921
  """Sends SIGTERM to a running import/export daemon.
3922

3923
  """
3924
  logging.info("Abort import/export %s", name)
3925

    
3926
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3927
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3928

    
3929
  if pid:
3930
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3931
                 name, pid)
3932
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3933

    
3934

    
3935
def CleanupImportExport(name):
3936
  """Cleanup after an import or export.
3937

3938
  If the import/export daemon is still running it's killed. Afterwards the
3939
  whole status directory is removed.
3940

3941
  """
3942
  logging.info("Finalizing import/export %s", name)
3943

    
3944
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3945

    
3946
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3947

    
3948
  if pid:
3949
    logging.info("Import/export %s is still running with PID %s",
3950
                 name, pid)
3951
    utils.KillProcess(pid, waitpid=False)
3952

    
3953
  shutil.rmtree(status_dir, ignore_errors=True)
3954

    
3955

    
3956
def _FindDisks(disks):
3957
  """Finds attached L{BlockDev}s for the given disks.
3958

3959
  @type disks: list of L{objects.Disk}
3960
  @param disks: the disk objects we need to find
3961

3962
  @return: list of L{BlockDev} objects or C{None} if a given disk
3963
           was not found or was no attached.
3964

3965
  """
3966
  bdevs = []
3967

    
3968
  for disk in disks:
3969
    rd = _RecursiveFindBD(disk)
3970
    if rd is None:
3971
      _Fail("Can't find device %s", disk)
3972
    bdevs.append(rd)
3973
  return bdevs
3974

    
3975

    
3976
def DrbdDisconnectNet(disks):
3977
  """Disconnects the network on a list of drbd devices.
3978

3979
  """
3980
  bdevs = _FindDisks(disks)
3981

    
3982
  # disconnect disks
3983
  for rd in bdevs:
3984
    try:
3985
      rd.DisconnectNet()
3986
    except errors.BlockDeviceError, err:
3987
      _Fail("Can't change network configuration to standalone mode: %s",
3988
            err, exc=True)
3989

    
3990

    
3991
def DrbdAttachNet(disks, instance_name, multimaster):
3992
  """Attaches the network on a list of drbd devices.
3993

3994
  """
3995
  bdevs = _FindDisks(disks)
3996

    
3997
  if multimaster:
3998
    for idx, rd in enumerate(bdevs):
3999
      try:
4000
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
4001
      except EnvironmentError, err:
4002
        _Fail("Can't create symlink: %s", err)
4003
  # reconnect disks, switch to new master configuration and if
4004
  # needed primary mode
4005
  for rd in bdevs:
4006
    try:
4007
      rd.AttachNet(multimaster)
4008
    except errors.BlockDeviceError, err:
4009
      _Fail("Can't change network configuration: %s", err)
4010

    
4011
  # wait until the disks are connected; we need to retry the re-attach
4012
  # if the device becomes standalone, as this might happen if the one
4013
  # node disconnects and reconnects in a different mode before the
4014
  # other node reconnects; in this case, one or both of the nodes will
4015
  # decide it has wrong configuration and switch to standalone
4016

    
4017
  def _Attach():
4018
    all_connected = True
4019

    
4020
    for rd in bdevs:
4021
      stats = rd.GetProcStatus()
4022

    
4023
      all_connected = (all_connected and
4024
                       (stats.is_connected or stats.is_in_resync))
4025

    
4026
      if stats.is_standalone:
4027
        # peer had different config info and this node became
4028
        # standalone, even though this should not happen with the
4029
        # new staged way of changing disk configs
4030
        try:
4031
          rd.AttachNet(multimaster)
4032
        except errors.BlockDeviceError, err:
4033
          _Fail("Can't change network configuration: %s", err)
4034

    
4035
    if not all_connected:
4036
      raise utils.RetryAgain()
4037

    
4038
  try:
4039
    # Start with a delay of 100 miliseconds and go up to 5 seconds
4040
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
4041
  except utils.RetryTimeout:
4042
    _Fail("Timeout in disk reconnecting")
4043

    
4044
  if multimaster:
4045
    # change to primary mode
4046
    for rd in bdevs:
4047
      try:
4048
        rd.Open()
4049
      except errors.BlockDeviceError, err:
4050
        _Fail("Can't change to primary mode: %s", err)
4051

    
4052

    
4053
def DrbdWaitSync(disks):
4054
  """Wait until DRBDs have synchronized.
4055

4056
  """
4057
  def _helper(rd):
4058
    stats = rd.GetProcStatus()
4059
    if not (stats.is_connected or stats.is_in_resync):
4060
      raise utils.RetryAgain()
4061
    return stats
4062

    
4063
  bdevs = _FindDisks(disks)
4064

    
4065
  min_resync = 100
4066
  alldone = True
4067
  for rd in bdevs:
4068
    try:
4069
      # poll each second for 15 seconds
4070
      stats = utils.Retry(_helper, 1, 15, args=[rd])
4071
    except utils.RetryTimeout:
4072
      stats = rd.GetProcStatus()
4073
      # last check
4074
      if not (stats.is_connected or stats.is_in_resync):
4075
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
4076
    alldone = alldone and (not stats.is_in_resync)
4077
    if stats.sync_percent is not None:
4078
      min_resync = min(min_resync, stats.sync_percent)
4079

    
4080
  return (alldone, min_resync)
4081

    
4082

    
4083
def DrbdNeedsActivation(disks):
4084
  """Checks which of the passed disks needs activation and returns their UUIDs.
4085

4086
  """
4087
  faulty_disks = []
4088

    
4089
  for disk in disks:
4090
    rd = _RecursiveFindBD(disk)
4091
    if rd is None:
4092
      faulty_disks.append(disk)
4093
      continue
4094

    
4095
    stats = rd.GetProcStatus()
4096
    if stats.is_standalone or stats.is_diskless:
4097
      faulty_disks.append(disk)
4098

    
4099
  return [disk.uuid for disk in faulty_disks]
4100

    
4101

    
4102
def GetDrbdUsermodeHelper():
4103
  """Returns DRBD usermode helper currently configured.