Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ b262a5c6

History | View | Annotate | Download (138.2 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
32

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

    
37

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

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

    
73

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

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

    
91
# Actions for the master setup script
92
_MASTER_START = "start"
93
_MASTER_STOP = "stop"
94

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

    
100
#: Delay before returning an error for restricted commands
101
_RCMD_INVALID_DELAY = 10
102

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

    
108

    
109
class RPCFail(Exception):
110
  """Class denoting RPC failure.
111

112
  Its argument is the error message.
113

114
  """
115

    
116

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

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

125
  """
126
  return utils.PathJoin(pathutils.INSTANCE_REASON_DIR, instance_name)
127

    
128

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

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

135
  @type instance_name: string
136
  @param instance_name: The name of the instance
137
  @rtype: None
138

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

    
144

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

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

153
  @type msg: string
154
  @param msg: the text of the exception
155
  @raise RPCFail
156

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

    
167

    
168
def _GetConfig():
169
  """Simple wrapper to return a SimpleStore.
170

171
  @rtype: L{ssconf.SimpleStore}
172
  @return: a SimpleStore instance
173

174
  """
175
  return ssconf.SimpleStore()
176

    
177

    
178
def _GetSshRunner(cluster_name):
179
  """Simple wrapper to return an SshRunner.
180

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

187
  """
188
  return ssh.SshRunner(cluster_name)
189

    
190

    
191
def _Decompress(data):
192
  """Unpacks data compressed by the RPC client.
193

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

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

    
210

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

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

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

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

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

    
240

    
241
def _BuildUploadFileList():
242
  """Build the list of allowed upload files.
243

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

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

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

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

    
267
  return frozenset(allowed_files)
268

    
269

    
270
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
271

    
272

    
273
def JobQueuePurge():
274
  """Removes job queue files and archived jobs.
275

276
  @rtype: tuple
277
  @return: True, None
278

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

    
283

    
284
def GetMasterInfo():
285
  """Returns master information.
286

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

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

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

    
308

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

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

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

    
328
      env_fn = compat.partial(env_builder_fn, *args, **kwargs)
329

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

    
340
      return result
341
    return wrapper
342
  return decorator
343

    
344

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

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

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

    
365
  return env
366

    
367

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

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

382
  """
383
  env = _BuildMasterIpEnv(master_params)
384

    
385
  if use_external_mip_script:
386
    setup_script = pathutils.EXTERNAL_MASTER_SETUP_SCRIPT
387
  else:
388
    setup_script = pathutils.DEFAULT_MASTER_SETUP_SCRIPT
389

    
390
  result = utils.RunCmd([setup_script, action], env=env, reset_env=True)
391

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

    
396

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

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

409
  """
410
  _RunMasterSetupScript(master_params, _MASTER_START,
411
                        use_external_mip_script)
412

    
413

    
414
def StartMasterDaemons(no_voting):
415
  """Activate local node as master node.
416

417
  The function will start the master daemons (ganeti-masterd and ganeti-rapi).
418

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

424
  """
425

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

    
431
  env = {
432
    "EXTRA_MASTERD_ARGS": masterd_args,
433
    }
434

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

    
441

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

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

454
  """
455
  _RunMasterSetupScript(master_params, _MASTER_STOP,
456
                        use_external_mip_script)
457

    
458

    
459
def StopMasterDaemons():
460
  """Stop the master daemons on this node.
461

462
  Stop the master daemons (ganeti-masterd and ganeti-rapi) on this node.
463

464
  @rtype: None
465

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

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

    
476

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

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

485
  """
486
  if old_netmask == netmask:
487
    return
488

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

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

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

    
507

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

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

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

    
529

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

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

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

540
  @param modify_ssh_setup: boolean
541

542
  """
543
  _CleanDirectory(pathutils.DATA_DIR)
544
  _CleanDirectory(pathutils.CRYPTO_KEYS_DIR)
545
  JobQueuePurge()
546

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

    
551
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
552

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

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

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

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

    
575

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

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

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

    
596

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

600
  @see: C{_CheckStorageParams}
601

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

    
610

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

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

620
  """
621
  excl_stor = _CheckLvmStorageParams(params)
622
  return _GetVgInfo(name, excl_stor)
623

    
624

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

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

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

    
646

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

650
  @see: C{_GetLvmVgSpaceInfo}
651

652
  """
653
  excl_stor = _CheckLvmStorageParams(params)
654
  return _GetVgSpindlesInfo(name, excl_stor)
655

    
656

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

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

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

    
682

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

686
  The information returned depends on the hypervisor. Common items:
687

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

695
  @type hvparams: dict of string
696
  @param hvparams: the hypervisor's hvparams
697

698
  """
699
  return get_hv_fn(name).GetNodeInfo(hvparams=hvparams)
700

    
701

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

705
  See C{_GetHvInfo} for information on the output.
706

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

710
  """
711
  if hv_specs is None:
712
    return None
713

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

    
719

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

723
  @rtype: None or dict
724

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

    
731

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

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

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

    
755

    
756
def _GetFileStorageSpaceInfo(path, params):
757
  """Wrapper around filestorage.GetSpaceInfo.
758

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

763
  @see: C{filestorage.GetFileStorageSpaceInfo} for description of the
764
    parameters.
765

766
  """
767
  _CheckStorageParams(params, 0)
768
  return filestorage.GetFileStorageSpaceInfo(path)
769

    
770

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

    
782

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

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

    
808

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

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

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

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

    
825

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

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

842
  """
843
  if not vm_capable:
844
    return
845

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

    
856

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

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

871
  """
872
  if not vm_capable:
873
    return
874

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

    
884

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

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

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

    
908

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

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

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

    
929

    
930
def VerifyNode(what, cluster_name, all_hvparams):
931
  """Verify the status of the local node.
932

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

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

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

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

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

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

    
968
  _VerifyHypervisors(what, vm_capable, result, all_hvparams)
969
  _VerifyHvparams(what, vm_capable, result)
970

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

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

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

    
987
    # Use a random order
988
    random.shuffle(nodes)
989

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

    
997
    result[constants.NV_NODELIST] = val
998

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

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

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

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

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

    
1061
  _VerifyInstanceList(what, vm_capable, result, all_hvparams)
1062

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

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

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

    
1082
  _VerifyNodeInfo(what, vm_capable, result, all_hvparams)
1083

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

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

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

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

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

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

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

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

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

    
1143
  return result
1144

    
1145

    
1146
def GetBlockDevSizes(devices):
1147
  """Return the size of the given block devices
1148

1149
  @type devices: list
1150
  @param devices: list of block device nodes to query
1151
  @rtype: dict
1152
  @return:
1153
    dictionary of all block devices under /dev (key). The value is their
1154
    size in MiB.
1155

1156
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
1157

1158
  """
1159
  DEV_PREFIX = "/dev/"
1160
  blockdevs = {}
1161

    
1162
  for devpath in devices:
1163
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
1164
      continue
1165

    
1166
    try:
1167
      st = os.stat(devpath)
1168
    except EnvironmentError, err:
1169
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
1170
      continue
1171

    
1172
    if stat.S_ISBLK(st.st_mode):
1173
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
1174
      if result.failed:
1175
        # We don't want to fail, just do not list this device as available
1176
        logging.warning("Cannot get size for block device %s", devpath)
1177
        continue
1178

    
1179
      size = int(result.stdout) / (1024 * 1024)
1180
      blockdevs[devpath] = size
1181
  return blockdevs
1182

    
1183

    
1184
def GetVolumeList(vg_names):
1185
  """Compute list of logical volumes and their size.
1186

1187
  @type vg_names: list
1188
  @param vg_names: the volume groups whose LVs we should list, or
1189
      empty for all volume groups
1190
  @rtype: dict
1191
  @return:
1192
      dictionary of all partions (key) with value being a tuple of
1193
      their size (in MiB), inactive and online status::
1194

1195
        {'xenvg/test1': ('20.06', True, True)}
1196

1197
      in case of errors, a string is returned with the error
1198
      details.
1199

1200
  """
1201
  lvs = {}
1202
  sep = "|"
1203
  if not vg_names:
1204
    vg_names = []
1205
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1206
                         "--separator=%s" % sep,
1207
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
1208
  if result.failed:
1209
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
1210

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

    
1227
  return lvs
1228

    
1229

    
1230
def ListVolumeGroups():
1231
  """List the volume groups and their size.
1232

1233
  @rtype: dict
1234
  @return: dictionary with keys volume name and values the
1235
      size of the volume
1236

1237
  """
1238
  return utils.ListVolumeGroups()
1239

    
1240

    
1241
def NodeVolumes():
1242
  """List all volumes on this node.
1243

1244
  @rtype: list
1245
  @return:
1246
    A list of dictionaries, each having four keys:
1247
      - name: the logical volume name,
1248
      - size: the size of the logical volume
1249
      - dev: the physical device on which the LV lives
1250
      - vg: the volume group to which it belongs
1251

1252
    In case of errors, we return an empty list and log the
1253
    error.
1254

1255
    Note that since a logical volume can live on multiple physical
1256
    volumes, the resulting list might include a logical volume
1257
    multiple times.
1258

1259
  """
1260
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1261
                         "--separator=|",
1262
                         "--options=lv_name,lv_size,devices,vg_name"])
1263
  if result.failed:
1264
    _Fail("Failed to list logical volumes, lvs output: %s",
1265
          result.output)
1266

    
1267
  def parse_dev(dev):
1268
    return dev.split("(")[0]
1269

    
1270
  def handle_dev(dev):
1271
    return [parse_dev(x) for x in dev.split(",")]
1272

    
1273
  def map_line(line):
1274
    line = [v.strip() for v in line]
1275
    return [{"name": line[0], "size": line[1],
1276
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
1277

    
1278
  all_devs = []
1279
  for line in result.stdout.splitlines():
1280
    if line.count("|") >= 3:
1281
      all_devs.extend(map_line(line.split("|")))
1282
    else:
1283
      logging.warning("Strange line in the output from lvs: '%s'", line)
1284
  return all_devs
1285

    
1286

    
1287
def BridgesExist(bridges_list):
1288
  """Check if a list of bridges exist on the current node.
1289

1290
  @rtype: boolean
1291
  @return: C{True} if all of them exist, C{False} otherwise
1292

1293
  """
1294
  missing = []
1295
  for bridge in bridges_list:
1296
    if not utils.BridgeExists(bridge):
1297
      missing.append(bridge)
1298

    
1299
  if missing:
1300
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
1301

    
1302

    
1303
def GetInstanceListForHypervisor(hname, hvparams=None,
1304
                                 get_hv_fn=hypervisor.GetHypervisor):
1305
  """Provides a list of instances of the given hypervisor.
1306

1307
  @type hname: string
1308
  @param hname: name of the hypervisor
1309
  @type hvparams: dict of strings
1310
  @param hvparams: hypervisor parameters for the given hypervisor
1311
  @type get_hv_fn: function
1312
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1313
    name; optional parameter to increase testability
1314

1315
  @rtype: list
1316
  @return: a list of all running instances on the current node
1317
    - instance1.example.com
1318
    - instance2.example.com
1319

1320
  """
1321
  results = []
1322
  try:
1323
    hv = get_hv_fn(hname)
1324
    names = hv.ListInstances(hvparams=hvparams)
1325
    results.extend(names)
1326
  except errors.HypervisorError, err:
1327
    _Fail("Error enumerating instances (hypervisor %s): %s",
1328
          hname, err, exc=True)
1329
  return results
1330

    
1331

    
1332
def GetInstanceList(hypervisor_list, all_hvparams=None,
1333
                    get_hv_fn=hypervisor.GetHypervisor):
1334
  """Provides a list of instances.
1335

1336
  @type hypervisor_list: list
1337
  @param hypervisor_list: the list of hypervisors to query information
1338
  @type all_hvparams: dict of dict of strings
1339
  @param all_hvparams: a dictionary mapping hypervisor types to respective
1340
    cluster-wide hypervisor parameters
1341
  @type get_hv_fn: function
1342
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1343
    name; optional parameter to increase testability
1344

1345
  @rtype: list
1346
  @return: a list of all running instances on the current node
1347
    - instance1.example.com
1348
    - instance2.example.com
1349

1350
  """
1351
  results = []
1352
  for hname in hypervisor_list:
1353
    hvparams = all_hvparams[hname]
1354
    results.extend(GetInstanceListForHypervisor(hname, hvparams=hvparams,
1355
                                                get_hv_fn=get_hv_fn))
1356
  return results
1357

    
1358

    
1359
def GetInstanceInfo(instance, hname, hvparams=None):
1360
  """Gives back the information about an instance as a dictionary.
1361

1362
  @type instance: string
1363
  @param instance: the instance name
1364
  @type hname: string
1365
  @param hname: the hypervisor type of the instance
1366
  @type hvparams: dict of strings
1367
  @param hvparams: the instance's hvparams
1368

1369
  @rtype: dict
1370
  @return: dictionary with the following keys:
1371
      - memory: memory size of instance (int)
1372
      - state: xen state of instance (string)
1373
      - time: cpu time of instance (float)
1374
      - vcpus: the number of vcpus (int)
1375

1376
  """
1377
  output = {}
1378

    
1379
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance,
1380
                                                          hvparams=hvparams)
1381
  if iinfo is not None:
1382
    output["memory"] = iinfo[2]
1383
    output["vcpus"] = iinfo[3]
1384
    output["state"] = iinfo[4]
1385
    output["time"] = iinfo[5]
1386

    
1387
  return output
1388

    
1389

    
1390
def GetInstanceMigratable(instance):
1391
  """Computes whether an instance can be migrated.
1392

1393
  @type instance: L{objects.Instance}
1394
  @param instance: object representing the instance to be checked.
1395

1396
  @rtype: tuple
1397
  @return: tuple of (result, description) where:
1398
      - result: whether the instance can be migrated or not
1399
      - description: a description of the issue, if relevant
1400

1401
  """
1402
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1403
  iname = instance.name
1404
  if iname not in hyper.ListInstances(instance.hvparams):
1405
    _Fail("Instance %s is not running", iname)
1406

    
1407
  for idx in range(len(instance.disks)):
1408
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1409
    if not os.path.islink(link_name):
1410
      logging.warning("Instance %s is missing symlink %s for disk %d",
1411
                      iname, link_name, idx)
1412

    
1413

    
1414
def GetAllInstancesInfo(hypervisor_list, all_hvparams):
1415
  """Gather data about all instances.
1416

1417
  This is the equivalent of L{GetInstanceInfo}, except that it
1418
  computes data for all instances at once, thus being faster if one
1419
  needs data about more than one instance.
1420

1421
  @type hypervisor_list: list
1422
  @param hypervisor_list: list of hypervisors to query for instance data
1423
  @type all_hvparams: dict of dict of strings
1424
  @param all_hvparams: mapping of hypervisor names to hvparams
1425

1426
  @rtype: dict
1427
  @return: dictionary of instance: data, with data having the following keys:
1428
      - memory: memory size of instance (int)
1429
      - state: xen state of instance (string)
1430
      - time: cpu time of instance (float)
1431
      - vcpus: the number of vcpus
1432

1433
  """
1434
  output = {}
1435

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

    
1457
  return output
1458

    
1459

    
1460
def _InstanceLogName(kind, os_name, instance, component):
1461
  """Compute the OS log filename for a given instance and operation.
1462

1463
  The instance name and os name are passed in as strings since not all
1464
  operations have these as part of an instance object.
1465

1466
  @type kind: string
1467
  @param kind: the operation type (e.g. add, import, etc.)
1468
  @type os_name: string
1469
  @param os_name: the os name
1470
  @type instance: string
1471
  @param instance: the name of the instance being imported/added/etc.
1472
  @type component: string or None
1473
  @param component: the name of the component of the instance being
1474
      transferred
1475

1476
  """
1477
  # TODO: Use tempfile.mkstemp to create unique filename
1478
  if component:
1479
    assert "/" not in component
1480
    c_msg = "-%s" % component
1481
  else:
1482
    c_msg = ""
1483
  base = ("%s-%s-%s%s-%s.log" %
1484
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1485
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1486

    
1487

    
1488
def InstanceOsAdd(instance, reinstall, debug):
1489
  """Add an OS to an instance.
1490

1491
  @type instance: L{objects.Instance}
1492
  @param instance: Instance whose OS is to be installed
1493
  @type reinstall: boolean
1494
  @param reinstall: whether this is an instance reinstall
1495
  @type debug: integer
1496
  @param debug: debug level, passed to the OS scripts
1497
  @rtype: None
1498

1499
  """
1500
  inst_os = OSFromDisk(instance.os)
1501

    
1502
  create_env = OSEnvironment(instance, inst_os, debug)
1503
  if reinstall:
1504
    create_env["INSTANCE_REINSTALL"] = "1"
1505

    
1506
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1507

    
1508
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1509
                        cwd=inst_os.path, output=logfile, reset_env=True)
1510
  if result.failed:
1511
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1512
                  " output: %s", result.cmd, result.fail_reason, logfile,
1513
                  result.output)
1514
    lines = [utils.SafeEncode(val)
1515
             for val in utils.TailFile(logfile, lines=20)]
1516
    _Fail("OS create script failed (%s), last lines in the"
1517
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1518

    
1519

    
1520
def RunRenameInstance(instance, old_name, debug):
1521
  """Run the OS rename script for an instance.
1522

1523
  @type instance: L{objects.Instance}
1524
  @param instance: Instance whose OS is to be installed
1525
  @type old_name: string
1526
  @param old_name: previous instance name
1527
  @type debug: integer
1528
  @param debug: debug level, passed to the OS scripts
1529
  @rtype: boolean
1530
  @return: the success of the operation
1531

1532
  """
1533
  inst_os = OSFromDisk(instance.os)
1534

    
1535
  rename_env = OSEnvironment(instance, inst_os, debug)
1536
  rename_env["OLD_INSTANCE_NAME"] = old_name
1537

    
1538
  logfile = _InstanceLogName("rename", instance.os,
1539
                             "%s-%s" % (old_name, instance.name), None)
1540

    
1541
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1542
                        cwd=inst_os.path, output=logfile, reset_env=True)
1543

    
1544
  if result.failed:
1545
    logging.error("os create command '%s' returned error: %s output: %s",
1546
                  result.cmd, result.fail_reason, result.output)
1547
    lines = [utils.SafeEncode(val)
1548
             for val in utils.TailFile(logfile, lines=20)]
1549
    _Fail("OS rename script failed (%s), last lines in the"
1550
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1551

    
1552

    
1553
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1554
  """Returns symlink path for block device.
1555

1556
  """
1557
  if _dir is None:
1558
    _dir = pathutils.DISK_LINKS_DIR
1559

    
1560
  return utils.PathJoin(_dir,
1561
                        ("%s%s%s" %
1562
                         (instance_name, constants.DISK_SEPARATOR, idx)))
1563

    
1564

    
1565
def _SymlinkBlockDev(instance_name, device_path, idx):
1566
  """Set up symlinks to a instance's block device.
1567

1568
  This is an auxiliary function run when an instance is start (on the primary
1569
  node) or when an instance is migrated (on the target node).
1570

1571

1572
  @param instance_name: the name of the target instance
1573
  @param device_path: path of the physical block device, on the node
1574
  @param idx: the disk index
1575
  @return: absolute path to the disk's symlink
1576

1577
  """
1578
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1579
  try:
1580
    os.symlink(device_path, link_name)
1581
  except OSError, err:
1582
    if err.errno == errno.EEXIST:
1583
      if (not os.path.islink(link_name) or
1584
          os.readlink(link_name) != device_path):
1585
        os.remove(link_name)
1586
        os.symlink(device_path, link_name)
1587
    else:
1588
      raise
1589

    
1590
  return link_name
1591

    
1592

    
1593
def _RemoveBlockDevLinks(instance_name, disks):
1594
  """Remove the block device symlinks belonging to the given instance.
1595

1596
  """
1597
  for idx, _ in enumerate(disks):
1598
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1599
    if os.path.islink(link_name):
1600
      try:
1601
        os.remove(link_name)
1602
      except OSError:
1603
        logging.exception("Can't remove symlink '%s'", link_name)
1604

    
1605

    
1606
def _GatherAndLinkBlockDevs(instance):
1607
  """Set up an instance's block device(s).
1608

1609
  This is run on the primary node at instance startup. The block
1610
  devices must be already assembled.
1611

1612
  @type instance: L{objects.Instance}
1613
  @param instance: the instance whose disks we shoul assemble
1614
  @rtype: list
1615
  @return: list of (disk_object, device_path)
1616

1617
  """
1618
  block_devices = []
1619
  for idx, disk in enumerate(instance.disks):
1620
    device = _RecursiveFindBD(disk)
1621
    if device is None:
1622
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1623
                                    str(disk))
1624
    device.Open()
1625
    try:
1626
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1627
    except OSError, e:
1628
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1629
                                    e.strerror)
1630

    
1631
    block_devices.append((disk, link_name))
1632

    
1633
  return block_devices
1634

    
1635

    
1636
def StartInstance(instance, startup_paused, reason, store_reason=True):
1637
  """Start an instance.
1638

1639
  @type instance: L{objects.Instance}
1640
  @param instance: the instance object
1641
  @type startup_paused: bool
1642
  @param instance: pause instance at startup?
1643
  @type reason: list of reasons
1644
  @param reason: the reason trail for this startup
1645
  @type store_reason: boolean
1646
  @param store_reason: whether to store the shutdown reason trail on file
1647
  @rtype: None
1648

1649
  """
1650
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1651
                                                   instance.hvparams)
1652

    
1653
  if instance.name in running_instances:
1654
    logging.info("Instance %s already running, not starting", instance.name)
1655
    return
1656

    
1657
  try:
1658
    block_devices = _GatherAndLinkBlockDevs(instance)
1659
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1660
    hyper.StartInstance(instance, block_devices, startup_paused)
1661
    if store_reason:
1662
      _StoreInstReasonTrail(instance.name, reason)
1663
  except errors.BlockDeviceError, err:
1664
    _Fail("Block device error: %s", err, exc=True)
1665
  except errors.HypervisorError, err:
1666
    _RemoveBlockDevLinks(instance.name, instance.disks)
1667
    _Fail("Hypervisor error: %s", err, exc=True)
1668

    
1669

    
1670
def InstanceShutdown(instance, timeout, reason, store_reason=True):
1671
  """Shut an instance down.
1672

1673
  @note: this functions uses polling with a hardcoded timeout.
1674

1675
  @type instance: L{objects.Instance}
1676
  @param instance: the instance object
1677
  @type timeout: integer
1678
  @param timeout: maximum timeout for soft shutdown
1679
  @type reason: list of reasons
1680
  @param reason: the reason trail for this shutdown
1681
  @type store_reason: boolean
1682
  @param store_reason: whether to store the shutdown reason trail on file
1683
  @rtype: None
1684

1685
  """
1686
  hv_name = instance.hypervisor
1687
  hyper = hypervisor.GetHypervisor(hv_name)
1688
  iname = instance.name
1689

    
1690
  if instance.name not in hyper.ListInstances(instance.hvparams):
1691
    logging.info("Instance %s not running, doing nothing", iname)
1692
    return
1693

    
1694
  class _TryShutdown:
1695
    def __init__(self):
1696
      self.tried_once = False
1697

    
1698
    def __call__(self):
1699
      if iname not in hyper.ListInstances(instance.hvparams):
1700
        return
1701

    
1702
      try:
1703
        hyper.StopInstance(instance, retry=self.tried_once)
1704
        if store_reason:
1705
          _StoreInstReasonTrail(instance.name, reason)
1706
      except errors.HypervisorError, err:
1707
        if iname not in hyper.ListInstances(instance.hvparams):
1708
          # if the instance is no longer existing, consider this a
1709
          # success and go to cleanup
1710
          return
1711

    
1712
        _Fail("Failed to stop instance %s: %s", iname, err)
1713

    
1714
      self.tried_once = True
1715

    
1716
      raise utils.RetryAgain()
1717

    
1718
  try:
1719
    utils.Retry(_TryShutdown(), 5, timeout)
1720
  except utils.RetryTimeout:
1721
    # the shutdown did not succeed
1722
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1723

    
1724
    try:
1725
      hyper.StopInstance(instance, force=True)
1726
    except errors.HypervisorError, err:
1727
      if iname in hyper.ListInstances(instance.hvparams):
1728
        # only raise an error if the instance still exists, otherwise
1729
        # the error could simply be "instance ... unknown"!
1730
        _Fail("Failed to force stop instance %s: %s", iname, err)
1731

    
1732
    time.sleep(1)
1733

    
1734
    if iname in hyper.ListInstances(instance.hvparams):
1735
      _Fail("Could not shutdown instance %s even by destroy", iname)
1736

    
1737
  try:
1738
    hyper.CleanupInstance(instance.name)
1739
  except errors.HypervisorError, err:
1740
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1741

    
1742
  _RemoveBlockDevLinks(iname, instance.disks)
1743

    
1744

    
1745
def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1746
  """Reboot an instance.
1747

1748
  @type instance: L{objects.Instance}
1749
  @param instance: the instance object to reboot
1750
  @type reboot_type: str
1751
  @param reboot_type: the type of reboot, one the following
1752
    constants:
1753
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1754
        instance OS, do not recreate the VM
1755
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1756
        restart the VM (at the hypervisor level)
1757
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1758
        not accepted here, since that mode is handled differently, in
1759
        cmdlib, and translates into full stop and start of the
1760
        instance (instead of a call_instance_reboot RPC)
1761
  @type shutdown_timeout: integer
1762
  @param shutdown_timeout: maximum timeout for soft shutdown
1763
  @type reason: list of reasons
1764
  @param reason: the reason trail for this reboot
1765
  @rtype: None
1766

1767
  """
1768
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1769
                                                   instance.hvparams)
1770

    
1771
  if instance.name not in running_instances:
1772
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1773

    
1774
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1775
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1776
    try:
1777
      hyper.RebootInstance(instance)
1778
    except errors.HypervisorError, err:
1779
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1780
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1781
    try:
1782
      InstanceShutdown(instance, shutdown_timeout, reason, store_reason=False)
1783
      result = StartInstance(instance, False, reason, store_reason=False)
1784
      _StoreInstReasonTrail(instance.name, reason)
1785
      return result
1786
    except errors.HypervisorError, err:
1787
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1788
  else:
1789
    _Fail("Invalid reboot_type received: %s", reboot_type)
1790

    
1791

    
1792
def InstanceBalloonMemory(instance, memory):
1793
  """Resize an instance's memory.
1794

1795
  @type instance: L{objects.Instance}
1796
  @param instance: the instance object
1797
  @type memory: int
1798
  @param memory: new memory amount in MB
1799
  @rtype: None
1800

1801
  """
1802
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1803
  running = hyper.ListInstances(instance.hvparams)
1804
  if instance.name not in running:
1805
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1806
    return
1807
  try:
1808
    hyper.BalloonInstanceMemory(instance, memory)
1809
  except errors.HypervisorError, err:
1810
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1811

    
1812

    
1813
def MigrationInfo(instance):
1814
  """Gather information about an instance to be migrated.
1815

1816
  @type instance: L{objects.Instance}
1817
  @param instance: the instance definition
1818

1819
  """
1820
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1821
  try:
1822
    info = hyper.MigrationInfo(instance)
1823
  except errors.HypervisorError, err:
1824
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1825
  return info
1826

    
1827

    
1828
def AcceptInstance(instance, info, target):
1829
  """Prepare the node to accept an instance.
1830

1831
  @type instance: L{objects.Instance}
1832
  @param instance: the instance definition
1833
  @type info: string/data (opaque)
1834
  @param info: migration information, from the source node
1835
  @type target: string
1836
  @param target: target host (usually ip), on this node
1837

1838
  """
1839
  # TODO: why is this required only for DTS_EXT_MIRROR?
1840
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1841
    # Create the symlinks, as the disks are not active
1842
    # in any way
1843
    try:
1844
      _GatherAndLinkBlockDevs(instance)
1845
    except errors.BlockDeviceError, err:
1846
      _Fail("Block device error: %s", err, exc=True)
1847

    
1848
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1849
  try:
1850
    hyper.AcceptInstance(instance, info, target)
1851
  except errors.HypervisorError, err:
1852
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1853
      _RemoveBlockDevLinks(instance.name, instance.disks)
1854
    _Fail("Failed to accept instance: %s", err, exc=True)
1855

    
1856

    
1857
def FinalizeMigrationDst(instance, info, success):
1858
  """Finalize any preparation to accept an instance.
1859

1860
  @type instance: L{objects.Instance}
1861
  @param instance: the instance definition
1862
  @type info: string/data (opaque)
1863
  @param info: migration information, from the source node
1864
  @type success: boolean
1865
  @param success: whether the migration was a success or a failure
1866

1867
  """
1868
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1869
  try:
1870
    hyper.FinalizeMigrationDst(instance, info, success)
1871
  except errors.HypervisorError, err:
1872
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1873

    
1874

    
1875
def MigrateInstance(cluster_name, instance, target, live):
1876
  """Migrates an instance to another node.
1877

1878
  @type cluster_name: string
1879
  @param cluster_name: name of the cluster
1880
  @type instance: L{objects.Instance}
1881
  @param instance: the instance definition
1882
  @type target: string
1883
  @param target: the target node name
1884
  @type live: boolean
1885
  @param live: whether the migration should be done live or not (the
1886
      interpretation of this parameter is left to the hypervisor)
1887
  @raise RPCFail: if migration fails for some reason
1888

1889
  """
1890
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1891

    
1892
  try:
1893
    hyper.MigrateInstance(cluster_name, instance, target, live)
1894
  except errors.HypervisorError, err:
1895
    _Fail("Failed to migrate instance: %s", err, exc=True)
1896

    
1897

    
1898
def FinalizeMigrationSource(instance, success, live):
1899
  """Finalize the instance migration on the source node.
1900

1901
  @type instance: L{objects.Instance}
1902
  @param instance: the instance definition of the migrated instance
1903
  @type success: bool
1904
  @param success: whether the migration succeeded or not
1905
  @type live: bool
1906
  @param live: whether the user requested a live migration or not
1907
  @raise RPCFail: If the execution fails for some reason
1908

1909
  """
1910
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1911

    
1912
  try:
1913
    hyper.FinalizeMigrationSource(instance, success, live)
1914
  except Exception, err:  # pylint: disable=W0703
1915
    _Fail("Failed to finalize the migration on the source node: %s", err,
1916
          exc=True)
1917

    
1918

    
1919
def GetMigrationStatus(instance):
1920
  """Get the migration status
1921

1922
  @type instance: L{objects.Instance}
1923
  @param instance: the instance that is being migrated
1924
  @rtype: L{objects.MigrationStatus}
1925
  @return: the status of the current migration (one of
1926
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1927
           progress info that can be retrieved from the hypervisor
1928
  @raise RPCFail: If the migration status cannot be retrieved
1929

1930
  """
1931
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1932
  try:
1933
    return hyper.GetMigrationStatus(instance)
1934
  except Exception, err:  # pylint: disable=W0703
1935
    _Fail("Failed to get migration status: %s", err, exc=True)
1936

    
1937
def HotplugDevice(instance, action, dev_type, device, extra, seq):
1938
  """Hotplug a device
1939

1940
  Hotplug is currently supported only for KVM Hypervisor.
1941
  @type instance: L{objects.Instance}
1942
  @param instance: the instance to which we hotplug a device
1943
  @type action: string
1944
  @param action: the hotplug action to perform
1945
  @type dev_type: string
1946
  @param dev_type: the device type to hotplug
1947
  @type device: either L{objects.NIC} or L{objects.Disk}
1948
  @param device: the device object to hotplug
1949
  @type extra: string
1950
  @param extra: extra info used by hotplug code (e.g. disk link)
1951
  @type seq: int
1952
  @param seq: the index of the device from master perspective
1953
  @raise RPCFail: in case instance does not have KVM hypervisor
1954

1955
  """
1956
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1957
  try:
1958
    getattr(hyper, "HotplugDevice")
1959
  except NameError:
1960
    _Fail("Hotplug is not supported for %s hypervisor",
1961
          instance.hypervisor, exc=True )
1962
  return hyper.HotplugDevice(instance, action, dev_type, device, extra, seq)
1963

    
1964
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
1965
  """Creates a block device for an instance.
1966

1967
  @type disk: L{objects.Disk}
1968
  @param disk: the object describing the disk we should create
1969
  @type size: int
1970
  @param size: the size of the physical underlying device, in MiB
1971
  @type owner: str
1972
  @param owner: the name of the instance for which disk is created,
1973
      used for device cache data
1974
  @type on_primary: boolean
1975
  @param on_primary:  indicates if it is the primary node or not
1976
  @type info: string
1977
  @param info: string that will be sent to the physical device
1978
      creation, used for example to set (LVM) tags on LVs
1979
  @type excl_stor: boolean
1980
  @param excl_stor: Whether exclusive_storage is active
1981

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

1986
  """
1987
  # TODO: remove the obsolete "size" argument
1988
  # pylint: disable=W0613
1989
  clist = []
1990
  if disk.children:
1991
    for child in disk.children:
1992
      try:
1993
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1994
      except errors.BlockDeviceError, err:
1995
        _Fail("Can't assemble device %s: %s", child, err)
1996
      if on_primary or disk.AssembleOnSecondary():
1997
        # we need the children open in case the device itself has to
1998
        # be assembled
1999
        try:
2000
          # pylint: disable=E1103
2001
          crdev.Open()
2002
        except errors.BlockDeviceError, err:
2003
          _Fail("Can't make child '%s' read-write: %s", child, err)
2004
      clist.append(crdev)
2005

    
2006
  try:
2007
    device = bdev.Create(disk, clist, excl_stor)
2008
  except errors.BlockDeviceError, err:
2009
    _Fail("Can't create block device: %s", err)
2010

    
2011
  if on_primary or disk.AssembleOnSecondary():
2012
    try:
2013
      device.Assemble()
2014
    except errors.BlockDeviceError, err:
2015
      _Fail("Can't assemble device after creation, unusual event: %s", err)
2016
    if on_primary or disk.OpenOnSecondary():
2017
      try:
2018
        device.Open(force=True)
2019
      except errors.BlockDeviceError, err:
2020
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
2021
    DevCacheManager.UpdateCache(device.dev_path, owner,
2022
                                on_primary, disk.iv_name)
2023

    
2024
  device.SetInfo(info)
2025

    
2026
  return device.unique_id
2027

    
2028

    
2029
def _WipeDevice(path, offset, size):
2030
  """This function actually wipes the device.
2031

2032
  @param path: The path to the device to wipe
2033
  @param offset: The offset in MiB in the file
2034
  @param size: The size in MiB to write
2035

2036
  """
2037
  # Internal sizes are always in Mebibytes; if the following "dd" command
2038
  # should use a different block size the offset and size given to this
2039
  # function must be adjusted accordingly before being passed to "dd".
2040
  block_size = 1024 * 1024
2041

    
2042
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
2043
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
2044
         "count=%d" % size]
2045
  result = utils.RunCmd(cmd)
2046

    
2047
  if result.failed:
2048
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
2049
          result.fail_reason, result.output)
2050

    
2051

    
2052
def BlockdevWipe(disk, offset, size):
2053
  """Wipes a block device.
2054

2055
  @type disk: L{objects.Disk}
2056
  @param disk: the disk object we want to wipe
2057
  @type offset: int
2058
  @param offset: The offset in MiB in the file
2059
  @type size: int
2060
  @param size: The size in MiB to write
2061

2062
  """
2063
  try:
2064
    rdev = _RecursiveFindBD(disk)
2065
  except errors.BlockDeviceError:
2066
    rdev = None
2067

    
2068
  if not rdev:
2069
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
2070

    
2071
  # Do cross verify some of the parameters
2072
  if offset < 0:
2073
    _Fail("Negative offset")
2074
  if size < 0:
2075
    _Fail("Negative size")
2076
  if offset > rdev.size:
2077
    _Fail("Offset is bigger than device size")
2078
  if (offset + size) > rdev.size:
2079
    _Fail("The provided offset and size to wipe is bigger than device size")
2080

    
2081
  _WipeDevice(rdev.dev_path, offset, size)
2082

    
2083

    
2084
def BlockdevPauseResumeSync(disks, pause):
2085
  """Pause or resume the sync of the block device.
2086

2087
  @type disks: list of L{objects.Disk}
2088
  @param disks: the disks object we want to pause/resume
2089
  @type pause: bool
2090
  @param pause: Wheater to pause or resume
2091

2092
  """
2093
  success = []
2094
  for disk in disks:
2095
    try:
2096
      rdev = _RecursiveFindBD(disk)
2097
    except errors.BlockDeviceError:
2098
      rdev = None
2099

    
2100
    if not rdev:
2101
      success.append((False, ("Cannot change sync for device %s:"
2102
                              " device not found" % disk.iv_name)))
2103
      continue
2104

    
2105
    result = rdev.PauseResumeSync(pause)
2106

    
2107
    if result:
2108
      success.append((result, None))
2109
    else:
2110
      if pause:
2111
        msg = "Pause"
2112
      else:
2113
        msg = "Resume"
2114
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
2115

    
2116
  return success
2117

    
2118

    
2119
def BlockdevRemove(disk):
2120
  """Remove a block device.
2121

2122
  @note: This is intended to be called recursively.
2123

2124
  @type disk: L{objects.Disk}
2125
  @param disk: the disk object we should remove
2126
  @rtype: boolean
2127
  @return: the success of the operation
2128

2129
  """
2130
  msgs = []
2131
  try:
2132
    rdev = _RecursiveFindBD(disk)
2133
  except errors.BlockDeviceError, err:
2134
    # probably can't attach
2135
    logging.info("Can't attach to device %s in remove", disk)
2136
    rdev = None
2137
  if rdev is not None:
2138
    r_path = rdev.dev_path
2139
    try:
2140
      rdev.Remove()
2141
    except errors.BlockDeviceError, err:
2142
      msgs.append(str(err))
2143
    if not msgs:
2144
      DevCacheManager.RemoveCache(r_path)
2145

    
2146
  if disk.children:
2147
    for child in disk.children:
2148
      try:
2149
        BlockdevRemove(child)
2150
      except RPCFail, err:
2151
        msgs.append(str(err))
2152

    
2153
  if msgs:
2154
    _Fail("; ".join(msgs))
2155

    
2156

    
2157
def _RecursiveAssembleBD(disk, owner, as_primary):
2158
  """Activate a block device for an instance.
2159

2160
  This is run on the primary and secondary nodes for an instance.
2161

2162
  @note: this function is called recursively.
2163

2164
  @type disk: L{objects.Disk}
2165
  @param disk: the disk we try to assemble
2166
  @type owner: str
2167
  @param owner: the name of the instance which owns the disk
2168
  @type as_primary: boolean
2169
  @param as_primary: if we should make the block device
2170
      read/write
2171

2172
  @return: the assembled device or None (in case no device
2173
      was assembled)
2174
  @raise errors.BlockDeviceError: in case there is an error
2175
      during the activation of the children or the device
2176
      itself
2177

2178
  """
2179
  children = []
2180
  if disk.children:
2181
    mcn = disk.ChildrenNeeded()
2182
    if mcn == -1:
2183
      mcn = 0 # max number of Nones allowed
2184
    else:
2185
      mcn = len(disk.children) - mcn # max number of Nones
2186
    for chld_disk in disk.children:
2187
      try:
2188
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
2189
      except errors.BlockDeviceError, err:
2190
        if children.count(None) >= mcn:
2191
          raise
2192
        cdev = None
2193
        logging.error("Error in child activation (but continuing): %s",
2194
                      str(err))
2195
      children.append(cdev)
2196

    
2197
  if as_primary or disk.AssembleOnSecondary():
2198
    r_dev = bdev.Assemble(disk, children)
2199
    result = r_dev
2200
    if as_primary or disk.OpenOnSecondary():
2201
      r_dev.Open()
2202
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
2203
                                as_primary, disk.iv_name)
2204

    
2205
  else:
2206
    result = True
2207
  return result
2208

    
2209

    
2210
def BlockdevAssemble(disk, owner, as_primary, idx):
2211
  """Activate a block device for an instance.
2212

2213
  This is a wrapper over _RecursiveAssembleBD.
2214

2215
  @rtype: str or boolean
2216
  @return: a C{/dev/...} path for primary nodes, and
2217
      C{True} for secondary nodes
2218

2219
  """
2220
  try:
2221
    result = _RecursiveAssembleBD(disk, owner, as_primary)
2222
    if isinstance(result, BlockDev):
2223
      # pylint: disable=E1103
2224
      result = result.dev_path
2225
      if as_primary:
2226
        _SymlinkBlockDev(owner, result, idx)
2227
  except errors.BlockDeviceError, err:
2228
    _Fail("Error while assembling disk: %s", err, exc=True)
2229
  except OSError, err:
2230
    _Fail("Error while symlinking disk: %s", err, exc=True)
2231

    
2232
  return result
2233

    
2234

    
2235
def BlockdevShutdown(disk):
2236
  """Shut down a block device.
2237

2238
  First, if the device is assembled (Attach() is successful), then
2239
  the device is shutdown. Then the children of the device are
2240
  shutdown.
2241

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

2246
  @type disk: L{objects.Disk}
2247
  @param disk: the description of the disk we should
2248
      shutdown
2249
  @rtype: None
2250

2251
  """
2252
  msgs = []
2253
  r_dev = _RecursiveFindBD(disk)
2254
  if r_dev is not None:
2255
    r_path = r_dev.dev_path
2256
    try:
2257
      r_dev.Shutdown()
2258
      DevCacheManager.RemoveCache(r_path)
2259
    except errors.BlockDeviceError, err:
2260
      msgs.append(str(err))
2261

    
2262
  if disk.children:
2263
    for child in disk.children:
2264
      try:
2265
        BlockdevShutdown(child)
2266
      except RPCFail, err:
2267
        msgs.append(str(err))
2268

    
2269
  if msgs:
2270
    _Fail("; ".join(msgs))
2271

    
2272

    
2273
def BlockdevAddchildren(parent_cdev, new_cdevs):
2274
  """Extend a mirrored block device.
2275

2276
  @type parent_cdev: L{objects.Disk}
2277
  @param parent_cdev: the disk to which we should add children
2278
  @type new_cdevs: list of L{objects.Disk}
2279
  @param new_cdevs: the list of children which we should add
2280
  @rtype: None
2281

2282
  """
2283
  parent_bdev = _RecursiveFindBD(parent_cdev)
2284
  if parent_bdev is None:
2285
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
2286
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
2287
  if new_bdevs.count(None) > 0:
2288
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
2289
  parent_bdev.AddChildren(new_bdevs)
2290

    
2291

    
2292
def BlockdevRemovechildren(parent_cdev, new_cdevs):
2293
  """Shrink a mirrored block device.
2294

2295
  @type parent_cdev: L{objects.Disk}
2296
  @param parent_cdev: the disk from which we should remove children
2297
  @type new_cdevs: list of L{objects.Disk}
2298
  @param new_cdevs: the list of children which we should remove
2299
  @rtype: None
2300

2301
  """
2302
  parent_bdev = _RecursiveFindBD(parent_cdev)
2303
  if parent_bdev is None:
2304
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
2305
  devs = []
2306
  for disk in new_cdevs:
2307
    rpath = disk.StaticDevPath()
2308
    if rpath is None:
2309
      bd = _RecursiveFindBD(disk)
2310
      if bd is None:
2311
        _Fail("Can't find device %s while removing children", disk)
2312
      else:
2313
        devs.append(bd.dev_path)
2314
    else:
2315
      if not utils.IsNormAbsPath(rpath):
2316
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
2317
      devs.append(rpath)
2318
  parent_bdev.RemoveChildren(devs)
2319

    
2320

    
2321
def BlockdevGetmirrorstatus(disks):
2322
  """Get the mirroring status of a list of devices.
2323

2324
  @type disks: list of L{objects.Disk}
2325
  @param disks: the list of disks which we should query
2326
  @rtype: disk
2327
  @return: List of L{objects.BlockDevStatus}, one for each disk
2328
  @raise errors.BlockDeviceError: if any of the disks cannot be
2329
      found
2330

2331
  """
2332
  stats = []
2333
  for dsk in disks:
2334
    rbd = _RecursiveFindBD(dsk)
2335
    if rbd is None:
2336
      _Fail("Can't find device %s", dsk)
2337

    
2338
    stats.append(rbd.CombinedSyncStatus())
2339

    
2340
  return stats
2341

    
2342

    
2343
def BlockdevGetmirrorstatusMulti(disks):
2344
  """Get the mirroring status of a list of devices.
2345

2346
  @type disks: list of L{objects.Disk}
2347
  @param disks: the list of disks which we should query
2348
  @rtype: disk
2349
  @return: List of tuples, (bool, status), one for each disk; bool denotes
2350
    success/failure, status is L{objects.BlockDevStatus} on success, string
2351
    otherwise
2352

2353
  """
2354
  result = []
2355
  for disk in disks:
2356
    try:
2357
      rbd = _RecursiveFindBD(disk)
2358
      if rbd is None:
2359
        result.append((False, "Can't find device %s" % disk))
2360
        continue
2361

    
2362
      status = rbd.CombinedSyncStatus()
2363
    except errors.BlockDeviceError, err:
2364
      logging.exception("Error while getting disk status")
2365
      result.append((False, str(err)))
2366
    else:
2367
      result.append((True, status))
2368

    
2369
  assert len(disks) == len(result)
2370

    
2371
  return result
2372

    
2373

    
2374
def _RecursiveFindBD(disk):
2375
  """Check if a device is activated.
2376

2377
  If so, return information about the real device.
2378

2379
  @type disk: L{objects.Disk}
2380
  @param disk: the disk object we need to find
2381

2382
  @return: None if the device can't be found,
2383
      otherwise the device instance
2384

2385
  """
2386
  children = []
2387
  if disk.children:
2388
    for chdisk in disk.children:
2389
      children.append(_RecursiveFindBD(chdisk))
2390

    
2391
  return bdev.FindDevice(disk, children)
2392

    
2393

    
2394
def _OpenRealBD(disk):
2395
  """Opens the underlying block device of a disk.
2396

2397
  @type disk: L{objects.Disk}
2398
  @param disk: the disk object we want to open
2399

2400
  """
2401
  real_disk = _RecursiveFindBD(disk)
2402
  if real_disk is None:
2403
    _Fail("Block device '%s' is not set up", disk)
2404

    
2405
  real_disk.Open()
2406

    
2407
  return real_disk
2408

    
2409

    
2410
def BlockdevFind(disk):
2411
  """Check if a device is activated.
2412

2413
  If it is, return information about the real device.
2414

2415
  @type disk: L{objects.Disk}
2416
  @param disk: the disk to find
2417
  @rtype: None or objects.BlockDevStatus
2418
  @return: None if the disk cannot be found, otherwise a the current
2419
           information
2420

2421
  """
2422
  try:
2423
    rbd = _RecursiveFindBD(disk)
2424
  except errors.BlockDeviceError, err:
2425
    _Fail("Failed to find device: %s", err, exc=True)
2426

    
2427
  if rbd is None:
2428
    return None
2429

    
2430
  return rbd.GetSyncStatus()
2431

    
2432

    
2433
def BlockdevGetdimensions(disks):
2434
  """Computes the size of the given disks.
2435

2436
  If a disk is not found, returns None instead.
2437

2438
  @type disks: list of L{objects.Disk}
2439
  @param disks: the list of disk to compute the size for
2440
  @rtype: list
2441
  @return: list with elements None if the disk cannot be found,
2442
      otherwise the pair (size, spindles), where spindles is None if the
2443
      device doesn't support that
2444

2445
  """
2446
  result = []
2447
  for cf in disks:
2448
    try:
2449
      rbd = _RecursiveFindBD(cf)
2450
    except errors.BlockDeviceError:
2451
      result.append(None)
2452
      continue
2453
    if rbd is None:
2454
      result.append(None)
2455
    else:
2456
      result.append(rbd.GetActualDimensions())
2457
  return result
2458

    
2459

    
2460
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2461
  """Export a block device to a remote node.
2462

2463
  @type disk: L{objects.Disk}
2464
  @param disk: the description of the disk to export
2465
  @type dest_node: str
2466
  @param dest_node: the destination node to export to
2467
  @type dest_path: str
2468
  @param dest_path: the destination path on the target node
2469
  @type cluster_name: str
2470
  @param cluster_name: the cluster name, needed for SSH hostalias
2471
  @rtype: None
2472

2473
  """
2474
  real_disk = _OpenRealBD(disk)
2475

    
2476
  # the block size on the read dd is 1MiB to match our units
2477
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2478
                               "dd if=%s bs=1048576 count=%s",
2479
                               real_disk.dev_path, str(disk.size))
2480

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

    
2490
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2491
                                                   constants.SSH_LOGIN_USER,
2492
                                                   destcmd)
2493

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

    
2497
  result = utils.RunCmd(["bash", "-c", command])
2498

    
2499
  if result.failed:
2500
    _Fail("Disk copy command '%s' returned error: %s"
2501
          " output: %s", command, result.fail_reason, result.output)
2502

    
2503

    
2504
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2505
  """Write a file to the filesystem.
2506

2507
  This allows the master to overwrite(!) a file. It will only perform
2508
  the operation if the file belongs to a list of configuration files.
2509

2510
  @type file_name: str
2511
  @param file_name: the target file name
2512
  @type data: str
2513
  @param data: the new contents of the file
2514
  @type mode: int
2515
  @param mode: the mode to give the file (can be None)
2516
  @type uid: string
2517
  @param uid: the owner of the file
2518
  @type gid: string
2519
  @param gid: the group of the file
2520
  @type atime: float
2521
  @param atime: the atime to set on the file (can be None)
2522
  @type mtime: float
2523
  @param mtime: the mtime to set on the file (can be None)
2524
  @rtype: None
2525

2526
  """
2527
  file_name = vcluster.LocalizeVirtualPath(file_name)
2528

    
2529
  if not os.path.isabs(file_name):
2530
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2531

    
2532
  if file_name not in _ALLOWED_UPLOAD_FILES:
2533
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2534
          file_name)
2535

    
2536
  raw_data = _Decompress(data)
2537

    
2538
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2539
    _Fail("Invalid username/groupname type")
2540

    
2541
  getents = runtime.GetEnts()
2542
  uid = getents.LookupUser(uid)
2543
  gid = getents.LookupGroup(gid)
2544

    
2545
  utils.SafeWriteFile(file_name, None,
2546
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2547
                      atime=atime, mtime=mtime)
2548

    
2549

    
2550
def RunOob(oob_program, command, node, timeout):
2551
  """Executes oob_program with given command on given node.
2552

2553
  @param oob_program: The path to the executable oob_program
2554
  @param command: The command to invoke on oob_program
2555
  @param node: The node given as an argument to the program
2556
  @param timeout: Timeout after which we kill the oob program
2557

2558
  @return: stdout
2559
  @raise RPCFail: If execution fails for some reason
2560

2561
  """
2562
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2563

    
2564
  if result.failed:
2565
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2566
          result.fail_reason, result.output)
2567

    
2568
  return result.stdout
2569

    
2570

    
2571
def _OSOndiskAPIVersion(os_dir):
2572
  """Compute and return the API version of a given OS.
2573

2574
  This function will try to read the API version of the OS residing in
2575
  the 'os_dir' directory.
2576

2577
  @type os_dir: str
2578
  @param os_dir: the directory in which we should look for the OS
2579
  @rtype: tuple
2580
  @return: tuple (status, data) with status denoting the validity and
2581
      data holding either the vaid versions or an error message
2582

2583
  """
2584
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2585

    
2586
  try:
2587
    st = os.stat(api_file)
2588
  except EnvironmentError, err:
2589
    return False, ("Required file '%s' not found under path %s: %s" %
2590
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2591

    
2592
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2593
    return False, ("File '%s' in %s is not a regular file" %
2594
                   (constants.OS_API_FILE, os_dir))
2595

    
2596
  try:
2597
    api_versions = utils.ReadFile(api_file).splitlines()
2598
  except EnvironmentError, err:
2599
    return False, ("Error while reading the API version file at %s: %s" %
2600
                   (api_file, utils.ErrnoOrStr(err)))
2601

    
2602
  try:
2603
    api_versions = [int(version.strip()) for version in api_versions]
2604
  except (TypeError, ValueError), err:
2605
    return False, ("API version(s) can't be converted to integer: %s" %
2606
                   str(err))
2607

    
2608
  return True, api_versions
2609

    
2610

    
2611
def DiagnoseOS(top_dirs=None):
2612
  """Compute the validity for all OSes.
2613

2614
  @type top_dirs: list
2615
  @param top_dirs: the list of directories in which to
2616
      search (if not given defaults to
2617
      L{pathutils.OS_SEARCH_PATH})
2618
  @rtype: list of L{objects.OS}
2619
  @return: a list of tuples (name, path, status, diagnose, variants,
2620
      parameters, api_version) for all (potential) OSes under all
2621
      search paths, where:
2622
          - name is the (potential) OS name
2623
          - path is the full path to the OS
2624
          - status True/False is the validity of the OS
2625
          - diagnose is the error message for an invalid OS, otherwise empty
2626
          - variants is a list of supported OS variants, if any
2627
          - parameters is a list of (name, help) parameters, if any
2628
          - api_version is a list of support OS API versions
2629

2630
  """
2631
  if top_dirs is None:
2632
    top_dirs = pathutils.OS_SEARCH_PATH
2633

    
2634
  result = []
2635
  for dir_name in top_dirs:
2636
    if os.path.isdir(dir_name):
2637
      try:
2638
        f_names = utils.ListVisibleFiles(dir_name)
2639
      except EnvironmentError, err:
2640
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2641
        break
2642
      for name in f_names:
2643
        os_path = utils.PathJoin(dir_name, name)
2644
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2645
        if status:
2646
          diagnose = ""
2647
          variants = os_inst.supported_variants
2648
          parameters = os_inst.supported_parameters
2649
          api_versions = os_inst.api_versions
2650
        else:
2651
          diagnose = os_inst
2652
          variants = parameters = api_versions = []
2653
        result.append((name, os_path, status, diagnose, variants,
2654
                       parameters, api_versions))
2655

    
2656
  return result
2657

    
2658

    
2659
def _TryOSFromDisk(name, base_dir=None):
2660
  """Create an OS instance from disk.
2661

2662
  This function will return an OS instance if the given name is a
2663
  valid OS name.
2664

2665
  @type base_dir: string
2666
  @keyword base_dir: Base directory containing OS installations.
2667
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2668
  @rtype: tuple
2669
  @return: success and either the OS instance if we find a valid one,
2670
      or error message
2671

2672
  """
2673
  if base_dir is None:
2674
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2675
  else:
2676
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2677

    
2678
  if os_dir is None:
2679
    return False, "Directory for OS %s not found in search path" % name
2680

    
2681
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2682
  if not status:
2683
    # push the error up
2684
    return status, api_versions
2685

    
2686
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2687
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2688
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2689

    
2690
  # OS Files dictionary, we will populate it with the absolute path
2691
  # names; if the value is True, then it is a required file, otherwise
2692
  # an optional one
2693
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2694

    
2695
  if max(api_versions) >= constants.OS_API_V15:
2696
    os_files[constants.OS_VARIANTS_FILE] = False
2697

    
2698
  if max(api_versions) >= constants.OS_API_V20:
2699
    os_files[constants.OS_PARAMETERS_FILE] = True
2700
  else:
2701
    del os_files[constants.OS_SCRIPT_VERIFY]
2702

    
2703
  for (filename, required) in os_files.items():
2704
    os_files[filename] = utils.PathJoin(os_dir, filename)
2705

    
2706
    try:
2707
      st = os.stat(os_files[filename])
2708
    except EnvironmentError, err:
2709
      if err.errno == errno.ENOENT and not required:
2710
        del os_files[filename]
2711
        continue
2712
      return False, ("File '%s' under path '%s' is missing (%s)" %
2713
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2714

    
2715
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2716
      return False, ("File '%s' under path '%s' is not a regular file" %
2717
                     (filename, os_dir))
2718

    
2719
    if filename in constants.OS_SCRIPTS:
2720
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2721
        return False, ("File '%s' under path '%s' is not executable" %
2722
                       (filename, os_dir))
2723

    
2724
  variants = []
2725
  if constants.OS_VARIANTS_FILE in os_files:
2726
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2727
    try:
2728
      variants = \
2729
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2730
    except EnvironmentError, err:
2731
      # we accept missing files, but not other errors
2732
      if err.errno != errno.ENOENT:
2733
        return False, ("Error while reading the OS variants file at %s: %s" %
2734
                       (variants_file, utils.ErrnoOrStr(err)))
2735

    
2736
  parameters = []
2737
  if constants.OS_PARAMETERS_FILE in os_files:
2738
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2739
    try:
2740
      parameters = utils.ReadFile(parameters_file).splitlines()
2741
    except EnvironmentError, err:
2742
      return False, ("Error while reading the OS parameters file at %s: %s" %
2743
                     (parameters_file, utils.ErrnoOrStr(err)))
2744
    parameters = [v.split(None, 1) for v in parameters]
2745

    
2746
  os_obj = objects.OS(name=name, path=os_dir,
2747
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2748
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2749
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2750
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2751
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2752
                                                 None),
2753
                      supported_variants=variants,
2754
                      supported_parameters=parameters,
2755
                      api_versions=api_versions)
2756
  return True, os_obj
2757

    
2758

    
2759
def OSFromDisk(name, base_dir=None):
2760
  """Create an OS instance from disk.
2761

2762
  This function will return an OS instance if the given name is a
2763
  valid OS name. Otherwise, it will raise an appropriate
2764
  L{RPCFail} exception, detailing why this is not a valid OS.
2765

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

2769
  @type base_dir: string
2770
  @keyword base_dir: Base directory containing OS installations.
2771
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2772
  @rtype: L{objects.OS}
2773
  @return: the OS instance if we find a valid one
2774
  @raise RPCFail: if we don't find a valid OS
2775

2776
  """
2777
  name_only = objects.OS.GetName(name)
2778
  status, payload = _TryOSFromDisk(name_only, base_dir)
2779

    
2780
  if not status:
2781
    _Fail(payload)
2782

    
2783
  return payload
2784

    
2785

    
2786
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2787
  """Calculate the basic environment for an os script.
2788

2789
  @type os_name: str
2790
  @param os_name: full operating system name (including variant)
2791
  @type inst_os: L{objects.OS}
2792
  @param inst_os: operating system for which the environment is being built
2793
  @type os_params: dict
2794
  @param os_params: the OS parameters
2795
  @type debug: integer
2796
  @param debug: debug level (0 or 1, for OS Api 10)
2797
  @rtype: dict
2798
  @return: dict of environment variables
2799
  @raise errors.BlockDeviceError: if the block device
2800
      cannot be found
2801

2802
  """
2803
  result = {}
2804
  api_version = \
2805
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2806
  result["OS_API_VERSION"] = "%d" % api_version
2807
  result["OS_NAME"] = inst_os.name
2808
  result["DEBUG_LEVEL"] = "%d" % debug
2809

    
2810
  # OS variants
2811
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2812
    variant = objects.OS.GetVariant(os_name)
2813
    if not variant:
2814
      variant = inst_os.supported_variants[0]
2815
  else:
2816
    variant = ""
2817
  result["OS_VARIANT"] = variant
2818

    
2819
  # OS params
2820
  for pname, pvalue in os_params.items():
2821
    result["OSP_%s" % pname.upper()] = pvalue
2822

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

    
2828
  return result
2829

    
2830

    
2831
def OSEnvironment(instance, inst_os, debug=0):
2832
  """Calculate the environment for an os script.
2833

2834
  @type instance: L{objects.Instance}
2835
  @param instance: target instance for the os script run
2836
  @type inst_os: L{objects.OS}
2837
  @param inst_os: operating system for which the environment is being built
2838
  @type debug: integer
2839
  @param debug: debug level (0 or 1, for OS Api 10)
2840
  @rtype: dict
2841
  @return: dict of environment variables
2842
  @raise errors.BlockDeviceError: if the block device
2843
      cannot be found
2844

2845
  """
2846
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2847

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

    
2851
  result["HYPERVISOR"] = instance.hypervisor
2852
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2853
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2854
  result["INSTANCE_SECONDARY_NODES"] = \
2855
      ("%s" % " ".join(instance.secondary_nodes))
2856

    
2857
  # Disks
2858
  for idx, disk in enumerate(instance.disks):
2859
    real_disk = _OpenRealBD(disk)
2860
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2861
    result["DISK_%d_ACCESS" % idx] = disk.mode
2862
    result["DISK_%d_UUID" % idx] = disk.uuid
2863
    if disk.name:
2864
      result["DISK_%d_NAME" % idx] = disk.name
2865
    if constants.HV_DISK_TYPE in instance.hvparams:
2866
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2867
        instance.hvparams[constants.HV_DISK_TYPE]
2868
    if disk.dev_type in constants.LDS_BLOCK:
2869
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2870
    elif disk.dev_type == constants.LD_FILE:
2871
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2872
        "file:%s" % disk.physical_id[0]
2873

    
2874
  # NICs
2875
  for idx, nic in enumerate(instance.nics):
2876
    result["NIC_%d_MAC" % idx] = nic.mac
2877
    result["NIC_%d_UUID" % idx] = nic.uuid
2878
    if nic.name:
2879
      result["NIC_%d_NAME" % idx] = nic.name
2880
    if nic.ip:
2881
      result["NIC_%d_IP" % idx] = nic.ip
2882
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2883
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2884
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2885
    if nic.nicparams[constants.NIC_LINK]:
2886
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2887
    if nic.netinfo:
2888
      nobj = objects.Network.FromDict(nic.netinfo)
2889
      result.update(nobj.HooksDict("NIC_%d_" % idx))
2890
    if constants.HV_NIC_TYPE in instance.hvparams:
2891
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2892
        instance.hvparams[constants.HV_NIC_TYPE]
2893

    
2894
  # HV/BE params
2895
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2896
    for key, value in source.items():
2897
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2898

    
2899
  return result
2900

    
2901

    
2902
def DiagnoseExtStorage(top_dirs=None):
2903
  """Compute the validity for all ExtStorage Providers.
2904

2905
  @type top_dirs: list
2906
  @param top_dirs: the list of directories in which to
2907
      search (if not given defaults to
2908
      L{pathutils.ES_SEARCH_PATH})
2909
  @rtype: list of L{objects.ExtStorage}
2910
  @return: a list of tuples (name, path, status, diagnose, parameters)
2911
      for all (potential) ExtStorage Providers under all
2912
      search paths, where:
2913
          - name is the (potential) ExtStorage Provider
2914
          - path is the full path to the ExtStorage Provider
2915
          - status True/False is the validity of the ExtStorage Provider
2916
          - diagnose is the error message for an invalid ExtStorage Provider,
2917
            otherwise empty
2918
          - parameters is a list of (name, help) parameters, if any
2919

2920
  """
2921
  if top_dirs is None:
2922
    top_dirs = pathutils.ES_SEARCH_PATH
2923

    
2924
  result = []
2925
  for dir_name in top_dirs:
2926
    if os.path.isdir(dir_name):
2927
      try:
2928
        f_names = utils.ListVisibleFiles(dir_name)
2929
      except EnvironmentError, err:
2930
        logging.exception("Can't list the ExtStorage directory %s: %s",
2931
                          dir_name, err)
2932
        break
2933
      for name in f_names:
2934
        es_path = utils.PathJoin(dir_name, name)
2935
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2936
        if status:
2937
          diagnose = ""
2938
          parameters = es_inst.supported_parameters
2939
        else:
2940
          diagnose = es_inst
2941
          parameters = []
2942
        result.append((name, es_path, status, diagnose, parameters))
2943

    
2944
  return result
2945

    
2946

    
2947
def BlockdevGrow(disk, amount, dryrun, backingstore, excl_stor):
2948
  """Grow a stack of block devices.
2949

2950
  This function is called recursively, with the childrens being the
2951
  first ones to resize.
2952

2953
  @type disk: L{objects.Disk}
2954
  @param disk: the disk to be grown
2955
  @type amount: integer
2956
  @param amount: the amount (in mebibytes) to grow with
2957
  @type dryrun: boolean
2958
  @param dryrun: whether to execute the operation in simulation mode
2959
      only, without actually increasing the size
2960
  @param backingstore: whether to execute the operation on backing storage
2961
      only, or on "logical" storage only; e.g. DRBD is logical storage,
2962
      whereas LVM, file, RBD are backing storage
2963
  @rtype: (status, result)
2964
  @type excl_stor: boolean
2965
  @param excl_stor: Whether exclusive_storage is active
2966
  @return: a tuple with the status of the operation (True/False), and
2967
      the errors message if status is False
2968

2969
  """
2970
  r_dev = _RecursiveFindBD(disk)
2971
  if r_dev is None:
2972
    _Fail("Cannot find block device %s", disk)
2973

    
2974
  try:
2975
    r_dev.Grow(amount, dryrun, backingstore, excl_stor)
2976
  except errors.BlockDeviceError, err:
2977
    _Fail("Failed to grow block device: %s", err, exc=True)
2978

    
2979

    
2980
def BlockdevSnapshot(disk):
2981
  """Create a snapshot copy of a block device.
2982

2983
  This function is called recursively, and the snapshot is actually created
2984
  just for the leaf lvm backend device.
2985

2986
  @type disk: L{objects.Disk}
2987
  @param disk: the disk to be snapshotted
2988
  @rtype: string
2989
  @return: snapshot disk ID as (vg, lv)
2990

2991
  """
2992
  if disk.dev_type == constants.LD_DRBD8:
2993
    if not disk.children:
2994
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2995
            disk.unique_id)
2996
    return BlockdevSnapshot(disk.children[0])
2997
  elif disk.dev_type == constants.LD_LV:
2998
    r_dev = _RecursiveFindBD(disk)
2999
    if r_dev is not None:
3000
      # FIXME: choose a saner value for the snapshot size
3001
      # let's stay on the safe side and ask for the full size, for now
3002
      return r_dev.Snapshot(disk.size)
3003
    else:
3004
      _Fail("Cannot find block device %s", disk)
3005
  else:
3006
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
3007
          disk.unique_id, disk.dev_type)
3008

    
3009

    
3010
def BlockdevSetInfo(disk, info):
3011
  """Sets 'metadata' information on block devices.
3012

3013
  This function sets 'info' metadata on block devices. Initial
3014
  information is set at device creation; this function should be used
3015
  for example after renames.
3016

3017
  @type disk: L{objects.Disk}
3018
  @param disk: the disk to be grown
3019
  @type info: string
3020
  @param info: new 'info' metadata
3021
  @rtype: (status, result)
3022
  @return: a tuple with the status of the operation (True/False), and
3023
      the errors message if status is False
3024

3025
  """
3026
  r_dev = _RecursiveFindBD(disk)
3027
  if r_dev is None:
3028
    _Fail("Cannot find block device %s", disk)
3029

    
3030
  try:
3031
    r_dev.SetInfo(info)
3032
  except errors.BlockDeviceError, err:
3033
    _Fail("Failed to set information on block device: %s", err, exc=True)
3034

    
3035

    
3036
def FinalizeExport(instance, snap_disks):
3037
  """Write out the export configuration information.
3038

3039
  @type instance: L{objects.Instance}
3040
  @param instance: the instance which we export, used for
3041
      saving configuration
3042
  @type snap_disks: list of L{objects.Disk}
3043
  @param snap_disks: list of snapshot block devices, which
3044
      will be used to get the actual name of the dump file
3045

3046
  @rtype: None
3047

3048
  """
3049
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
3050
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
3051

    
3052
  config = objects.SerializableConfigParser()
3053

    
3054
  config.add_section(constants.INISECT_EXP)
3055
  config.set(constants.INISECT_EXP, "version", "0")
3056
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
3057
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
3058
  config.set(constants.INISECT_EXP, "os", instance.os)
3059
  config.set(constants.INISECT_EXP, "compression", "none")
3060

    
3061
  config.add_section(constants.INISECT_INS)
3062
  config.set(constants.INISECT_INS, "name", instance.name)
3063
  config.set(constants.INISECT_INS, "maxmem", "%d" %
3064
             instance.beparams[constants.BE_MAXMEM])
3065
  config.set(constants.INISECT_INS, "minmem", "%d" %
3066
             instance.beparams[constants.BE_MINMEM])
3067
  # "memory" is deprecated, but useful for exporting to old ganeti versions
3068
  config.set(constants.INISECT_INS, "memory", "%d" %
3069
             instance.beparams[constants.BE_MAXMEM])
3070
  config.set(constants.INISECT_INS, "vcpus", "%d" %
3071
             instance.beparams[constants.BE_VCPUS])
3072
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
3073
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
3074
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
3075

    
3076
  nic_total = 0
3077
  for nic_count, nic in enumerate(instance.nics):
3078
    nic_total += 1
3079
    config.set(constants.INISECT_INS, "nic%d_mac" %
3080
               nic_count, "%s" % nic.mac)
3081
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
3082
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
3083
               "%s" % nic.network)
3084
    for param in constants.NICS_PARAMETER_TYPES:
3085
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
3086
                 "%s" % nic.nicparams.get(param, None))
3087
  # TODO: redundant: on load can read nics until it doesn't exist
3088
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
3089

    
3090
  disk_total = 0
3091
  for disk_count, disk in enumerate(snap_disks):
3092
    if disk:
3093
      disk_total += 1
3094
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
3095
                 ("%s" % disk.iv_name))
3096
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
3097
                 ("%s" % disk.physical_id[1]))
3098
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
3099
                 ("%d" % disk.size))
3100

    
3101
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
3102

    
3103
  # New-style hypervisor/backend parameters
3104

    
3105
  config.add_section(constants.INISECT_HYP)
3106
  for name, value in instance.hvparams.items():
3107
    if name not in constants.HVC_GLOBALS:
3108
      config.set(constants.INISECT_HYP, name, str(value))
3109

    
3110
  config.add_section(constants.INISECT_BEP)
3111
  for name, value in instance.beparams.items():
3112
    config.set(constants.INISECT_BEP, name, str(value))
3113

    
3114
  config.add_section(constants.INISECT_OSP)
3115
  for name, value in instance.osparams.items():
3116
    config.set(constants.INISECT_OSP, name, str(value))
3117

    
3118
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
3119
                  data=config.Dumps())
3120
  shutil.rmtree(finaldestdir, ignore_errors=True)
3121
  shutil.move(destdir, finaldestdir)
3122

    
3123

    
3124
def ExportInfo(dest):
3125
  """Get export configuration information.
3126

3127
  @type dest: str
3128
  @param dest: directory containing the export
3129

3130
  @rtype: L{objects.SerializableConfigParser}
3131
  @return: a serializable config file containing the
3132
      export info
3133

3134
  """
3135
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
3136

    
3137
  config = objects.SerializableConfigParser()
3138
  config.read(cff)
3139

    
3140
  if (not config.has_section(constants.INISECT_EXP) or
3141
      not config.has_section(constants.INISECT_INS)):
3142
    _Fail("Export info file doesn't have the required fields")
3143

    
3144
  return config.Dumps()
3145

    
3146

    
3147
def ListExports():
3148
  """Return a list of exports currently available on this machine.
3149

3150
  @rtype: list
3151
  @return: list of the exports
3152

3153
  """
3154
  if os.path.isdir(pathutils.EXPORT_DIR):
3155
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
3156
  else:
3157
    _Fail("No exports directory")
3158

    
3159

    
3160
def RemoveExport(export):
3161
  """Remove an existing export from the node.
3162

3163
  @type export: str
3164
  @param export: the name of the export to remove
3165
  @rtype: None
3166

3167
  """
3168
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
3169

    
3170
  try:
3171
    shutil.rmtree(target)
3172
  except EnvironmentError, err:
3173
    _Fail("Error while removing the export: %s", err, exc=True)
3174

    
3175

    
3176
def BlockdevRename(devlist):
3177
  """Rename a list of block devices.
3178

3179
  @type devlist: list of tuples
3180
  @param devlist: list of tuples of the form  (disk,
3181
      new_logical_id, new_physical_id); disk is an
3182
      L{objects.Disk} object describing the current disk,
3183
      and new logical_id/physical_id is the name we
3184
      rename it to
3185
  @rtype: boolean
3186
  @return: True if all renames succeeded, False otherwise
3187

3188
  """
3189
  msgs = []
3190
  result = True
3191
  for disk, unique_id in devlist:
3192
    dev = _RecursiveFindBD(disk)
3193
    if dev is None:
3194
      msgs.append("Can't find device %s in rename" % str(disk))
3195
      result = False
3196
      continue
3197
    try:
3198
      old_rpath = dev.dev_path
3199
      dev.Rename(unique_id)
3200
      new_rpath = dev.dev_path
3201
      if old_rpath != new_rpath:
3202
        DevCacheManager.RemoveCache(old_rpath)
3203
        # FIXME: we should add the new cache information here, like:
3204
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
3205
        # but we don't have the owner here - maybe parse from existing
3206
        # cache? for now, we only lose lvm data when we rename, which
3207
        # is less critical than DRBD or MD
3208
    except errors.BlockDeviceError, err:
3209
      msgs.append("Can't rename device '%s' to '%s': %s" %
3210
                  (dev, unique_id, err))
3211
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
3212
      result = False
3213
  if not result:
3214
    _Fail("; ".join(msgs))
3215

    
3216

    
3217
def _TransformFileStorageDir(fs_dir):
3218
  """Checks whether given file_storage_dir is valid.
3219

3220
  Checks wheter the given fs_dir is within the cluster-wide default
3221
  file_storage_dir or the shared_file_storage_dir, which are stored in
3222
  SimpleStore. Only paths under those directories are allowed.
3223

3224
  @type fs_dir: str
3225
  @param fs_dir: the path to check
3226

3227
  @return: the normalized path if valid, None otherwise
3228

3229
  """
3230
  filestorage.CheckFileStoragePath(fs_dir)
3231

    
3232
  return os.path.normpath(fs_dir)
3233

    
3234

    
3235
def CreateFileStorageDir(file_storage_dir):
3236
  """Create file storage directory.
3237

3238
  @type file_storage_dir: str
3239
  @param file_storage_dir: directory to create
3240

3241
  @rtype: tuple
3242
  @return: tuple with first element a boolean indicating wheter dir
3243
      creation was successful or not
3244

3245
  """
3246
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3247
  if os.path.exists(file_storage_dir):
3248
    if not os.path.isdir(file_storage_dir):
3249
      _Fail("Specified storage dir '%s' is not a directory",
3250
            file_storage_dir)
3251
  else:
3252
    try:
3253
      os.makedirs(file_storage_dir, 0750)
3254
    except OSError, err:
3255
      _Fail("Cannot create file storage directory '%s': %s",
3256
            file_storage_dir, err, exc=True)
3257

    
3258

    
3259
def RemoveFileStorageDir(file_storage_dir):
3260
  """Remove file storage directory.
3261

3262
  Remove it only if it's empty. If not log an error and return.
3263

3264
  @type file_storage_dir: str
3265
  @param file_storage_dir: the directory we should cleanup
3266
  @rtype: tuple (success,)
3267
  @return: tuple of one element, C{success}, denoting
3268
      whether the operation was successful
3269

3270
  """
3271
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3272
  if os.path.exists(file_storage_dir):
3273
    if not os.path.isdir(file_storage_dir):
3274
      _Fail("Specified Storage directory '%s' is not a directory",
3275
            file_storage_dir)
3276
    # deletes dir only if empty, otherwise we want to fail the rpc call
3277
    try:
3278
      os.rmdir(file_storage_dir)
3279
    except OSError, err:
3280
      _Fail("Cannot remove file storage directory '%s': %s",
3281
            file_storage_dir, err)
3282

    
3283

    
3284
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
3285
  """Rename the file storage directory.
3286

3287
  @type old_file_storage_dir: str
3288
  @param old_file_storage_dir: the current path
3289
  @type new_file_storage_dir: str
3290
  @param new_file_storage_dir: the name we should rename to
3291
  @rtype: tuple (success,)
3292
  @return: tuple of one element, C{success}, denoting
3293
      whether the operation was successful
3294

3295
  """
3296
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
3297
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
3298
  if not os.path.exists(new_file_storage_dir):
3299
    if os.path.isdir(old_file_storage_dir):
3300
      try:
3301
        os.rename(old_file_storage_dir, new_file_storage_dir)
3302
      except OSError, err:
3303
        _Fail("Cannot rename '%s' to '%s': %s",
3304
              old_file_storage_dir, new_file_storage_dir, err)
3305
    else:
3306
      _Fail("Specified storage dir '%s' is not a directory",
3307
            old_file_storage_dir)
3308
  else:
3309
    if os.path.exists(old_file_storage_dir):
3310
      _Fail("Cannot rename '%s' to '%s': both locations exist",
3311
            old_file_storage_dir, new_file_storage_dir)
3312

    
3313

    
3314
def _EnsureJobQueueFile(file_name):
3315
  """Checks whether the given filename is in the queue directory.
3316

3317
  @type file_name: str
3318
  @param file_name: the file name we should check
3319
  @rtype: None
3320
  @raises RPCFail: if the file is not valid
3321

3322
  """
3323
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
3324
    _Fail("Passed job queue file '%s' does not belong to"
3325
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
3326

    
3327

    
3328
def JobQueueUpdate(file_name, content):
3329
  """Updates a file in the queue directory.
3330

3331
  This is just a wrapper over L{utils.io.WriteFile}, with proper
3332
  checking.
3333

3334
  @type file_name: str
3335
  @param file_name: the job file name
3336
  @type content: str
3337
  @param content: the new job contents
3338
  @rtype: boolean
3339
  @return: the success of the operation
3340

3341
  """
3342
  file_name = vcluster.LocalizeVirtualPath(file_name)
3343

    
3344
  _EnsureJobQueueFile(file_name)
3345
  getents = runtime.GetEnts()
3346

    
3347
  # Write and replace the file atomically
3348
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3349
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3350

    
3351

    
3352
def JobQueueRename(old, new):
3353
  """Renames a job queue file.
3354

3355
  This is just a wrapper over os.rename with proper checking.
3356

3357
  @type old: str
3358
  @param old: the old (actual) file name
3359
  @type new: str
3360
  @param new: the desired file name
3361
  @rtype: tuple
3362
  @return: the success of the operation and payload
3363

3364
  """
3365
  old = vcluster.LocalizeVirtualPath(old)
3366
  new = vcluster.LocalizeVirtualPath(new)
3367

    
3368
  _EnsureJobQueueFile(old)
3369
  _EnsureJobQueueFile(new)
3370

    
3371
  getents = runtime.GetEnts()
3372

    
3373
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3374
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3375

    
3376

    
3377
def BlockdevClose(instance_name, disks):
3378
  """Closes the given block devices.
3379

3380
  This means they will be switched to secondary mode (in case of
3381
  DRBD).
3382

3383
  @param instance_name: if the argument is not empty, the symlinks
3384
      of this instance will be removed
3385
  @type disks: list of L{objects.Disk}
3386
  @param disks: the list of disks to be closed
3387
  @rtype: tuple (success, message)
3388
  @return: a tuple of success and message, where success
3389
      indicates the succes of the operation, and message
3390
      which will contain the error details in case we
3391
      failed
3392

3393
  """
3394
  bdevs = []
3395
  for cf in disks:
3396
    rd = _RecursiveFindBD(cf)
3397
    if rd is None:
3398
      _Fail("Can't find device %s", cf)
3399
    bdevs.append(rd)
3400

    
3401
  msg = []
3402
  for rd in bdevs:
3403
    try:
3404
      rd.Close()
3405
    except errors.BlockDeviceError, err:
3406
      msg.append(str(err))
3407
  if msg:
3408
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3409
  else:
3410
    if instance_name:
3411
      _RemoveBlockDevLinks(instance_name, disks)
3412

    
3413

    
3414
def ValidateHVParams(hvname, hvparams):
3415
  """Validates the given hypervisor parameters.
3416

3417
  @type hvname: string
3418
  @param hvname: the hypervisor name
3419
  @type hvparams: dict
3420
  @param hvparams: the hypervisor parameters to be validated
3421
  @rtype: None
3422

3423
  """
3424
  try:
3425
    hv_type = hypervisor.GetHypervisor(hvname)
3426
    hv_type.ValidateParameters(hvparams)
3427
  except errors.HypervisorError, err:
3428
    _Fail(str(err), log=False)
3429

    
3430

    
3431
def _CheckOSPList(os_obj, parameters):
3432
  """Check whether a list of parameters is supported by the OS.
3433

3434
  @type os_obj: L{objects.OS}
3435
  @param os_obj: OS object to check
3436
  @type parameters: list
3437
  @param parameters: the list of parameters to check
3438

3439
  """
3440
  supported = [v[0] for v in os_obj.supported_parameters]
3441
  delta = frozenset(parameters).difference(supported)
3442
  if delta:
3443
    _Fail("The following parameters are not supported"
3444
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3445

    
3446

    
3447
def ValidateOS(required, osname, checks, osparams):
3448
  """Validate the given OS' parameters.
3449

3450
  @type required: boolean
3451
  @param required: whether absence of the OS should translate into
3452
      failure or not
3453
  @type osname: string
3454
  @param osname: the OS to be validated
3455
  @type checks: list
3456
  @param checks: list of the checks to run (currently only 'parameters')
3457
  @type osparams: dict
3458
  @param osparams: dictionary with OS parameters
3459
  @rtype: boolean
3460
  @return: True if the validation passed, or False if the OS was not
3461
      found and L{required} was false
3462

3463
  """
3464
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3465
    _Fail("Unknown checks required for OS %s: %s", osname,
3466
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3467

    
3468
  name_only = objects.OS.GetName(osname)
3469
  status, tbv = _TryOSFromDisk(name_only, None)
3470

    
3471
  if not status:
3472
    if required:
3473
      _Fail(tbv)
3474
    else:
3475
      return False
3476

    
3477
  if max(tbv.api_versions) < constants.OS_API_V20:
3478
    return True
3479

    
3480
  if constants.OS_VALIDATE_PARAMETERS in checks:
3481
    _CheckOSPList(tbv, osparams.keys())
3482

    
3483
  validate_env = OSCoreEnv(osname, tbv, osparams)
3484
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3485
                        cwd=tbv.path, reset_env=True)
3486
  if result.failed:
3487
    logging.error("os validate command '%s' returned error: %s output: %s",
3488
                  result.cmd, result.fail_reason, result.output)
3489
    _Fail("OS validation script failed (%s), output: %s",
3490
          result.fail_reason, result.output, log=False)
3491

    
3492
  return True
3493

    
3494

    
3495
def DemoteFromMC():
3496
  """Demotes the current node from master candidate role.
3497

3498
  """
3499
  # try to ensure we're not the master by mistake
3500
  master, myself = ssconf.GetMasterAndMyself()
3501
  if master == myself:
3502
    _Fail("ssconf status shows I'm the master node, will not demote")
3503

    
3504
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3505
  if not result.failed:
3506
    _Fail("The master daemon is running, will not demote")
3507

    
3508
  try:
3509
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3510
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3511
  except EnvironmentError, err:
3512
    if err.errno != errno.ENOENT:
3513
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3514

    
3515
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3516

    
3517

    
3518
def _GetX509Filenames(cryptodir, name):
3519
  """Returns the full paths for the private key and certificate.
3520

3521
  """
3522
  return (utils.PathJoin(cryptodir, name),
3523
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3524
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3525

    
3526

    
3527
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3528
  """Creates a new X509 certificate for SSL/TLS.
3529

3530
  @type validity: int
3531
  @param validity: Validity in seconds
3532
  @rtype: tuple; (string, string)
3533
  @return: Certificate name and public part
3534

3535
  """
3536
  (key_pem, cert_pem) = \
3537
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3538
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3539

    
3540
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3541
                              prefix="x509-%s-" % utils.TimestampForFilename())
3542
  try:
3543
    name = os.path.basename(cert_dir)
3544
    assert len(name) > 5
3545

    
3546
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3547

    
3548
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3549
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3550

    
3551
    # Never return private key as it shouldn't leave the node
3552
    return (name, cert_pem)
3553
  except Exception:
3554
    shutil.rmtree(cert_dir, ignore_errors=True)
3555
    raise
3556

    
3557

    
3558
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3559
  """Removes a X509 certificate.
3560

3561
  @type name: string
3562
  @param name: Certificate name
3563

3564
  """
3565
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3566

    
3567
  utils.RemoveFile(key_file)
3568
  utils.RemoveFile(cert_file)
3569

    
3570
  try:
3571
    os.rmdir(cert_dir)
3572
  except EnvironmentError, err:
3573
    _Fail("Cannot remove certificate directory '%s': %s",
3574
          cert_dir, err)
3575

    
3576

    
3577
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3578
  """Returns the command for the requested input/output.
3579

3580
  @type instance: L{objects.Instance}
3581
  @param instance: The instance object
3582
  @param mode: Import/export mode
3583
  @param ieio: Input/output type
3584
  @param ieargs: Input/output arguments
3585

3586
  """
3587
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3588

    
3589
  env = None
3590
  prefix = None
3591
  suffix = None
3592
  exp_size = None
3593

    
3594
  if ieio == constants.IEIO_FILE:
3595
    (filename, ) = ieargs
3596

    
3597
    if not utils.IsNormAbsPath(filename):
3598
      _Fail("Path '%s' is not normalized or absolute", filename)
3599

    
3600
    real_filename = os.path.realpath(filename)
3601
    directory = os.path.dirname(real_filename)
3602

    
3603
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3604
      _Fail("File '%s' is not under exports directory '%s': %s",
3605
            filename, pathutils.EXPORT_DIR, real_filename)
3606

    
3607
    # Create directory
3608
    utils.Makedirs(directory, mode=0750)
3609

    
3610
    quoted_filename = utils.ShellQuote(filename)
3611

    
3612
    if mode == constants.IEM_IMPORT:
3613
      suffix = "> %s" % quoted_filename
3614
    elif mode == constants.IEM_EXPORT:
3615
      suffix = "< %s" % quoted_filename
3616

    
3617
      # Retrieve file size
3618
      try:
3619
        st = os.stat(filename)
3620
      except EnvironmentError, err:
3621
        logging.error("Can't stat(2) %s: %s", filename, err)
3622
      else:
3623
        exp_size = utils.BytesToMebibyte(st.st_size)
3624

    
3625
  elif ieio == constants.IEIO_RAW_DISK:
3626
    (disk, ) = ieargs
3627

    
3628
    real_disk = _OpenRealBD(disk)
3629

    
3630
    if mode == constants.IEM_IMPORT:
3631
      # we set here a smaller block size as, due to transport buffering, more
3632
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3633
      # is not already there or we pass a wrong path; we use notrunc to no
3634
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3635
      # much memory; this means that at best, we flush every 64k, which will
3636
      # not be very fast
3637
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3638
                                    " bs=%s oflag=dsync"),
3639
                                    real_disk.dev_path,
3640
                                    str(64 * 1024))
3641

    
3642
    elif mode == constants.IEM_EXPORT:
3643
      # the block size on the read dd is 1MiB to match our units
3644
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3645
                                   real_disk.dev_path,
3646
                                   str(1024 * 1024), # 1 MB
3647
                                   str(disk.size))
3648
      exp_size = disk.size
3649

    
3650
  elif ieio == constants.IEIO_SCRIPT:
3651
    (disk, disk_index, ) = ieargs
3652

    
3653
    assert isinstance(disk_index, (int, long))
3654

    
3655
    real_disk = _OpenRealBD(disk)
3656

    
3657
    inst_os = OSFromDisk(instance.os)
3658
    env = OSEnvironment(instance, inst_os)
3659

    
3660
    if mode == constants.IEM_IMPORT:
3661
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3662
      env["IMPORT_INDEX"] = str(disk_index)
3663
      script = inst_os.import_script
3664

    
3665
    elif mode == constants.IEM_EXPORT:
3666
      env["EXPORT_DEVICE"] = real_disk.dev_path
3667
      env["EXPORT_INDEX"] = str(disk_index)
3668
      script = inst_os.export_script
3669

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

    
3673
    if mode == constants.IEM_IMPORT:
3674
      suffix = "| %s" % script_cmd
3675

    
3676
    elif mode == constants.IEM_EXPORT:
3677
      prefix = "%s |" % script_cmd
3678

    
3679
    # Let script predict size
3680
    exp_size = constants.IE_CUSTOM_SIZE
3681

    
3682
  else:
3683
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3684

    
3685
  return (env, prefix, suffix, exp_size)
3686

    
3687

    
3688
def _CreateImportExportStatusDir(prefix):
3689
  """Creates status directory for import/export.
3690

3691
  """
3692
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3693
                          prefix=("%s-%s-" %
3694
                                  (prefix, utils.TimestampForFilename())))
3695

    
3696

    
3697
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3698
                            ieio, ieioargs):
3699
  """Starts an import or export daemon.
3700

3701
  @param mode: Import/output mode
3702
  @type opts: L{objects.ImportExportOptions}
3703
  @param opts: Daemon options
3704
  @type host: string
3705
  @param host: Remote host for export (None for import)
3706
  @type port: int
3707
  @param port: Remote port for export (None for import)
3708
  @type instance: L{objects.Instance}
3709
  @param instance: Instance object
3710
  @type component: string
3711
  @param component: which part of the instance is transferred now,
3712
      e.g. 'disk/0'
3713
  @param ieio: Input/output type
3714
  @param ieioargs: Input/output arguments
3715

3716
  """
3717
  if mode == constants.IEM_IMPORT:
3718
    prefix = "import"
3719

    
3720
    if not (host is None and port is None):
3721
      _Fail("Can not specify host or port on import")
3722

    
3723
  elif mode == constants.IEM_EXPORT:
3724
    prefix = "export"
3725

    
3726
    if host is None or port is None:
3727
      _Fail("Host and port must be specified for an export")
3728

    
3729
  else:
3730
    _Fail("Invalid mode %r", mode)
3731

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

    
3735
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3736
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3737

    
3738
  if opts.key_name is None:
3739
    # Use server.pem
3740
    key_path = pathutils.NODED_CERT_FILE
3741
    cert_path = pathutils.NODED_CERT_FILE
3742
    assert opts.ca_pem is None
3743
  else:
3744
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3745
                                                 opts.key_name)
3746
    assert opts.ca_pem is not None
3747

    
3748
  for i in [key_path, cert_path]:
3749
    if not os.path.exists(i):
3750
      _Fail("File '%s' does not exist" % i)
3751

    
3752
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3753
  try:
3754
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3755
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3756
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3757

    
3758
    if opts.ca_pem is None:
3759
      # Use server.pem
3760
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3761
    else:
3762
      ca = opts.ca_pem
3763

    
3764
    # Write CA file
3765
    utils.WriteFile(ca_file, data=ca, mode=0400)
3766

    
3767
    cmd = [
3768
      pathutils.IMPORT_EXPORT_DAEMON,
3769
      status_file, mode,
3770
      "--key=%s" % key_path,
3771
      "--cert=%s" % cert_path,
3772
      "--ca=%s" % ca_file,
3773
      ]
3774

    
3775
    if host:
3776
      cmd.append("--host=%s" % host)
3777

    
3778
    if port:
3779
      cmd.append("--port=%s" % port)
3780

    
3781
    if opts.ipv6:
3782
      cmd.append("--ipv6")
3783
    else:
3784
      cmd.append("--ipv4")
3785

    
3786
    if opts.compress:
3787
      cmd.append("--compress=%s" % opts.compress)
3788

    
3789
    if opts.magic:
3790
      cmd.append("--magic=%s" % opts.magic)
3791

    
3792
    if exp_size is not None:
3793
      cmd.append("--expected-size=%s" % exp_size)
3794

    
3795
    if cmd_prefix:
3796
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3797

    
3798
    if cmd_suffix:
3799
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3800

    
3801
    if mode == constants.IEM_EXPORT:
3802
      # Retry connection a few times when connecting to remote peer
3803
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3804
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3805
    elif opts.connect_timeout is not None:
3806
      assert mode == constants.IEM_IMPORT
3807
      # Overall timeout for establishing connection while listening
3808
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3809

    
3810
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3811

    
3812
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3813
    # support for receiving a file descriptor for output
3814
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3815
                      output=logfile)
3816

    
3817
    # The import/export name is simply the status directory name
3818
    return os.path.basename(status_dir)
3819

    
3820
  except Exception:
3821
    shutil.rmtree(status_dir, ignore_errors=True)
3822
    raise
3823

    
3824

    
3825
def GetImportExportStatus(names):
3826
  """Returns import/export daemon status.
3827

3828
  @type names: sequence
3829
  @param names: List of names
3830
  @rtype: List of dicts
3831
  @return: Returns a list of the state of each named import/export or None if a
3832
           status couldn't be read
3833

3834
  """
3835
  result = []
3836

    
3837
  for name in names:
3838
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3839
                                 _IES_STATUS_FILE)
3840

    
3841
    try:
3842
      data = utils.ReadFile(status_file)
3843
    except EnvironmentError, err:
3844
      if err.errno != errno.ENOENT:
3845
        raise
3846
      data = None
3847

    
3848
    if not data:
3849
      result.append(None)
3850
      continue
3851

    
3852
    result.append(serializer.LoadJson(data))
3853

    
3854
  return result
3855

    
3856

    
3857
def AbortImportExport(name):
3858
  """Sends SIGTERM to a running import/export daemon.
3859

3860
  """
3861
  logging.info("Abort import/export %s", name)
3862

    
3863
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3864
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3865

    
3866
  if pid:
3867
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3868
                 name, pid)
3869
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3870

    
3871

    
3872
def CleanupImportExport(name):
3873
  """Cleanup after an import or export.
3874

3875
  If the import/export daemon is still running it's killed. Afterwards the
3876
  whole status directory is removed.
3877

3878
  """
3879
  logging.info("Finalizing import/export %s", name)
3880

    
3881
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3882

    
3883
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3884

    
3885
  if pid:
3886
    logging.info("Import/export %s is still running with PID %s",
3887
                 name, pid)
3888
    utils.KillProcess(pid, waitpid=False)
3889

    
3890
  shutil.rmtree(status_dir, ignore_errors=True)
3891

    
3892

    
3893
def _SetPhysicalId(target_node_uuid, nodes_ip, disks):
3894
  """Sets the correct physical ID on all passed disks.
3895

3896
  """
3897
  for cf in disks:
3898
    cf.SetPhysicalID(target_node_uuid, nodes_ip)
3899

    
3900

    
3901
def _FindDisks(target_node_uuid, nodes_ip, disks):
3902
  """Sets the physical ID on disks and returns the block devices.
3903

3904
  """
3905
  _SetPhysicalId(target_node_uuid, nodes_ip, disks)
3906

    
3907
  bdevs = []
3908

    
3909
  for cf in disks:
3910
    rd = _RecursiveFindBD(cf)
3911
    if rd is None:
3912
      _Fail("Can't find device %s", cf)
3913
    bdevs.append(rd)
3914
  return bdevs
3915

    
3916

    
3917
def DrbdDisconnectNet(target_node_uuid, nodes_ip, disks):
3918
  """Disconnects the network on a list of drbd devices.
3919

3920
  """
3921
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3922

    
3923
  # disconnect disks
3924
  for rd in bdevs:
3925
    try:
3926
      rd.DisconnectNet()
3927
    except errors.BlockDeviceError, err:
3928
      _Fail("Can't change network configuration to standalone mode: %s",
3929
            err, exc=True)
3930

    
3931

    
3932
def DrbdAttachNet(target_node_uuid, nodes_ip, disks, instance_name,
3933
                  multimaster):
3934
  """Attaches the network on a list of drbd devices.
3935

3936
  """
3937
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3938

    
3939
  if multimaster:
3940
    for idx, rd in enumerate(bdevs):
3941
      try:
3942
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3943
      except EnvironmentError, err:
3944
        _Fail("Can't create symlink: %s", err)
3945
  # reconnect disks, switch to new master configuration and if
3946
  # needed primary mode
3947
  for rd in bdevs:
3948
    try:
3949
      rd.AttachNet(multimaster)
3950
    except errors.BlockDeviceError, err:
3951
      _Fail("Can't change network configuration: %s", err)
3952

    
3953
  # wait until the disks are connected; we need to retry the re-attach
3954
  # if the device becomes standalone, as this might happen if the one
3955
  # node disconnects and reconnects in a different mode before the
3956
  # other node reconnects; in this case, one or both of the nodes will
3957
  # decide it has wrong configuration and switch to standalone
3958

    
3959
  def _Attach():
3960
    all_connected = True
3961

    
3962
    for rd in bdevs:
3963
      stats = rd.GetProcStatus()
3964

    
3965
      all_connected = (all_connected and
3966
                       (stats.is_connected or stats.is_in_resync))
3967

    
3968
      if stats.is_standalone:
3969
        # peer had different config info and this node became
3970
        # standalone, even though this should not happen with the
3971
        # new staged way of changing disk configs
3972
        try:
3973
          rd.AttachNet(multimaster)
3974
        except errors.BlockDeviceError, err:
3975
          _Fail("Can't change network configuration: %s", err)
3976

    
3977
    if not all_connected:
3978
      raise utils.RetryAgain()
3979

    
3980
  try:
3981
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3982
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3983
  except utils.RetryTimeout:
3984
    _Fail("Timeout in disk reconnecting")
3985

    
3986
  if multimaster:
3987
    # change to primary mode
3988
    for rd in bdevs:
3989
      try:
3990
        rd.Open()
3991
      except errors.BlockDeviceError, err:
3992
        _Fail("Can't change to primary mode: %s", err)
3993

    
3994

    
3995
def DrbdWaitSync(target_node_uuid, nodes_ip, disks):
3996
  """Wait until DRBDs have synchronized.
3997

3998
  """
3999
  def _helper(rd):
4000
    stats = rd.GetProcStatus()
4001
    if not (stats.is_connected or stats.is_in_resync):
4002
      raise utils.RetryAgain()
4003
    return stats
4004

    
4005
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
4006

    
4007
  min_resync = 100
4008
  alldone = True
4009
  for rd in bdevs:
4010
    try:
4011
      # poll each second for 15 seconds
4012
      stats = utils.Retry(_helper, 1, 15, args=[rd])
4013
    except utils.RetryTimeout:
4014
      stats = rd.GetProcStatus()
4015
      # last check
4016
      if not (stats.is_connected or stats.is_in_resync):
4017
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
4018
    alldone = alldone and (not stats.is_in_resync)
4019
    if stats.sync_percent is not None:
4020
      min_resync = min(min_resync, stats.sync_percent)
4021

    
4022
  return (alldone, min_resync)
4023

    
4024

    
4025
def DrbdNeedsActivation(target_node_uuid, nodes_ip, disks):
4026
  """Checks which of the passed disks needs activation and returns their UUIDs.
4027

4028
  """
4029
  _SetPhysicalId(target_node_uuid, nodes_ip, disks)
4030
  faulty_disks = []
4031

    
4032
  for disk in disks:
4033
    rd = _RecursiveFindBD(disk)
4034
    if rd is None:
4035
      faulty_disks.append(disk)
4036
      continue
4037

    
4038
    stats = rd.GetProcStatus()
4039
    if stats.is_standalone or stats.is_diskless:
4040
      faulty_disks.append(disk)
4041

    
4042
  return [disk.uuid for disk in faulty_disks]
4043

    
4044

    
4045
def GetDrbdUsermodeHelper():
4046
  """Returns DRBD usermode helper currently configured.
4047

4048
  """
4049
  try:
4050
    return drbd.DRBD8.GetUsermodeHelper()
4051
  except errors.BlockDeviceError, err:
4052
    _Fail(str(err))
4053

    
4054

    
4055
def PowercycleNode(hypervisor_type, hvparams=None):
4056
  """Hard-powercycle the node.
4057

4058
  Because we need to return first, and schedule the powercycle in the
4059
  background, we won't be able to report failures nicely.
4060

4061
  """
4062
  hyper = hypervisor.GetHypervisor(hypervisor_type)
4063
  try:
4064
    pid = os.fork()
4065
  except OSError:
4066
    # if we can't fork, we'll pretend that we're in the child process
4067
    pid = 0
4068
  if pid > 0:
4069
    return "Reboot scheduled in 5 seconds"
4070
  # ensure the child is running on ram
4071
  try:
4072
    utils.Mlockall()
4073
  except Exception: # pylint: disable=W0703
4074
    pass
4075
  time.sleep(5)
4076
  hyper.PowercycleNode(hvparams=hvparams)
4077

    
4078

    
4079
def _VerifyRestrictedCmdName(cmd):
4080
  """Verifies a restricted command name.
4081

4082
  @type cmd: string
4083
  @param cmd: Command name
4084
  @rtype: tuple; (boolean, string or None)
4085
  @return: The tuple's first element is the status; if C{False}, the second
4086
    element is an error message string, otherwise it's C{None}
4087

4088
  """
4089
  if not cmd.strip():
4090
    return (False, "Missing command name")
4091

    
4092
  if os.path.basename(cmd) != cmd:
4093
    return (False, "Invalid command name")
4094

    
4095
  if not constants.EXT_PLUGIN_MASK.match(cmd):
4096
    return (False, "Command name contains forbidden characters")
4097

    
4098
  return (True, None)
4099

    
4100

    
4101
def _CommonRestrictedCmdCheck(path, owner):
4102
  """Common checks for restricted command file system directories and files.
4103

4104
  @type path: string
4105
  @param path: Path to check
4106
  @param owner: C{None} or tuple containing UID and GID
4107
  @rtype: tuple; (boolean, string or C{os.stat} result)
4108
  @return: The tuple's first element is the status; if C{False}, the second
4109
    element is an error message string, otherwise it's the result of C{os.stat}
4110

4111
  """
4112
  if owner is None:
4113
    # Default to root as owner
4114
    owner = (0, 0)
4115

    
4116
  try:
4117
    st = os.stat(path)
4118
  except EnvironmentError, err:
4119
    return (False, "Can't stat(2) '%s': %s" % (path, err))
4120