Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 18397489

History | View | Annotate | Download (137.4 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
  if what.get(constants.NV_SHARED_FILE_STORAGE_PATH):
1144
    pathresult = filestorage.CheckFileStoragePath(
1145
        what[constants.NV_SHARED_FILE_STORAGE_PATH])
1146
    if pathresult:
1147
      result[constants.NV_SHARED_FILE_STORAGE_PATH] = pathresult
1148

    
1149
  return result
1150

    
1151

    
1152
def GetBlockDevSizes(devices):
1153
  """Return the size of the given block devices
1154

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

1162
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
1163

1164
  """
1165
  DEV_PREFIX = "/dev/"
1166
  blockdevs = {}
1167

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

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

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

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

    
1189

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

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

1201
        {'xenvg/test1': ('20.06', True, True)}
1202

1203
      in case of errors, a string is returned with the error
1204
      details.
1205

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

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

    
1233
  return lvs
1234

    
1235

    
1236
def ListVolumeGroups():
1237
  """List the volume groups and their size.
1238

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

1243
  """
1244
  return utils.ListVolumeGroups()
1245

    
1246

    
1247
def NodeVolumes():
1248
  """List all volumes on this node.
1249

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

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

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

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

    
1273
  def parse_dev(dev):
1274
    return dev.split("(")[0]
1275

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

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

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

    
1292

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

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

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

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

    
1308

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

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

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

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

    
1337

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

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

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

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

    
1364

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

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

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

1382
  """
1383
  output = {}
1384

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

    
1393
  return output
1394

    
1395

    
1396
def GetInstanceMigratable(instance):
1397
  """Computes whether an instance can be migrated.
1398

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

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

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

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

    
1419

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

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

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

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

1439
  """
1440
  output = {}
1441

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

    
1463
  return output
1464

    
1465

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

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

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

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

    
1493

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

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

1505
  """
1506
  inst_os = OSFromDisk(instance.os)
1507

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

    
1512
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1513

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

    
1525

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

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

1538
  """
1539
  inst_os = OSFromDisk(instance.os)
1540

    
1541
  rename_env = OSEnvironment(instance, inst_os, debug)
1542
  rename_env["OLD_INSTANCE_NAME"] = old_name
1543

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

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

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

    
1558

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

1562
  """
1563
  if _dir is None:
1564
    _dir = pathutils.DISK_LINKS_DIR
1565

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

    
1570

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

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

1577

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

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

    
1596
  return link_name
1597

    
1598

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

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

    
1611

    
1612
def _GatherAndLinkBlockDevs(instance):
1613
  """Set up an instance's block device(s).
1614

1615
  This is run on the primary node at instance startup. The block
1616
  devices must be already assembled.
1617

1618
  @type instance: L{objects.Instance}
1619
  @param instance: the instance whose disks we shoul assemble
1620
  @rtype: list
1621
  @return: list of (disk_object, device_path)
1622

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

    
1637
    block_devices.append((disk, link_name))
1638

    
1639
  return block_devices
1640

    
1641

    
1642
def StartInstance(instance, startup_paused, reason, store_reason=True):
1643
  """Start an instance.
1644

1645
  @type instance: L{objects.Instance}
1646
  @param instance: the instance object
1647
  @type startup_paused: bool
1648
  @param instance: pause instance at startup?
1649
  @type reason: list of reasons
1650
  @param reason: the reason trail for this startup
1651
  @type store_reason: boolean
1652
  @param store_reason: whether to store the shutdown reason trail on file
1653
  @rtype: None
1654

1655
  """
1656
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1657
                                                   instance.hvparams)
1658

    
1659
  if instance.name in running_instances:
1660
    logging.info("Instance %s already running, not starting", instance.name)
1661
    return
1662

    
1663
  try:
1664
    block_devices = _GatherAndLinkBlockDevs(instance)
1665
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1666
    hyper.StartInstance(instance, block_devices, startup_paused)
1667
    if store_reason:
1668
      _StoreInstReasonTrail(instance.name, reason)
1669
  except errors.BlockDeviceError, err:
1670
    _Fail("Block device error: %s", err, exc=True)
1671
  except errors.HypervisorError, err:
1672
    _RemoveBlockDevLinks(instance.name, instance.disks)
1673
    _Fail("Hypervisor error: %s", err, exc=True)
1674

    
1675

    
1676
def InstanceShutdown(instance, timeout, reason, store_reason=True):
1677
  """Shut an instance down.
1678

1679
  @note: this functions uses polling with a hardcoded timeout.
1680

1681
  @type instance: L{objects.Instance}
1682
  @param instance: the instance object
1683
  @type timeout: integer
1684
  @param timeout: maximum timeout for soft shutdown
1685
  @type reason: list of reasons
1686
  @param reason: the reason trail for this shutdown
1687
  @type store_reason: boolean
1688
  @param store_reason: whether to store the shutdown reason trail on file
1689
  @rtype: None
1690

1691
  """
1692
  hv_name = instance.hypervisor
1693
  hyper = hypervisor.GetHypervisor(hv_name)
1694
  iname = instance.name
1695

    
1696
  if instance.name not in hyper.ListInstances(instance.hvparams):
1697
    logging.info("Instance %s not running, doing nothing", iname)
1698
    return
1699

    
1700
  class _TryShutdown:
1701
    def __init__(self):
1702
      self.tried_once = False
1703

    
1704
    def __call__(self):
1705
      if iname not in hyper.ListInstances(instance.hvparams):
1706
        return
1707

    
1708
      try:
1709
        hyper.StopInstance(instance, retry=self.tried_once)
1710
        if store_reason:
1711
          _StoreInstReasonTrail(instance.name, reason)
1712
      except errors.HypervisorError, err:
1713
        if iname not in hyper.ListInstances(instance.hvparams):
1714
          # if the instance is no longer existing, consider this a
1715
          # success and go to cleanup
1716
          return
1717

    
1718
        _Fail("Failed to stop instance %s: %s", iname, err)
1719

    
1720
      self.tried_once = True
1721

    
1722
      raise utils.RetryAgain()
1723

    
1724
  try:
1725
    utils.Retry(_TryShutdown(), 5, timeout)
1726
  except utils.RetryTimeout:
1727
    # the shutdown did not succeed
1728
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1729

    
1730
    try:
1731
      hyper.StopInstance(instance, force=True)
1732
    except errors.HypervisorError, err:
1733
      if iname in hyper.ListInstances(instance.hvparams):
1734
        # only raise an error if the instance still exists, otherwise
1735
        # the error could simply be "instance ... unknown"!
1736
        _Fail("Failed to force stop instance %s: %s", iname, err)
1737

    
1738
    time.sleep(1)
1739

    
1740
    if iname in hyper.ListInstances(instance.hvparams):
1741
      _Fail("Could not shutdown instance %s even by destroy", iname)
1742

    
1743
  try:
1744
    hyper.CleanupInstance(instance.name)
1745
  except errors.HypervisorError, err:
1746
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1747

    
1748
  _RemoveBlockDevLinks(iname, instance.disks)
1749

    
1750

    
1751
def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1752
  """Reboot an instance.
1753

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

1773
  """
1774
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1775
                                                   instance.hvparams)
1776

    
1777
  if instance.name not in running_instances:
1778
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1779

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

    
1797

    
1798
def InstanceBalloonMemory(instance, memory):
1799
  """Resize an instance's memory.
1800

1801
  @type instance: L{objects.Instance}
1802
  @param instance: the instance object
1803
  @type memory: int
1804
  @param memory: new memory amount in MB
1805
  @rtype: None
1806

1807
  """
1808
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1809
  running = hyper.ListInstances(instance.hvparams)
1810
  if instance.name not in running:
1811
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1812
    return
1813
  try:
1814
    hyper.BalloonInstanceMemory(instance, memory)
1815
  except errors.HypervisorError, err:
1816
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1817

    
1818

    
1819
def MigrationInfo(instance):
1820
  """Gather information about an instance to be migrated.
1821

1822
  @type instance: L{objects.Instance}
1823
  @param instance: the instance definition
1824

1825
  """
1826
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1827
  try:
1828
    info = hyper.MigrationInfo(instance)
1829
  except errors.HypervisorError, err:
1830
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1831
  return info
1832

    
1833

    
1834
def AcceptInstance(instance, info, target):
1835
  """Prepare the node to accept an instance.
1836

1837
  @type instance: L{objects.Instance}
1838
  @param instance: the instance definition
1839
  @type info: string/data (opaque)
1840
  @param info: migration information, from the source node
1841
  @type target: string
1842
  @param target: target host (usually ip), on this node
1843

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

    
1854
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1855
  try:
1856
    hyper.AcceptInstance(instance, info, target)
1857
  except errors.HypervisorError, err:
1858
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1859
      _RemoveBlockDevLinks(instance.name, instance.disks)
1860
    _Fail("Failed to accept instance: %s", err, exc=True)
1861

    
1862

    
1863
def FinalizeMigrationDst(instance, info, success):
1864
  """Finalize any preparation to accept an instance.
1865

1866
  @type instance: L{objects.Instance}
1867
  @param instance: the instance definition
1868
  @type info: string/data (opaque)
1869
  @param info: migration information, from the source node
1870
  @type success: boolean
1871
  @param success: whether the migration was a success or a failure
1872

1873
  """
1874
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1875
  try:
1876
    hyper.FinalizeMigrationDst(instance, info, success)
1877
  except errors.HypervisorError, err:
1878
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1879

    
1880

    
1881
def MigrateInstance(cluster_name, instance, target, live):
1882
  """Migrates an instance to another node.
1883

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

1895
  """
1896
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1897

    
1898
  try:
1899
    hyper.MigrateInstance(cluster_name, instance, target, live)
1900
  except errors.HypervisorError, err:
1901
    _Fail("Failed to migrate instance: %s", err, exc=True)
1902

    
1903

    
1904
def FinalizeMigrationSource(instance, success, live):
1905
  """Finalize the instance migration on the source node.
1906

1907
  @type instance: L{objects.Instance}
1908
  @param instance: the instance definition of the migrated instance
1909
  @type success: bool
1910
  @param success: whether the migration succeeded or not
1911
  @type live: bool
1912
  @param live: whether the user requested a live migration or not
1913
  @raise RPCFail: If the execution fails for some reason
1914

1915
  """
1916
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1917

    
1918
  try:
1919
    hyper.FinalizeMigrationSource(instance, success, live)
1920
  except Exception, err:  # pylint: disable=W0703
1921
    _Fail("Failed to finalize the migration on the source node: %s", err,
1922
          exc=True)
1923

    
1924

    
1925
def GetMigrationStatus(instance):
1926
  """Get the migration status
1927

1928
  @type instance: L{objects.Instance}
1929
  @param instance: the instance that is being migrated
1930
  @rtype: L{objects.MigrationStatus}
1931
  @return: the status of the current migration (one of
1932
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1933
           progress info that can be retrieved from the hypervisor
1934
  @raise RPCFail: If the migration status cannot be retrieved
1935

1936
  """
1937
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1938
  try:
1939
    return hyper.GetMigrationStatus(instance)
1940
  except Exception, err:  # pylint: disable=W0703
1941
    _Fail("Failed to get migration status: %s", err, exc=True)
1942

    
1943

    
1944
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
1945
  """Creates a block device for an instance.
1946

1947
  @type disk: L{objects.Disk}
1948
  @param disk: the object describing the disk we should create
1949
  @type size: int
1950
  @param size: the size of the physical underlying device, in MiB
1951
  @type owner: str
1952
  @param owner: the name of the instance for which disk is created,
1953
      used for device cache data
1954
  @type on_primary: boolean
1955
  @param on_primary:  indicates if it is the primary node or not
1956
  @type info: string
1957
  @param info: string that will be sent to the physical device
1958
      creation, used for example to set (LVM) tags on LVs
1959
  @type excl_stor: boolean
1960
  @param excl_stor: Whether exclusive_storage is active
1961

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

1966
  """
1967
  # TODO: remove the obsolete "size" argument
1968
  # pylint: disable=W0613
1969
  clist = []
1970
  if disk.children:
1971
    for child in disk.children:
1972
      try:
1973
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1974
      except errors.BlockDeviceError, err:
1975
        _Fail("Can't assemble device %s: %s", child, err)
1976
      if on_primary or disk.AssembleOnSecondary():
1977
        # we need the children open in case the device itself has to
1978
        # be assembled
1979
        try:
1980
          # pylint: disable=E1103
1981
          crdev.Open()
1982
        except errors.BlockDeviceError, err:
1983
          _Fail("Can't make child '%s' read-write: %s", child, err)
1984
      clist.append(crdev)
1985

    
1986
  try:
1987
    device = bdev.Create(disk, clist, excl_stor)
1988
  except errors.BlockDeviceError, err:
1989
    _Fail("Can't create block device: %s", err)
1990

    
1991
  if on_primary or disk.AssembleOnSecondary():
1992
    try:
1993
      device.Assemble()
1994
    except errors.BlockDeviceError, err:
1995
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1996
    if on_primary or disk.OpenOnSecondary():
1997
      try:
1998
        device.Open(force=True)
1999
      except errors.BlockDeviceError, err:
2000
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
2001
    DevCacheManager.UpdateCache(device.dev_path, owner,
2002
                                on_primary, disk.iv_name)
2003

    
2004
  device.SetInfo(info)
2005

    
2006
  return device.unique_id
2007

    
2008

    
2009
def _WipeDevice(path, offset, size):
2010
  """This function actually wipes the device.
2011

2012
  @param path: The path to the device to wipe
2013
  @param offset: The offset in MiB in the file
2014
  @param size: The size in MiB to write
2015

2016
  """
2017
  # Internal sizes are always in Mebibytes; if the following "dd" command
2018
  # should use a different block size the offset and size given to this
2019
  # function must be adjusted accordingly before being passed to "dd".
2020
  block_size = 1024 * 1024
2021

    
2022
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
2023
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
2024
         "count=%d" % size]
2025
  result = utils.RunCmd(cmd)
2026

    
2027
  if result.failed:
2028
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
2029
          result.fail_reason, result.output)
2030

    
2031

    
2032
def BlockdevWipe(disk, offset, size):
2033
  """Wipes a block device.
2034

2035
  @type disk: L{objects.Disk}
2036
  @param disk: the disk object we want to wipe
2037
  @type offset: int
2038
  @param offset: The offset in MiB in the file
2039
  @type size: int
2040
  @param size: The size in MiB to write
2041

2042
  """
2043
  try:
2044
    rdev = _RecursiveFindBD(disk)
2045
  except errors.BlockDeviceError:
2046
    rdev = None
2047

    
2048
  if not rdev:
2049
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
2050

    
2051
  # Do cross verify some of the parameters
2052
  if offset < 0:
2053
    _Fail("Negative offset")
2054
  if size < 0:
2055
    _Fail("Negative size")
2056
  if offset > rdev.size:
2057
    _Fail("Offset is bigger than device size")
2058
  if (offset + size) > rdev.size:
2059
    _Fail("The provided offset and size to wipe is bigger than device size")
2060

    
2061
  _WipeDevice(rdev.dev_path, offset, size)
2062

    
2063

    
2064
def BlockdevPauseResumeSync(disks, pause):
2065
  """Pause or resume the sync of the block device.
2066

2067
  @type disks: list of L{objects.Disk}
2068
  @param disks: the disks object we want to pause/resume
2069
  @type pause: bool
2070
  @param pause: Wheater to pause or resume
2071

2072
  """
2073
  success = []
2074
  for disk in disks:
2075
    try:
2076
      rdev = _RecursiveFindBD(disk)
2077
    except errors.BlockDeviceError:
2078
      rdev = None
2079

    
2080
    if not rdev:
2081
      success.append((False, ("Cannot change sync for device %s:"
2082
                              " device not found" % disk.iv_name)))
2083
      continue
2084

    
2085
    result = rdev.PauseResumeSync(pause)
2086

    
2087
    if result:
2088
      success.append((result, None))
2089
    else:
2090
      if pause:
2091
        msg = "Pause"
2092
      else:
2093
        msg = "Resume"
2094
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
2095

    
2096
  return success
2097

    
2098

    
2099
def BlockdevRemove(disk):
2100
  """Remove a block device.
2101

2102
  @note: This is intended to be called recursively.
2103

2104
  @type disk: L{objects.Disk}
2105
  @param disk: the disk object we should remove
2106
  @rtype: boolean
2107
  @return: the success of the operation
2108

2109
  """
2110
  msgs = []
2111
  try:
2112
    rdev = _RecursiveFindBD(disk)
2113
  except errors.BlockDeviceError, err:
2114
    # probably can't attach
2115
    logging.info("Can't attach to device %s in remove", disk)
2116
    rdev = None
2117
  if rdev is not None:
2118
    r_path = rdev.dev_path
2119
    try:
2120
      rdev.Remove()
2121
    except errors.BlockDeviceError, err:
2122
      msgs.append(str(err))
2123
    if not msgs:
2124
      DevCacheManager.RemoveCache(r_path)
2125

    
2126
  if disk.children:
2127
    for child in disk.children:
2128
      try:
2129
        BlockdevRemove(child)
2130
      except RPCFail, err:
2131
        msgs.append(str(err))
2132

    
2133
  if msgs:
2134
    _Fail("; ".join(msgs))
2135

    
2136

    
2137
def _RecursiveAssembleBD(disk, owner, as_primary):
2138
  """Activate a block device for an instance.
2139

2140
  This is run on the primary and secondary nodes for an instance.
2141

2142
  @note: this function is called recursively.
2143

2144
  @type disk: L{objects.Disk}
2145
  @param disk: the disk we try to assemble
2146
  @type owner: str
2147
  @param owner: the name of the instance which owns the disk
2148
  @type as_primary: boolean
2149
  @param as_primary: if we should make the block device
2150
      read/write
2151

2152
  @return: the assembled device or None (in case no device
2153
      was assembled)
2154
  @raise errors.BlockDeviceError: in case there is an error
2155
      during the activation of the children or the device
2156
      itself
2157

2158
  """
2159
  children = []
2160
  if disk.children:
2161
    mcn = disk.ChildrenNeeded()
2162
    if mcn == -1:
2163
      mcn = 0 # max number of Nones allowed
2164
    else:
2165
      mcn = len(disk.children) - mcn # max number of Nones
2166
    for chld_disk in disk.children:
2167
      try:
2168
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
2169
      except errors.BlockDeviceError, err:
2170
        if children.count(None) >= mcn:
2171
          raise
2172
        cdev = None
2173
        logging.error("Error in child activation (but continuing): %s",
2174
                      str(err))
2175
      children.append(cdev)
2176

    
2177
  if as_primary or disk.AssembleOnSecondary():
2178
    r_dev = bdev.Assemble(disk, children)
2179
    result = r_dev
2180
    if as_primary or disk.OpenOnSecondary():
2181
      r_dev.Open()
2182
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
2183
                                as_primary, disk.iv_name)
2184

    
2185
  else:
2186
    result = True
2187
  return result
2188

    
2189

    
2190
def BlockdevAssemble(disk, owner, as_primary, idx):
2191
  """Activate a block device for an instance.
2192

2193
  This is a wrapper over _RecursiveAssembleBD.
2194

2195
  @rtype: str or boolean
2196
  @return: a C{/dev/...} path for primary nodes, and
2197
      C{True} for secondary nodes
2198

2199
  """
2200
  try:
2201
    result = _RecursiveAssembleBD(disk, owner, as_primary)
2202
    if isinstance(result, BlockDev):
2203
      # pylint: disable=E1103
2204
      result = result.dev_path
2205
      if as_primary:
2206
        _SymlinkBlockDev(owner, result, idx)
2207
  except errors.BlockDeviceError, err:
2208
    _Fail("Error while assembling disk: %s", err, exc=True)
2209
  except OSError, err:
2210
    _Fail("Error while symlinking disk: %s", err, exc=True)
2211

    
2212
  return result
2213

    
2214

    
2215
def BlockdevShutdown(disk):
2216
  """Shut down a block device.
2217

2218
  First, if the device is assembled (Attach() is successful), then
2219
  the device is shutdown. Then the children of the device are
2220
  shutdown.
2221

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

2226
  @type disk: L{objects.Disk}
2227
  @param disk: the description of the disk we should
2228
      shutdown
2229
  @rtype: None
2230

2231
  """
2232
  msgs = []
2233
  r_dev = _RecursiveFindBD(disk)
2234
  if r_dev is not None:
2235
    r_path = r_dev.dev_path
2236
    try:
2237
      r_dev.Shutdown()
2238
      DevCacheManager.RemoveCache(r_path)
2239
    except errors.BlockDeviceError, err:
2240
      msgs.append(str(err))
2241

    
2242
  if disk.children:
2243
    for child in disk.children:
2244
      try:
2245
        BlockdevShutdown(child)
2246
      except RPCFail, err:
2247
        msgs.append(str(err))
2248

    
2249
  if msgs:
2250
    _Fail("; ".join(msgs))
2251

    
2252

    
2253
def BlockdevAddchildren(parent_cdev, new_cdevs):
2254
  """Extend a mirrored block device.
2255

2256
  @type parent_cdev: L{objects.Disk}
2257
  @param parent_cdev: the disk to which we should add children
2258
  @type new_cdevs: list of L{objects.Disk}
2259
  @param new_cdevs: the list of children which we should add
2260
  @rtype: None
2261

2262
  """
2263
  parent_bdev = _RecursiveFindBD(parent_cdev)
2264
  if parent_bdev is None:
2265
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
2266
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
2267
  if new_bdevs.count(None) > 0:
2268
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
2269
  parent_bdev.AddChildren(new_bdevs)
2270

    
2271

    
2272
def BlockdevRemovechildren(parent_cdev, new_cdevs):
2273
  """Shrink a mirrored block device.
2274

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

2281
  """
2282
  parent_bdev = _RecursiveFindBD(parent_cdev)
2283
  if parent_bdev is None:
2284
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
2285
  devs = []
2286
  for disk in new_cdevs:
2287
    rpath = disk.StaticDevPath()
2288
    if rpath is None:
2289
      bd = _RecursiveFindBD(disk)
2290
      if bd is None:
2291
        _Fail("Can't find device %s while removing children", disk)
2292
      else:
2293
        devs.append(bd.dev_path)
2294
    else:
2295
      if not utils.IsNormAbsPath(rpath):
2296
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
2297
      devs.append(rpath)
2298
  parent_bdev.RemoveChildren(devs)
2299

    
2300

    
2301
def BlockdevGetmirrorstatus(disks):
2302
  """Get the mirroring status of a list of devices.
2303

2304
  @type disks: list of L{objects.Disk}
2305
  @param disks: the list of disks which we should query
2306
  @rtype: disk
2307
  @return: List of L{objects.BlockDevStatus}, one for each disk
2308
  @raise errors.BlockDeviceError: if any of the disks cannot be
2309
      found
2310

2311
  """
2312
  stats = []
2313
  for dsk in disks:
2314
    rbd = _RecursiveFindBD(dsk)
2315
    if rbd is None:
2316
      _Fail("Can't find device %s", dsk)
2317

    
2318
    stats.append(rbd.CombinedSyncStatus())
2319

    
2320
  return stats
2321

    
2322

    
2323
def BlockdevGetmirrorstatusMulti(disks):
2324
  """Get the mirroring status of a list of devices.
2325

2326
  @type disks: list of L{objects.Disk}
2327
  @param disks: the list of disks which we should query
2328
  @rtype: disk
2329
  @return: List of tuples, (bool, status), one for each disk; bool denotes
2330
    success/failure, status is L{objects.BlockDevStatus} on success, string
2331
    otherwise
2332

2333
  """
2334
  result = []
2335
  for disk in disks:
2336
    try:
2337
      rbd = _RecursiveFindBD(disk)
2338
      if rbd is None:
2339
        result.append((False, "Can't find device %s" % disk))
2340
        continue
2341

    
2342
      status = rbd.CombinedSyncStatus()
2343
    except errors.BlockDeviceError, err:
2344
      logging.exception("Error while getting disk status")
2345
      result.append((False, str(err)))
2346
    else:
2347
      result.append((True, status))
2348

    
2349
  assert len(disks) == len(result)
2350

    
2351
  return result
2352

    
2353

    
2354
def _RecursiveFindBD(disk):
2355
  """Check if a device is activated.
2356

2357
  If so, return information about the real device.
2358

2359
  @type disk: L{objects.Disk}
2360
  @param disk: the disk object we need to find
2361

2362
  @return: None if the device can't be found,
2363
      otherwise the device instance
2364

2365
  """
2366
  children = []
2367
  if disk.children:
2368
    for chdisk in disk.children:
2369
      children.append(_RecursiveFindBD(chdisk))
2370

    
2371
  return bdev.FindDevice(disk, children)
2372

    
2373

    
2374
def _OpenRealBD(disk):
2375
  """Opens the underlying block device of a disk.
2376

2377
  @type disk: L{objects.Disk}
2378
  @param disk: the disk object we want to open
2379

2380
  """
2381
  real_disk = _RecursiveFindBD(disk)
2382
  if real_disk is None:
2383
    _Fail("Block device '%s' is not set up", disk)
2384

    
2385
  real_disk.Open()
2386

    
2387
  return real_disk
2388

    
2389

    
2390
def BlockdevFind(disk):
2391
  """Check if a device is activated.
2392

2393
  If it is, return information about the real device.
2394

2395
  @type disk: L{objects.Disk}
2396
  @param disk: the disk to find
2397
  @rtype: None or objects.BlockDevStatus
2398
  @return: None if the disk cannot be found, otherwise a the current
2399
           information
2400

2401
  """
2402
  try:
2403
    rbd = _RecursiveFindBD(disk)
2404
  except errors.BlockDeviceError, err:
2405
    _Fail("Failed to find device: %s", err, exc=True)
2406

    
2407
  if rbd is None:
2408
    return None
2409

    
2410
  return rbd.GetSyncStatus()
2411

    
2412

    
2413
def BlockdevGetdimensions(disks):
2414
  """Computes the size of the given disks.
2415

2416
  If a disk is not found, returns None instead.
2417

2418
  @type disks: list of L{objects.Disk}
2419
  @param disks: the list of disk to compute the size for
2420
  @rtype: list
2421
  @return: list with elements None if the disk cannot be found,
2422
      otherwise the pair (size, spindles), where spindles is None if the
2423
      device doesn't support that
2424

2425
  """
2426
  result = []
2427
  for cf in disks:
2428
    try:
2429
      rbd = _RecursiveFindBD(cf)
2430
    except errors.BlockDeviceError:
2431
      result.append(None)
2432
      continue
2433
    if rbd is None:
2434
      result.append(None)
2435
    else:
2436
      result.append(rbd.GetActualDimensions())
2437
  return result
2438

    
2439

    
2440
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2441
  """Export a block device to a remote node.
2442

2443
  @type disk: L{objects.Disk}
2444
  @param disk: the description of the disk to export
2445
  @type dest_node: str
2446
  @param dest_node: the destination node to export to
2447
  @type dest_path: str
2448
  @param dest_path: the destination path on the target node
2449
  @type cluster_name: str
2450
  @param cluster_name: the cluster name, needed for SSH hostalias
2451
  @rtype: None
2452

2453
  """
2454
  real_disk = _OpenRealBD(disk)
2455

    
2456
  # the block size on the read dd is 1MiB to match our units
2457
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2458
                               "dd if=%s bs=1048576 count=%s",
2459
                               real_disk.dev_path, str(disk.size))
2460

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

    
2470
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2471
                                                   constants.SSH_LOGIN_USER,
2472
                                                   destcmd)
2473

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

    
2477
  result = utils.RunCmd(["bash", "-c", command])
2478

    
2479
  if result.failed:
2480
    _Fail("Disk copy command '%s' returned error: %s"
2481
          " output: %s", command, result.fail_reason, result.output)
2482

    
2483

    
2484
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2485
  """Write a file to the filesystem.
2486

2487
  This allows the master to overwrite(!) a file. It will only perform
2488
  the operation if the file belongs to a list of configuration files.
2489

2490
  @type file_name: str
2491
  @param file_name: the target file name
2492
  @type data: str
2493
  @param data: the new contents of the file
2494
  @type mode: int
2495
  @param mode: the mode to give the file (can be None)
2496
  @type uid: string
2497
  @param uid: the owner of the file
2498
  @type gid: string
2499
  @param gid: the group of the file
2500
  @type atime: float
2501
  @param atime: the atime to set on the file (can be None)
2502
  @type mtime: float
2503
  @param mtime: the mtime to set on the file (can be None)
2504
  @rtype: None
2505

2506
  """
2507
  file_name = vcluster.LocalizeVirtualPath(file_name)
2508

    
2509
  if not os.path.isabs(file_name):
2510
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2511

    
2512
  if file_name not in _ALLOWED_UPLOAD_FILES:
2513
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2514
          file_name)
2515

    
2516
  raw_data = _Decompress(data)
2517

    
2518
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2519
    _Fail("Invalid username/groupname type")
2520

    
2521
  getents = runtime.GetEnts()
2522
  uid = getents.LookupUser(uid)
2523
  gid = getents.LookupGroup(gid)
2524

    
2525
  utils.SafeWriteFile(file_name, None,
2526
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2527
                      atime=atime, mtime=mtime)
2528

    
2529

    
2530
def RunOob(oob_program, command, node, timeout):
2531
  """Executes oob_program with given command on given node.
2532

2533
  @param oob_program: The path to the executable oob_program
2534
  @param command: The command to invoke on oob_program
2535
  @param node: The node given as an argument to the program
2536
  @param timeout: Timeout after which we kill the oob program
2537

2538
  @return: stdout
2539
  @raise RPCFail: If execution fails for some reason
2540

2541
  """
2542
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2543

    
2544
  if result.failed:
2545
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2546
          result.fail_reason, result.output)
2547

    
2548
  return result.stdout
2549

    
2550

    
2551
def _OSOndiskAPIVersion(os_dir):
2552
  """Compute and return the API version of a given OS.
2553

2554
  This function will try to read the API version of the OS residing in
2555
  the 'os_dir' directory.
2556

2557
  @type os_dir: str
2558
  @param os_dir: the directory in which we should look for the OS
2559
  @rtype: tuple
2560
  @return: tuple (status, data) with status denoting the validity and
2561
      data holding either the vaid versions or an error message
2562

2563
  """
2564
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2565

    
2566
  try:
2567
    st = os.stat(api_file)
2568
  except EnvironmentError, err:
2569
    return False, ("Required file '%s' not found under path %s: %s" %
2570
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2571

    
2572
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2573
    return False, ("File '%s' in %s is not a regular file" %
2574
                   (constants.OS_API_FILE, os_dir))
2575

    
2576
  try:
2577
    api_versions = utils.ReadFile(api_file).splitlines()
2578
  except EnvironmentError, err:
2579
    return False, ("Error while reading the API version file at %s: %s" %
2580
                   (api_file, utils.ErrnoOrStr(err)))
2581

    
2582
  try:
2583
    api_versions = [int(version.strip()) for version in api_versions]
2584
  except (TypeError, ValueError), err:
2585
    return False, ("API version(s) can't be converted to integer: %s" %
2586
                   str(err))
2587

    
2588
  return True, api_versions
2589

    
2590

    
2591
def DiagnoseOS(top_dirs=None):
2592
  """Compute the validity for all OSes.
2593

2594
  @type top_dirs: list
2595
  @param top_dirs: the list of directories in which to
2596
      search (if not given defaults to
2597
      L{pathutils.OS_SEARCH_PATH})
2598
  @rtype: list of L{objects.OS}
2599
  @return: a list of tuples (name, path, status, diagnose, variants,
2600
      parameters, api_version) for all (potential) OSes under all
2601
      search paths, where:
2602
          - name is the (potential) OS name
2603
          - path is the full path to the OS
2604
          - status True/False is the validity of the OS
2605
          - diagnose is the error message for an invalid OS, otherwise empty
2606
          - variants is a list of supported OS variants, if any
2607
          - parameters is a list of (name, help) parameters, if any
2608
          - api_version is a list of support OS API versions
2609

2610
  """
2611
  if top_dirs is None:
2612
    top_dirs = pathutils.OS_SEARCH_PATH
2613

    
2614
  result = []
2615
  for dir_name in top_dirs:
2616
    if os.path.isdir(dir_name):
2617
      try:
2618
        f_names = utils.ListVisibleFiles(dir_name)
2619
      except EnvironmentError, err:
2620
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2621
        break
2622
      for name in f_names:
2623
        os_path = utils.PathJoin(dir_name, name)
2624
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2625
        if status:
2626
          diagnose = ""
2627
          variants = os_inst.supported_variants
2628
          parameters = os_inst.supported_parameters
2629
          api_versions = os_inst.api_versions
2630
        else:
2631
          diagnose = os_inst
2632
          variants = parameters = api_versions = []
2633
        result.append((name, os_path, status, diagnose, variants,
2634
                       parameters, api_versions))
2635

    
2636
  return result
2637

    
2638

    
2639
def _TryOSFromDisk(name, base_dir=None):
2640
  """Create an OS instance from disk.
2641

2642
  This function will return an OS instance if the given name is a
2643
  valid OS name.
2644

2645
  @type base_dir: string
2646
  @keyword base_dir: Base directory containing OS installations.
2647
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2648
  @rtype: tuple
2649
  @return: success and either the OS instance if we find a valid one,
2650
      or error message
2651

2652
  """
2653
  if base_dir is None:
2654
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2655
  else:
2656
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2657

    
2658
  if os_dir is None:
2659
    return False, "Directory for OS %s not found in search path" % name
2660

    
2661
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2662
  if not status:
2663
    # push the error up
2664
    return status, api_versions
2665

    
2666
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2667
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2668
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2669

    
2670
  # OS Files dictionary, we will populate it with the absolute path
2671
  # names; if the value is True, then it is a required file, otherwise
2672
  # an optional one
2673
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2674

    
2675
  if max(api_versions) >= constants.OS_API_V15:
2676
    os_files[constants.OS_VARIANTS_FILE] = False
2677

    
2678
  if max(api_versions) >= constants.OS_API_V20:
2679
    os_files[constants.OS_PARAMETERS_FILE] = True
2680
  else:
2681
    del os_files[constants.OS_SCRIPT_VERIFY]
2682

    
2683
  for (filename, required) in os_files.items():
2684
    os_files[filename] = utils.PathJoin(os_dir, filename)
2685

    
2686
    try:
2687
      st = os.stat(os_files[filename])
2688
    except EnvironmentError, err:
2689
      if err.errno == errno.ENOENT and not required:
2690
        del os_files[filename]
2691
        continue
2692
      return False, ("File '%s' under path '%s' is missing (%s)" %
2693
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2694

    
2695
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2696
      return False, ("File '%s' under path '%s' is not a regular file" %
2697
                     (filename, os_dir))
2698

    
2699
    if filename in constants.OS_SCRIPTS:
2700
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2701
        return False, ("File '%s' under path '%s' is not executable" %
2702
                       (filename, os_dir))
2703

    
2704
  variants = []
2705
  if constants.OS_VARIANTS_FILE in os_files:
2706
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2707
    try:
2708
      variants = \
2709
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2710
    except EnvironmentError, err:
2711
      # we accept missing files, but not other errors
2712
      if err.errno != errno.ENOENT:
2713
        return False, ("Error while reading the OS variants file at %s: %s" %
2714
                       (variants_file, utils.ErrnoOrStr(err)))
2715

    
2716
  parameters = []
2717
  if constants.OS_PARAMETERS_FILE in os_files:
2718
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2719
    try:
2720
      parameters = utils.ReadFile(parameters_file).splitlines()
2721
    except EnvironmentError, err:
2722
      return False, ("Error while reading the OS parameters file at %s: %s" %
2723
                     (parameters_file, utils.ErrnoOrStr(err)))
2724
    parameters = [v.split(None, 1) for v in parameters]
2725

    
2726
  os_obj = objects.OS(name=name, path=os_dir,
2727
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2728
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2729
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2730
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2731
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2732
                                                 None),
2733
                      supported_variants=variants,
2734
                      supported_parameters=parameters,
2735
                      api_versions=api_versions)
2736
  return True, os_obj
2737

    
2738

    
2739
def OSFromDisk(name, base_dir=None):
2740
  """Create an OS instance from disk.
2741

2742
  This function will return an OS instance if the given name is a
2743
  valid OS name. Otherwise, it will raise an appropriate
2744
  L{RPCFail} exception, detailing why this is not a valid OS.
2745

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

2749
  @type base_dir: string
2750
  @keyword base_dir: Base directory containing OS installations.
2751
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2752
  @rtype: L{objects.OS}
2753
  @return: the OS instance if we find a valid one
2754
  @raise RPCFail: if we don't find a valid OS
2755

2756
  """
2757
  name_only = objects.OS.GetName(name)
2758
  status, payload = _TryOSFromDisk(name_only, base_dir)
2759

    
2760
  if not status:
2761
    _Fail(payload)
2762

    
2763
  return payload
2764

    
2765

    
2766
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2767
  """Calculate the basic environment for an os script.
2768

2769
  @type os_name: str
2770
  @param os_name: full operating system name (including variant)
2771
  @type inst_os: L{objects.OS}
2772
  @param inst_os: operating system for which the environment is being built
2773
  @type os_params: dict
2774
  @param os_params: the OS parameters
2775
  @type debug: integer
2776
  @param debug: debug level (0 or 1, for OS Api 10)
2777
  @rtype: dict
2778
  @return: dict of environment variables
2779
  @raise errors.BlockDeviceError: if the block device
2780
      cannot be found
2781

2782
  """
2783
  result = {}
2784
  api_version = \
2785
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2786
  result["OS_API_VERSION"] = "%d" % api_version
2787
  result["OS_NAME"] = inst_os.name
2788
  result["DEBUG_LEVEL"] = "%d" % debug
2789

    
2790
  # OS variants
2791
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2792
    variant = objects.OS.GetVariant(os_name)
2793
    if not variant:
2794
      variant = inst_os.supported_variants[0]
2795
  else:
2796
    variant = ""
2797
  result["OS_VARIANT"] = variant
2798

    
2799
  # OS params
2800
  for pname, pvalue in os_params.items():
2801
    result["OSP_%s" % pname.upper()] = pvalue
2802

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

    
2808
  return result
2809

    
2810

    
2811
def OSEnvironment(instance, inst_os, debug=0):
2812
  """Calculate the environment for an os script.
2813

2814
  @type instance: L{objects.Instance}
2815
  @param instance: target instance for the os script run
2816
  @type inst_os: L{objects.OS}
2817
  @param inst_os: operating system for which the environment is being built
2818
  @type debug: integer
2819
  @param debug: debug level (0 or 1, for OS Api 10)
2820
  @rtype: dict
2821
  @return: dict of environment variables
2822
  @raise errors.BlockDeviceError: if the block device
2823
      cannot be found
2824

2825
  """
2826
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2827

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

    
2831
  result["HYPERVISOR"] = instance.hypervisor
2832
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2833
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2834
  result["INSTANCE_SECONDARY_NODES"] = \
2835
      ("%s" % " ".join(instance.secondary_nodes))
2836

    
2837
  # Disks
2838
  for idx, disk in enumerate(instance.disks):
2839
    real_disk = _OpenRealBD(disk)
2840
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2841
    result["DISK_%d_ACCESS" % idx] = disk.mode
2842
    result["DISK_%d_UUID" % idx] = disk.uuid
2843
    if disk.name:
2844
      result["DISK_%d_NAME" % idx] = disk.name
2845
    if constants.HV_DISK_TYPE in instance.hvparams:
2846
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2847
        instance.hvparams[constants.HV_DISK_TYPE]
2848
    if disk.dev_type in constants.LDS_BLOCK:
2849
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2850
    elif disk.dev_type == constants.LD_FILE:
2851
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2852
        "file:%s" % disk.physical_id[0]
2853

    
2854
  # NICs
2855
  for idx, nic in enumerate(instance.nics):
2856
    result["NIC_%d_MAC" % idx] = nic.mac
2857
    result["NIC_%d_UUID" % idx] = nic.uuid
2858
    if nic.name:
2859
      result["NIC_%d_NAME" % idx] = nic.name
2860
    if nic.ip:
2861
      result["NIC_%d_IP" % idx] = nic.ip
2862
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2863
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2864
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2865
    if nic.nicparams[constants.NIC_LINK]:
2866
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2867
    if nic.netinfo:
2868
      nobj = objects.Network.FromDict(nic.netinfo)
2869
      result.update(nobj.HooksDict("NIC_%d_" % idx))
2870
    if constants.HV_NIC_TYPE in instance.hvparams:
2871
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2872
        instance.hvparams[constants.HV_NIC_TYPE]
2873

    
2874
  # HV/BE params
2875
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2876
    for key, value in source.items():
2877
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2878

    
2879
  return result
2880

    
2881

    
2882
def DiagnoseExtStorage(top_dirs=None):
2883
  """Compute the validity for all ExtStorage Providers.
2884

2885
  @type top_dirs: list
2886
  @param top_dirs: the list of directories in which to
2887
      search (if not given defaults to
2888
      L{pathutils.ES_SEARCH_PATH})
2889
  @rtype: list of L{objects.ExtStorage}
2890
  @return: a list of tuples (name, path, status, diagnose, parameters)
2891
      for all (potential) ExtStorage Providers under all
2892
      search paths, where:
2893
          - name is the (potential) ExtStorage Provider
2894
          - path is the full path to the ExtStorage Provider
2895
          - status True/False is the validity of the ExtStorage Provider
2896
          - diagnose is the error message for an invalid ExtStorage Provider,
2897
            otherwise empty
2898
          - parameters is a list of (name, help) parameters, if any
2899

2900
  """
2901
  if top_dirs is None:
2902
    top_dirs = pathutils.ES_SEARCH_PATH
2903

    
2904
  result = []
2905
  for dir_name in top_dirs:
2906
    if os.path.isdir(dir_name):
2907
      try:
2908
        f_names = utils.ListVisibleFiles(dir_name)
2909
      except EnvironmentError, err:
2910
        logging.exception("Can't list the ExtStorage directory %s: %s",
2911
                          dir_name, err)
2912
        break
2913
      for name in f_names:
2914
        es_path = utils.PathJoin(dir_name, name)
2915
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2916
        if status:
2917
          diagnose = ""
2918
          parameters = es_inst.supported_parameters
2919
        else:
2920
          diagnose = es_inst
2921
          parameters = []
2922
        result.append((name, es_path, status, diagnose, parameters))
2923

    
2924
  return result
2925

    
2926

    
2927
def BlockdevGrow(disk, amount, dryrun, backingstore, excl_stor):
2928
  """Grow a stack of block devices.
2929

2930
  This function is called recursively, with the childrens being the
2931
  first ones to resize.
2932

2933
  @type disk: L{objects.Disk}
2934
  @param disk: the disk to be grown
2935
  @type amount: integer
2936
  @param amount: the amount (in mebibytes) to grow with
2937
  @type dryrun: boolean
2938
  @param dryrun: whether to execute the operation in simulation mode
2939
      only, without actually increasing the size
2940
  @param backingstore: whether to execute the operation on backing storage
2941
      only, or on "logical" storage only; e.g. DRBD is logical storage,
2942
      whereas LVM, file, RBD are backing storage
2943
  @rtype: (status, result)
2944
  @type excl_stor: boolean
2945
  @param excl_stor: Whether exclusive_storage is active
2946
  @return: a tuple with the status of the operation (True/False), and
2947
      the errors message if status is False
2948

2949
  """
2950
  r_dev = _RecursiveFindBD(disk)
2951
  if r_dev is None:
2952
    _Fail("Cannot find block device %s", disk)
2953

    
2954
  try:
2955
    r_dev.Grow(amount, dryrun, backingstore, excl_stor)
2956
  except errors.BlockDeviceError, err:
2957
    _Fail("Failed to grow block device: %s", err, exc=True)
2958

    
2959

    
2960
def BlockdevSnapshot(disk):
2961
  """Create a snapshot copy of a block device.
2962

2963
  This function is called recursively, and the snapshot is actually created
2964
  just for the leaf lvm backend device.
2965

2966
  @type disk: L{objects.Disk}
2967
  @param disk: the disk to be snapshotted
2968
  @rtype: string
2969
  @return: snapshot disk ID as (vg, lv)
2970

2971
  """
2972
  if disk.dev_type == constants.LD_DRBD8:
2973
    if not disk.children:
2974
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2975
            disk.unique_id)
2976
    return BlockdevSnapshot(disk.children[0])
2977
  elif disk.dev_type == constants.LD_LV:
2978
    r_dev = _RecursiveFindBD(disk)
2979
    if r_dev is not None:
2980
      # FIXME: choose a saner value for the snapshot size
2981
      # let's stay on the safe side and ask for the full size, for now
2982
      return r_dev.Snapshot(disk.size)
2983
    else:
2984
      _Fail("Cannot find block device %s", disk)
2985
  else:
2986
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2987
          disk.unique_id, disk.dev_type)
2988

    
2989

    
2990
def BlockdevSetInfo(disk, info):
2991
  """Sets 'metadata' information on block devices.
2992

2993
  This function sets 'info' metadata on block devices. Initial
2994
  information is set at device creation; this function should be used
2995
  for example after renames.
2996

2997
  @type disk: L{objects.Disk}
2998
  @param disk: the disk to be grown
2999
  @type info: string
3000
  @param info: new 'info' metadata
3001
  @rtype: (status, result)
3002
  @return: a tuple with the status of the operation (True/False), and
3003
      the errors message if status is False
3004

3005
  """
3006
  r_dev = _RecursiveFindBD(disk)
3007
  if r_dev is None:
3008
    _Fail("Cannot find block device %s", disk)
3009

    
3010
  try:
3011
    r_dev.SetInfo(info)
3012
  except errors.BlockDeviceError, err:
3013
    _Fail("Failed to set information on block device: %s", err, exc=True)
3014

    
3015

    
3016
def FinalizeExport(instance, snap_disks):
3017
  """Write out the export configuration information.
3018

3019
  @type instance: L{objects.Instance}
3020
  @param instance: the instance which we export, used for
3021
      saving configuration
3022
  @type snap_disks: list of L{objects.Disk}
3023
  @param snap_disks: list of snapshot block devices, which
3024
      will be used to get the actual name of the dump file
3025

3026
  @rtype: None
3027

3028
  """
3029
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
3030
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
3031

    
3032
  config = objects.SerializableConfigParser()
3033

    
3034
  config.add_section(constants.INISECT_EXP)
3035
  config.set(constants.INISECT_EXP, "version", "0")
3036
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
3037
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
3038
  config.set(constants.INISECT_EXP, "os", instance.os)
3039
  config.set(constants.INISECT_EXP, "compression", "none")
3040

    
3041
  config.add_section(constants.INISECT_INS)
3042
  config.set(constants.INISECT_INS, "name", instance.name)
3043
  config.set(constants.INISECT_INS, "maxmem", "%d" %
3044
             instance.beparams[constants.BE_MAXMEM])
3045
  config.set(constants.INISECT_INS, "minmem", "%d" %
3046
             instance.beparams[constants.BE_MINMEM])
3047
  # "memory" is deprecated, but useful for exporting to old ganeti versions
3048
  config.set(constants.INISECT_INS, "memory", "%d" %
3049
             instance.beparams[constants.BE_MAXMEM])
3050
  config.set(constants.INISECT_INS, "vcpus", "%d" %
3051
             instance.beparams[constants.BE_VCPUS])
3052
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
3053
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
3054
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
3055

    
3056
  nic_total = 0
3057
  for nic_count, nic in enumerate(instance.nics):
3058
    nic_total += 1
3059
    config.set(constants.INISECT_INS, "nic%d_mac" %
3060
               nic_count, "%s" % nic.mac)
3061
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
3062
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
3063
               "%s" % nic.network)
3064
    for param in constants.NICS_PARAMETER_TYPES:
3065
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
3066
                 "%s" % nic.nicparams.get(param, None))
3067
  # TODO: redundant: on load can read nics until it doesn't exist
3068
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
3069

    
3070
  disk_total = 0
3071
  for disk_count, disk in enumerate(snap_disks):
3072
    if disk:
3073
      disk_total += 1
3074
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
3075
                 ("%s" % disk.iv_name))
3076
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
3077
                 ("%s" % disk.physical_id[1]))
3078
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
3079
                 ("%d" % disk.size))
3080

    
3081
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
3082

    
3083
  # New-style hypervisor/backend parameters
3084

    
3085
  config.add_section(constants.INISECT_HYP)
3086
  for name, value in instance.hvparams.items():
3087
    if name not in constants.HVC_GLOBALS:
3088
      config.set(constants.INISECT_HYP, name, str(value))
3089

    
3090
  config.add_section(constants.INISECT_BEP)
3091
  for name, value in instance.beparams.items():
3092
    config.set(constants.INISECT_BEP, name, str(value))
3093

    
3094
  config.add_section(constants.INISECT_OSP)
3095
  for name, value in instance.osparams.items():
3096
    config.set(constants.INISECT_OSP, name, str(value))
3097

    
3098
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
3099
                  data=config.Dumps())
3100
  shutil.rmtree(finaldestdir, ignore_errors=True)
3101
  shutil.move(destdir, finaldestdir)
3102

    
3103

    
3104
def ExportInfo(dest):
3105
  """Get export configuration information.
3106

3107
  @type dest: str
3108
  @param dest: directory containing the export
3109

3110
  @rtype: L{objects.SerializableConfigParser}
3111
  @return: a serializable config file containing the
3112
      export info
3113

3114
  """
3115
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
3116

    
3117
  config = objects.SerializableConfigParser()
3118
  config.read(cff)
3119

    
3120
  if (not config.has_section(constants.INISECT_EXP) or
3121
      not config.has_section(constants.INISECT_INS)):
3122
    _Fail("Export info file doesn't have the required fields")
3123

    
3124
  return config.Dumps()
3125

    
3126

    
3127
def ListExports():
3128
  """Return a list of exports currently available on this machine.
3129

3130
  @rtype: list
3131
  @return: list of the exports
3132

3133
  """
3134
  if os.path.isdir(pathutils.EXPORT_DIR):
3135
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
3136
  else:
3137
    _Fail("No exports directory")
3138

    
3139

    
3140
def RemoveExport(export):
3141
  """Remove an existing export from the node.
3142

3143
  @type export: str
3144
  @param export: the name of the export to remove
3145
  @rtype: None
3146

3147
  """
3148
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
3149

    
3150
  try:
3151
    shutil.rmtree(target)
3152
  except EnvironmentError, err:
3153
    _Fail("Error while removing the export: %s", err, exc=True)
3154

    
3155

    
3156
def BlockdevRename(devlist):
3157
  """Rename a list of block devices.
3158

3159
  @type devlist: list of tuples
3160
  @param devlist: list of tuples of the form  (disk,
3161
      new_logical_id, new_physical_id); disk is an
3162
      L{objects.Disk} object describing the current disk,
3163
      and new logical_id/physical_id is the name we
3164
      rename it to
3165
  @rtype: boolean
3166
  @return: True if all renames succeeded, False otherwise
3167

3168
  """
3169
  msgs = []
3170
  result = True
3171
  for disk, unique_id in devlist:
3172
    dev = _RecursiveFindBD(disk)
3173
    if dev is None:
3174
      msgs.append("Can't find device %s in rename" % str(disk))
3175
      result = False
3176
      continue
3177
    try:
3178
      old_rpath = dev.dev_path
3179
      dev.Rename(unique_id)
3180
      new_rpath = dev.dev_path
3181
      if old_rpath != new_rpath:
3182
        DevCacheManager.RemoveCache(old_rpath)
3183
        # FIXME: we should add the new cache information here, like:
3184
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
3185
        # but we don't have the owner here - maybe parse from existing
3186
        # cache? for now, we only lose lvm data when we rename, which
3187
        # is less critical than DRBD or MD
3188
    except errors.BlockDeviceError, err:
3189
      msgs.append("Can't rename device '%s' to '%s': %s" %
3190
                  (dev, unique_id, err))
3191
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
3192
      result = False
3193
  if not result:
3194
    _Fail("; ".join(msgs))
3195

    
3196

    
3197
def _TransformFileStorageDir(fs_dir):
3198
  """Checks whether given file_storage_dir is valid.
3199

3200
  Checks wheter the given fs_dir is within the cluster-wide default
3201
  file_storage_dir or the shared_file_storage_dir, which are stored in
3202
  SimpleStore. Only paths under those directories are allowed.
3203

3204
  @type fs_dir: str
3205
  @param fs_dir: the path to check
3206

3207
  @return: the normalized path if valid, None otherwise
3208

3209
  """
3210
  filestorage.CheckFileStoragePath(fs_dir)
3211

    
3212
  return os.path.normpath(fs_dir)
3213

    
3214

    
3215
def CreateFileStorageDir(file_storage_dir):
3216
  """Create file storage directory.
3217

3218
  @type file_storage_dir: str
3219
  @param file_storage_dir: directory to create
3220

3221
  @rtype: tuple
3222
  @return: tuple with first element a boolean indicating wheter dir
3223
      creation was successful or not
3224

3225
  """
3226
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3227
  if os.path.exists(file_storage_dir):
3228
    if not os.path.isdir(file_storage_dir):
3229
      _Fail("Specified storage dir '%s' is not a directory",
3230
            file_storage_dir)
3231
  else:
3232
    try:
3233
      os.makedirs(file_storage_dir, 0750)
3234
    except OSError, err:
3235
      _Fail("Cannot create file storage directory '%s': %s",
3236
            file_storage_dir, err, exc=True)
3237

    
3238

    
3239
def RemoveFileStorageDir(file_storage_dir):
3240
  """Remove file storage directory.
3241

3242
  Remove it only if it's empty. If not log an error and return.
3243

3244
  @type file_storage_dir: str
3245
  @param file_storage_dir: the directory we should cleanup
3246
  @rtype: tuple (success,)
3247
  @return: tuple of one element, C{success}, denoting
3248
      whether the operation was successful
3249

3250
  """
3251
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3252
  if os.path.exists(file_storage_dir):
3253
    if not os.path.isdir(file_storage_dir):
3254
      _Fail("Specified Storage directory '%s' is not a directory",
3255
            file_storage_dir)
3256
    # deletes dir only if empty, otherwise we want to fail the rpc call
3257
    try:
3258
      os.rmdir(file_storage_dir)
3259
    except OSError, err:
3260
      _Fail("Cannot remove file storage directory '%s': %s",
3261
            file_storage_dir, err)
3262

    
3263

    
3264
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
3265
  """Rename the file storage directory.
3266

3267
  @type old_file_storage_dir: str
3268
  @param old_file_storage_dir: the current path
3269
  @type new_file_storage_dir: str
3270
  @param new_file_storage_dir: the name we should rename to
3271
  @rtype: tuple (success,)
3272
  @return: tuple of one element, C{success}, denoting
3273
      whether the operation was successful
3274

3275
  """
3276
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
3277
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
3278
  if not os.path.exists(new_file_storage_dir):
3279
    if os.path.isdir(old_file_storage_dir):
3280
      try:
3281
        os.rename(old_file_storage_dir, new_file_storage_dir)
3282
      except OSError, err:
3283
        _Fail("Cannot rename '%s' to '%s': %s",
3284
              old_file_storage_dir, new_file_storage_dir, err)
3285
    else:
3286
      _Fail("Specified storage dir '%s' is not a directory",
3287
            old_file_storage_dir)
3288
  else:
3289
    if os.path.exists(old_file_storage_dir):
3290
      _Fail("Cannot rename '%s' to '%s': both locations exist",
3291
            old_file_storage_dir, new_file_storage_dir)
3292

    
3293

    
3294
def _EnsureJobQueueFile(file_name):
3295
  """Checks whether the given filename is in the queue directory.
3296

3297
  @type file_name: str
3298
  @param file_name: the file name we should check
3299
  @rtype: None
3300
  @raises RPCFail: if the file is not valid
3301

3302
  """
3303
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
3304
    _Fail("Passed job queue file '%s' does not belong to"
3305
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
3306

    
3307

    
3308
def JobQueueUpdate(file_name, content):
3309
  """Updates a file in the queue directory.
3310

3311
  This is just a wrapper over L{utils.io.WriteFile}, with proper
3312
  checking.
3313

3314
  @type file_name: str
3315
  @param file_name: the job file name
3316
  @type content: str
3317
  @param content: the new job contents
3318
  @rtype: boolean
3319
  @return: the success of the operation
3320

3321
  """
3322
  file_name = vcluster.LocalizeVirtualPath(file_name)
3323

    
3324
  _EnsureJobQueueFile(file_name)
3325
  getents = runtime.GetEnts()
3326

    
3327
  # Write and replace the file atomically
3328
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3329
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3330

    
3331

    
3332
def JobQueueRename(old, new):
3333
  """Renames a job queue file.
3334

3335
  This is just a wrapper over os.rename with proper checking.
3336

3337
  @type old: str
3338
  @param old: the old (actual) file name
3339
  @type new: str
3340
  @param new: the desired file name
3341
  @rtype: tuple
3342
  @return: the success of the operation and payload
3343

3344
  """
3345
  old = vcluster.LocalizeVirtualPath(old)
3346
  new = vcluster.LocalizeVirtualPath(new)
3347

    
3348
  _EnsureJobQueueFile(old)
3349
  _EnsureJobQueueFile(new)
3350

    
3351
  getents = runtime.GetEnts()
3352

    
3353
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3354
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3355

    
3356

    
3357
def BlockdevClose(instance_name, disks):
3358
  """Closes the given block devices.
3359

3360
  This means they will be switched to secondary mode (in case of
3361
  DRBD).
3362

3363
  @param instance_name: if the argument is not empty, the symlinks
3364
      of this instance will be removed
3365
  @type disks: list of L{objects.Disk}
3366
  @param disks: the list of disks to be closed
3367
  @rtype: tuple (success, message)
3368
  @return: a tuple of success and message, where success
3369
      indicates the succes of the operation, and message
3370
      which will contain the error details in case we
3371
      failed
3372

3373
  """
3374
  bdevs = []
3375
  for cf in disks:
3376
    rd = _RecursiveFindBD(cf)
3377
    if rd is None:
3378
      _Fail("Can't find device %s", cf)
3379
    bdevs.append(rd)
3380

    
3381
  msg = []
3382
  for rd in bdevs:
3383
    try:
3384
      rd.Close()
3385
    except errors.BlockDeviceError, err:
3386
      msg.append(str(err))
3387
  if msg:
3388
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3389
  else:
3390
    if instance_name:
3391
      _RemoveBlockDevLinks(instance_name, disks)
3392

    
3393

    
3394
def ValidateHVParams(hvname, hvparams):
3395
  """Validates the given hypervisor parameters.
3396

3397
  @type hvname: string
3398
  @param hvname: the hypervisor name
3399
  @type hvparams: dict
3400
  @param hvparams: the hypervisor parameters to be validated
3401
  @rtype: None
3402

3403
  """
3404
  try:
3405
    hv_type = hypervisor.GetHypervisor(hvname)
3406
    hv_type.ValidateParameters(hvparams)
3407
  except errors.HypervisorError, err:
3408
    _Fail(str(err), log=False)
3409

    
3410

    
3411
def _CheckOSPList(os_obj, parameters):
3412
  """Check whether a list of parameters is supported by the OS.
3413

3414
  @type os_obj: L{objects.OS}
3415
  @param os_obj: OS object to check
3416
  @type parameters: list
3417
  @param parameters: the list of parameters to check
3418

3419
  """
3420
  supported = [v[0] for v in os_obj.supported_parameters]
3421
  delta = frozenset(parameters).difference(supported)
3422
  if delta:
3423
    _Fail("The following parameters are not supported"
3424
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3425

    
3426

    
3427
def ValidateOS(required, osname, checks, osparams):
3428
  """Validate the given OS' parameters.
3429

3430
  @type required: boolean
3431
  @param required: whether absence of the OS should translate into
3432
      failure or not
3433
  @type osname: string
3434
  @param osname: the OS to be validated
3435
  @type checks: list
3436
  @param checks: list of the checks to run (currently only 'parameters')
3437
  @type osparams: dict
3438
  @param osparams: dictionary with OS parameters
3439
  @rtype: boolean
3440
  @return: True if the validation passed, or False if the OS was not
3441
      found and L{required} was false
3442

3443
  """
3444
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3445
    _Fail("Unknown checks required for OS %s: %s", osname,
3446
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3447

    
3448
  name_only = objects.OS.GetName(osname)
3449
  status, tbv = _TryOSFromDisk(name_only, None)
3450

    
3451
  if not status:
3452
    if required:
3453
      _Fail(tbv)
3454
    else:
3455
      return False
3456

    
3457
  if max(tbv.api_versions) < constants.OS_API_V20:
3458
    return True
3459

    
3460
  if constants.OS_VALIDATE_PARAMETERS in checks:
3461
    _CheckOSPList(tbv, osparams.keys())
3462

    
3463
  validate_env = OSCoreEnv(osname, tbv, osparams)
3464
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3465
                        cwd=tbv.path, reset_env=True)
3466
  if result.failed:
3467
    logging.error("os validate command '%s' returned error: %s output: %s",
3468
                  result.cmd, result.fail_reason, result.output)
3469
    _Fail("OS validation script failed (%s), output: %s",
3470
          result.fail_reason, result.output, log=False)
3471

    
3472
  return True
3473

    
3474

    
3475
def DemoteFromMC():
3476
  """Demotes the current node from master candidate role.
3477

3478
  """
3479
  # try to ensure we're not the master by mistake
3480
  master, myself = ssconf.GetMasterAndMyself()
3481
  if master == myself:
3482
    _Fail("ssconf status shows I'm the master node, will not demote")
3483

    
3484
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3485
  if not result.failed:
3486
    _Fail("The master daemon is running, will not demote")
3487

    
3488
  try:
3489
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3490
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3491
  except EnvironmentError, err:
3492
    if err.errno != errno.ENOENT:
3493
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3494

    
3495
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3496

    
3497

    
3498
def _GetX509Filenames(cryptodir, name):
3499
  """Returns the full paths for the private key and certificate.
3500

3501
  """
3502
  return (utils.PathJoin(cryptodir, name),
3503
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3504
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3505

    
3506

    
3507
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3508
  """Creates a new X509 certificate for SSL/TLS.
3509

3510
  @type validity: int
3511
  @param validity: Validity in seconds
3512
  @rtype: tuple; (string, string)
3513
  @return: Certificate name and public part
3514

3515
  """
3516
  (key_pem, cert_pem) = \
3517
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3518
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3519

    
3520
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3521
                              prefix="x509-%s-" % utils.TimestampForFilename())
3522
  try:
3523
    name = os.path.basename(cert_dir)
3524
    assert len(name) > 5
3525

    
3526
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3527

    
3528
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3529
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3530

    
3531
    # Never return private key as it shouldn't leave the node
3532
    return (name, cert_pem)
3533
  except Exception:
3534
    shutil.rmtree(cert_dir, ignore_errors=True)
3535
    raise
3536

    
3537

    
3538
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3539
  """Removes a X509 certificate.
3540

3541
  @type name: string
3542
  @param name: Certificate name
3543

3544
  """
3545
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3546

    
3547
  utils.RemoveFile(key_file)
3548
  utils.RemoveFile(cert_file)
3549

    
3550
  try:
3551
    os.rmdir(cert_dir)
3552
  except EnvironmentError, err:
3553
    _Fail("Cannot remove certificate directory '%s': %s",
3554
          cert_dir, err)
3555

    
3556

    
3557
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3558
  """Returns the command for the requested input/output.
3559

3560
  @type instance: L{objects.Instance}
3561
  @param instance: The instance object
3562
  @param mode: Import/export mode
3563
  @param ieio: Input/output type
3564
  @param ieargs: Input/output arguments
3565

3566
  """
3567
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3568

    
3569
  env = None
3570
  prefix = None
3571
  suffix = None
3572
  exp_size = None
3573

    
3574
  if ieio == constants.IEIO_FILE:
3575
    (filename, ) = ieargs
3576

    
3577
    if not utils.IsNormAbsPath(filename):
3578
      _Fail("Path '%s' is not normalized or absolute", filename)
3579

    
3580
    real_filename = os.path.realpath(filename)
3581
    directory = os.path.dirname(real_filename)
3582

    
3583
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3584
      _Fail("File '%s' is not under exports directory '%s': %s",
3585
            filename, pathutils.EXPORT_DIR, real_filename)
3586

    
3587
    # Create directory
3588
    utils.Makedirs(directory, mode=0750)
3589

    
3590
    quoted_filename = utils.ShellQuote(filename)
3591

    
3592
    if mode == constants.IEM_IMPORT:
3593
      suffix = "> %s" % quoted_filename
3594
    elif mode == constants.IEM_EXPORT:
3595
      suffix = "< %s" % quoted_filename
3596

    
3597
      # Retrieve file size
3598
      try:
3599
        st = os.stat(filename)
3600
      except EnvironmentError, err:
3601
        logging.error("Can't stat(2) %s: %s", filename, err)
3602
      else:
3603
        exp_size = utils.BytesToMebibyte(st.st_size)
3604

    
3605
  elif ieio == constants.IEIO_RAW_DISK:
3606
    (disk, ) = ieargs
3607

    
3608
    real_disk = _OpenRealBD(disk)
3609

    
3610
    if mode == constants.IEM_IMPORT:
3611
      # we set here a smaller block size as, due to transport buffering, more
3612
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3613
      # is not already there or we pass a wrong path; we use notrunc to no
3614
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3615
      # much memory; this means that at best, we flush every 64k, which will
3616
      # not be very fast
3617
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3618
                                    " bs=%s oflag=dsync"),
3619
                                    real_disk.dev_path,
3620
                                    str(64 * 1024))
3621

    
3622
    elif mode == constants.IEM_EXPORT:
3623
      # the block size on the read dd is 1MiB to match our units
3624
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3625
                                   real_disk.dev_path,
3626
                                   str(1024 * 1024), # 1 MB
3627
                                   str(disk.size))
3628
      exp_size = disk.size
3629

    
3630
  elif ieio == constants.IEIO_SCRIPT:
3631
    (disk, disk_index, ) = ieargs
3632

    
3633
    assert isinstance(disk_index, (int, long))
3634

    
3635
    real_disk = _OpenRealBD(disk)
3636

    
3637
    inst_os = OSFromDisk(instance.os)
3638
    env = OSEnvironment(instance, inst_os)
3639

    
3640
    if mode == constants.IEM_IMPORT:
3641
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3642
      env["IMPORT_INDEX"] = str(disk_index)
3643
      script = inst_os.import_script
3644

    
3645
    elif mode == constants.IEM_EXPORT:
3646
      env["EXPORT_DEVICE"] = real_disk.dev_path
3647
      env["EXPORT_INDEX"] = str(disk_index)
3648
      script = inst_os.export_script
3649

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

    
3653
    if mode == constants.IEM_IMPORT:
3654
      suffix = "| %s" % script_cmd
3655

    
3656
    elif mode == constants.IEM_EXPORT:
3657
      prefix = "%s |" % script_cmd
3658

    
3659
    # Let script predict size
3660
    exp_size = constants.IE_CUSTOM_SIZE
3661

    
3662
  else:
3663
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3664

    
3665
  return (env, prefix, suffix, exp_size)
3666

    
3667

    
3668
def _CreateImportExportStatusDir(prefix):
3669
  """Creates status directory for import/export.
3670

3671
  """
3672
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3673
                          prefix=("%s-%s-" %
3674
                                  (prefix, utils.TimestampForFilename())))
3675

    
3676

    
3677
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3678
                            ieio, ieioargs):
3679
  """Starts an import or export daemon.
3680

3681
  @param mode: Import/output mode
3682
  @type opts: L{objects.ImportExportOptions}
3683
  @param opts: Daemon options
3684
  @type host: string
3685
  @param host: Remote host for export (None for import)
3686
  @type port: int
3687
  @param port: Remote port for export (None for import)
3688
  @type instance: L{objects.Instance}
3689
  @param instance: Instance object
3690
  @type component: string
3691
  @param component: which part of the instance is transferred now,
3692
      e.g. 'disk/0'
3693
  @param ieio: Input/output type
3694
  @param ieioargs: Input/output arguments
3695

3696
  """
3697
  if mode == constants.IEM_IMPORT:
3698
    prefix = "import"
3699

    
3700
    if not (host is None and port is None):
3701
      _Fail("Can not specify host or port on import")
3702

    
3703
  elif mode == constants.IEM_EXPORT:
3704
    prefix = "export"
3705

    
3706
    if host is None or port is None:
3707
      _Fail("Host and port must be specified for an export")
3708

    
3709
  else:
3710
    _Fail("Invalid mode %r", mode)
3711

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

    
3715
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3716
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3717

    
3718
  if opts.key_name is None:
3719
    # Use server.pem
3720
    key_path = pathutils.NODED_CERT_FILE
3721
    cert_path = pathutils.NODED_CERT_FILE
3722
    assert opts.ca_pem is None
3723
  else:
3724
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3725
                                                 opts.key_name)
3726
    assert opts.ca_pem is not None
3727

    
3728
  for i in [key_path, cert_path]:
3729
    if not os.path.exists(i):
3730
      _Fail("File '%s' does not exist" % i)
3731

    
3732
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3733
  try:
3734
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3735
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3736
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3737

    
3738
    if opts.ca_pem is None:
3739
      # Use server.pem
3740
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3741
    else:
3742
      ca = opts.ca_pem
3743

    
3744
    # Write CA file
3745
    utils.WriteFile(ca_file, data=ca, mode=0400)
3746

    
3747
    cmd = [
3748
      pathutils.IMPORT_EXPORT_DAEMON,
3749
      status_file, mode,
3750
      "--key=%s" % key_path,
3751
      "--cert=%s" % cert_path,
3752
      "--ca=%s" % ca_file,
3753
      ]
3754

    
3755
    if host:
3756
      cmd.append("--host=%s" % host)
3757

    
3758
    if port:
3759
      cmd.append("--port=%s" % port)
3760

    
3761
    if opts.ipv6:
3762
      cmd.append("--ipv6")
3763
    else:
3764
      cmd.append("--ipv4")
3765

    
3766
    if opts.compress:
3767
      cmd.append("--compress=%s" % opts.compress)
3768

    
3769
    if opts.magic:
3770
      cmd.append("--magic=%s" % opts.magic)
3771

    
3772
    if exp_size is not None:
3773
      cmd.append("--expected-size=%s" % exp_size)
3774

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

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

    
3781
    if mode == constants.IEM_EXPORT:
3782
      # Retry connection a few times when connecting to remote peer
3783
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3784
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3785
    elif opts.connect_timeout is not None:
3786
      assert mode == constants.IEM_IMPORT
3787
      # Overall timeout for establishing connection while listening
3788
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3789

    
3790
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3791

    
3792
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3793
    # support for receiving a file descriptor for output
3794
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3795
                      output=logfile)
3796

    
3797
    # The import/export name is simply the status directory name
3798
    return os.path.basename(status_dir)
3799

    
3800
  except Exception:
3801
    shutil.rmtree(status_dir, ignore_errors=True)
3802
    raise
3803

    
3804

    
3805
def GetImportExportStatus(names):
3806
  """Returns import/export daemon status.
3807

3808
  @type names: sequence
3809
  @param names: List of names
3810
  @rtype: List of dicts
3811
  @return: Returns a list of the state of each named import/export or None if a
3812
           status couldn't be read
3813

3814
  """
3815
  result = []
3816

    
3817
  for name in names:
3818
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3819
                                 _IES_STATUS_FILE)
3820

    
3821
    try:
3822
      data = utils.ReadFile(status_file)
3823
    except EnvironmentError, err:
3824
      if err.errno != errno.ENOENT:
3825
        raise
3826
      data = None
3827

    
3828
    if not data:
3829
      result.append(None)
3830
      continue
3831

    
3832
    result.append(serializer.LoadJson(data))
3833

    
3834
  return result
3835

    
3836

    
3837
def AbortImportExport(name):
3838
  """Sends SIGTERM to a running import/export daemon.
3839

3840
  """
3841
  logging.info("Abort import/export %s", name)
3842

    
3843
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3844
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3845

    
3846
  if pid:
3847
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3848
                 name, pid)
3849
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3850

    
3851

    
3852
def CleanupImportExport(name):
3853
  """Cleanup after an import or export.
3854

3855
  If the import/export daemon is still running it's killed. Afterwards the
3856
  whole status directory is removed.
3857

3858
  """
3859
  logging.info("Finalizing import/export %s", name)
3860

    
3861
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3862

    
3863
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3864

    
3865
  if pid:
3866
    logging.info("Import/export %s is still running with PID %s",
3867
                 name, pid)
3868
    utils.KillProcess(pid, waitpid=False)
3869

    
3870
  shutil.rmtree(status_dir, ignore_errors=True)
3871

    
3872

    
3873
def _SetPhysicalId(target_node_uuid, nodes_ip, disks):
3874
  """Sets the correct physical ID on all passed disks.
3875

3876
  """
3877
  for cf in disks:
3878
    cf.SetPhysicalID(target_node_uuid, nodes_ip)
3879

    
3880

    
3881
def _FindDisks(target_node_uuid, nodes_ip, disks):
3882
  """Sets the physical ID on disks and returns the block devices.
3883

3884
  """
3885
  _SetPhysicalId(target_node_uuid, nodes_ip, disks)
3886

    
3887
  bdevs = []
3888

    
3889
  for cf in disks:
3890
    rd = _RecursiveFindBD(cf)
3891
    if rd is None:
3892
      _Fail("Can't find device %s", cf)
3893
    bdevs.append(rd)
3894
  return bdevs
3895

    
3896

    
3897
def DrbdDisconnectNet(target_node_uuid, nodes_ip, disks):
3898
  """Disconnects the network on a list of drbd devices.
3899

3900
  """
3901
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3902

    
3903
  # disconnect disks
3904
  for rd in bdevs:
3905
    try:
3906
      rd.DisconnectNet()
3907
    except errors.BlockDeviceError, err:
3908
      _Fail("Can't change network configuration to standalone mode: %s",
3909
            err, exc=True)
3910

    
3911

    
3912
def DrbdAttachNet(target_node_uuid, nodes_ip, disks, instance_name,
3913
                  multimaster):
3914
  """Attaches the network on a list of drbd devices.
3915

3916
  """
3917
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3918

    
3919
  if multimaster:
3920
    for idx, rd in enumerate(bdevs):
3921
      try:
3922
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3923
      except EnvironmentError, err:
3924
        _Fail("Can't create symlink: %s", err)
3925
  # reconnect disks, switch to new master configuration and if
3926
  # needed primary mode
3927
  for rd in bdevs:
3928
    try:
3929
      rd.AttachNet(multimaster)
3930
    except errors.BlockDeviceError, err:
3931
      _Fail("Can't change network configuration: %s", err)
3932

    
3933
  # wait until the disks are connected; we need to retry the re-attach
3934
  # if the device becomes standalone, as this might happen if the one
3935
  # node disconnects and reconnects in a different mode before the
3936
  # other node reconnects; in this case, one or both of the nodes will
3937
  # decide it has wrong configuration and switch to standalone
3938

    
3939
  def _Attach():
3940
    all_connected = True
3941

    
3942
    for rd in bdevs:
3943
      stats = rd.GetProcStatus()
3944

    
3945
      all_connected = (all_connected and
3946
                       (stats.is_connected or stats.is_in_resync))
3947

    
3948
      if stats.is_standalone:
3949
        # peer had different config info and this node became
3950
        # standalone, even though this should not happen with the
3951
        # new staged way of changing disk configs
3952
        try:
3953
          rd.AttachNet(multimaster)
3954
        except errors.BlockDeviceError, err:
3955
          _Fail("Can't change network configuration: %s", err)
3956

    
3957
    if not all_connected:
3958
      raise utils.RetryAgain()
3959

    
3960
  try:
3961
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3962
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3963
  except utils.RetryTimeout:
3964
    _Fail("Timeout in disk reconnecting")
3965

    
3966
  if multimaster:
3967
    # change to primary mode
3968
    for rd in bdevs:
3969
      try:
3970
        rd.Open()
3971
      except errors.BlockDeviceError, err:
3972
        _Fail("Can't change to primary mode: %s", err)
3973

    
3974

    
3975
def DrbdWaitSync(target_node_uuid, nodes_ip, disks):
3976
  """Wait until DRBDs have synchronized.
3977

3978
  """
3979
  def _helper(rd):
3980
    stats = rd.GetProcStatus()
3981
    if not (stats.is_connected or stats.is_in_resync):
3982
      raise utils.RetryAgain()
3983
    return stats
3984

    
3985
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3986

    
3987
  min_resync = 100
3988
  alldone = True
3989
  for rd in bdevs:
3990
    try:
3991
      # poll each second for 15 seconds
3992
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3993
    except utils.RetryTimeout:
3994
      stats = rd.GetProcStatus()
3995
      # last check
3996
      if not (stats.is_connected or stats.is_in_resync):
3997
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3998
    alldone = alldone and (not stats.is_in_resync)
3999
    if stats.sync_percent is not None:
4000
      min_resync = min(min_resync, stats.sync_percent)
4001

    
4002
  return (alldone, min_resync)
4003

    
4004

    
4005
def DrbdNeedsActivation(target_node_uuid, nodes_ip, disks):
4006
  """Checks which of the passed disks needs activation and returns their UUIDs.
4007

4008
  """
4009
  _SetPhysicalId(target_node_uuid, nodes_ip, disks)
4010
  faulty_disks = []
4011

    
4012
  for disk in disks:
4013
    rd = _RecursiveFindBD(disk)
4014
    if rd is None:
4015
      faulty_disks.append(disk)
4016
      continue
4017

    
4018
    stats = rd.GetProcStatus()
4019
    if stats.is_standalone or stats.is_diskless:
4020
      faulty_disks.append(disk)
4021

    
4022
  return [disk.uuid for disk in faulty_disks]
4023

    
4024

    
4025
def GetDrbdUsermodeHelper():
4026
  """Returns DRBD usermode helper currently configured.
4027

4028
  """
4029
  try:
4030
    return drbd.DRBD8.GetUsermodeHelper()
4031
  except errors.BlockDeviceError, err:
4032
    _Fail(str(err))
4033

    
4034

    
4035
def PowercycleNode(hypervisor_type, hvparams=None):
4036
  """Hard-powercycle the node.
4037

4038
  Because we need to return first, and schedule the powercycle in the
4039
  background, we won't be able to report failures nicely.
4040

4041
  """
4042
  hyper = hypervisor.GetHypervisor(hypervisor_type)
4043
  try:
4044
    pid = os.fork()
4045
  except OSError:
4046
    # if we can't fork, we'll pretend that we're in the child process
4047
    pid = 0
4048
  if pid > 0:
4049
    return "Reboot scheduled in 5 seconds"
4050
  # ensure the child is running on ram
4051
  try:
4052
    utils.Mlockall()
4053
  except Exception: # pylint: disable=W0703
4054
    pass
4055
  time.sleep(5)
4056
  hyper.PowercycleNode(hvparams=hvparams)
4057

    
4058

    
4059
def _VerifyRestrictedCmdName(cmd):
4060
  """Verifies a restricted command name.
4061

4062
  @type cmd: string
4063
  @param cmd: Command name
4064
  @rtype: tuple; (boolean, string or None)
4065
  @return: The tuple's first element is the status; if C{False}, the second
4066
    element is an error message string, otherwise it's C{None}
4067

4068
  """
4069
  if not cmd.strip():
4070
    return (False, "Missing command name")
4071

    
4072
  if os.path.basename(cmd) != cmd:
4073
    return (False, "Invalid command name")
4074

    
4075
  if not constants.EXT_PLUGIN_MASK.match(cmd):
4076
    return (False, "Command name contains forbidden characters")
4077

    
4078
  return (True, None)
4079

    
4080

    
4081
def _CommonRestrictedCmdCheck(path, owner):
4082
  """Common checks for restricted command file system directories and files.
4083

4084
  @type path: string
4085
  @param path: Path to check
4086
  @param owner: C{None} or tuple containing UID and GID
4087
  @rtype: tuple; (boolean, string or C{os.stat} result)
4088
  @return: The tuple's first element is the status; if C{False}, the second
4089
    element is an error message string, otherwise it's the result of C{os.stat}
4090

4091
  """
4092
  if owner is None:
4093
    # Default to root as owner
4094
    owner = (0, 0)
4095

    
4096
  try:
4097
    st = os.stat(path)
4098
  except EnvironmentError, err:
4099
    return (False, "Can't stat(2) '%s': %s" % (path, err))
4100

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

    
4104
  if (st.st_uid, st.st_gid) != owner:
4105
    (owner_uid, owner_gid) = owner
4106
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
4107

    
4108
  return (True, st)
4109

    
4110

    
4111
def _VerifyRestrictedCmdDirectory(path, _owner=None):
4112
  """Verifies restricted command directory.
4113

4114
  @type path: string
4115
  @param path: Path to check
4116
  @rtype: tuple; (boolean, string or None)
4117
  @return: The tuple's first element is the status; if C{False}, the second
4118
    element is an error message string, otherwise it's C{None}
4119

4120
  """
4121
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
4122

    
4123
  if not status:
4124
    return (False, value)
4125

    
4126
  if not stat.S_ISDIR(value.st_mode):
4127
    return (False, "Path '%s' is not a directory" % path)
4128

    
4129
  return (True, None)
4130

    
4131

    
4132
def _VerifyRestrictedCmd(path, cmd, _owner=None):
4133
  """Verifies a whole restricted command and returns its executable filename.
4134

4135
  @type path: string
4136
  @param path: Directory containing restricted commands
4137
  @type cmd: string
4138
  @param cmd: Command name
4139
  @rtype: tuple; (boolean, string)
4140
  @return: The tuple's first element is the status; if C{False}, the second
4141
    element is an error message string, otherwise the second element is the
4142
    absolute path to the executable
4143

4144
  """
4145
  executable = utils.PathJoin(path, cmd)
4146

    
4147
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
4148

    
4149
  if not status:
4150
    return (False, msg)
4151

    
4152
  if not utils.IsExecutable(executable):
4153
    return (False, "access(2) thinks '%s' can't be executed" % executable)
4154

    
4155
  return (True, executable)
4156

    
4157

    
4158
def _PrepareRestrictedCmd(path, cmd,
4159
                          _verify_dir=_VerifyRestrictedCmdDirectory,
4160
                          _verify_name=_VerifyRestrictedCmdName,
4161
                          _verify_cmd=_VerifyRestrictedCmd):
4162
  """Performs a number of tests on a restricted command.
4163

4164
  @type path: string
4165
  @param path: Directory containing restricted commands
4166
  @type cmd: string
4167
  @param cmd: Command name
4168
  @return: Same as L{_VerifyRestrictedCmd}
4169

4170
  """
4171
  # Verify the directory first
4172
  (status, msg) = _verify_dir(path)
4173
  if status:
4174
    # Check command if everything was alright
4175
    (status, msg) = _verify_name(cmd)
4176

    
4177
  if not status:
4178
    return (False, msg)
4179

    
4180
  # Check actual executable
4181
  return _verify_cmd(path, cmd)
4182

    
4183

    
4184
def RunRestrictedCmd(cmd,
4185
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
4186
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
4187
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
4188
                     _sleep_fn=time.sleep,
4189
                     _prepare_fn=_PrepareRestrictedCmd,
4190
                     _runcmd_fn=utils.RunCmd,
4191
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
4192
  """Executes a restricted command after performing strict tests.
4193

4194
  @type cmd: string
4195
  @param cmd: Command name
4196
  @rtype: string
4197
  @return: Command output
4198
  @raise RPCFail: In case of an error
4199

4200
  """
4201
  logging.info("Preparing to run restricted command '%s'", cmd)
4202

    
4203
  if not _enabled:
4204
    _Fail("Restricted commands disabled at configure time")
4205

    
4206
  lock = None
4207
  try:
4208
    cmdresult = None
4209
    try:
4210
      lock = utils.FileLock.Open(_lock_file)
4211
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
4212

    
4213
      (status, value) = _prepare_fn(_path, cmd)
4214

    
4215
      if status:
4216
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
4217
                               postfork_fn=lambda _: lock.Unlock())
4218
      else:
4219
        logging.error(value)
4220
    except Exception: # pylint: disable=W0703
4221
      # Keep original error in log
4222
      logging.exception("Caught exception")
4223

    
4224
    if cmdresult is None:
4225
      logging.info("Sleeping for %0.1f seconds before returning",
4226
                   _RCMD_INVALID_DELAY)
4227
      _sleep_fn(_RCMD_INVALID_DELAY)
4228

    
4229
      # Do not include original error message in returned error
4230
      _Fail("Executing command '%s' failed" % cmd)
4231
    elif cmdresult.failed or cmdresult.fail_reason:
4232
      _Fail("Restricted command '%s' failed: %s; output: %s",
4233
            cmd, cmdresult.fail_reason, cmdresult.output)
4234
    else:
4235
      return cmdresult.output
4236
  finally:
4237
    if lock is not None:
4238
      # Release lock at last
4239
      lock.Close()
4240
      lock = None
4241

    
4242

    
4243
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
4244
  """Creates or removes the watcher pause file.
4245

4246
  @type until: None or number
4247
  @param until: Unix timestamp saying until when the watcher shouldn't run
4248

4249
  """
4250
  if until is None:
4251
    logging.info("Received request to no longer pause watcher")
4252
    utils.RemoveFile(_filename)
4253
  else:
4254
    logging.info("Received request to pause watcher until %s", until)
4255

    
4256
    if not ht.TNumber(until):
4257
      _Fail("Duration must be numeric")
4258

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

    
4261

    
4262
class HooksRunner(object):
4263
  """Hook runner.
4264

4265
  This class is instantiated on the node side (ganeti-noded) and not
4266
  on the master side.
4267

4268
  """
4269
  def __init__(self, hooks_base_dir=None):
4270
    """Constructor for hooks runner.
4271

4272
    @type hooks_base_dir: str or None
4273
    @param hooks_base_dir: if not None, this overrides the
4274
        L{pathutils.HOOKS_BASE_DIR} (useful for unittests)
4275

4276
    """
4277
    if hooks_base_dir is None:
4278
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
4279
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
4280
    # constant
4281
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
4282

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

4286
    """
4287
    assert len(node_list) == 1
4288
    node = node_list[0]
4289
    _, myself = ssconf.GetMasterAndMyself()
4290
    assert node == myself
4291

    
4292
    results = self.RunHooks(hpath, phase, env)
4293

    
4294
    # Return values in the form expected by HooksMaster
4295
    return {node: (None, False, results)}
4296

    
4297
  def RunHooks(self, hpath, phase, env):
4298
    """Run the scripts in the hooks directory.
4299

4300
    @type hpath: str
4301
    @param hpath: the path to the hooks directory which
4302
        holds the scripts
4303
    @type phase: str
4304
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
4305
        L{constants.HOOKS_PHASE_POST}
4306
    @type env: dict
4307
    @param env: dictionary with the environment for the hook
4308
    @rtype: list
4309
    @return: list of 3-element tuples:
4310
      - script path
4311
      - script result, either L{constants.HKR_SUCCESS} or
4312
        L{constants.HKR_FAIL}
4313
      - output of the script
4314

4315
    @raise errors.ProgrammerError: for invalid input
4316
        parameters
4317

4318
    """
4319
    if phase == constants.HOOKS_PHASE_PRE:
4320
      suffix = "pre"
4321
    elif phase == constants.HOOKS_PHASE_POST:
4322
      suffix = "post"
4323
    else:
4324
      _Fail("Unknown hooks phase '%s'", phase)
4325

    
4326
    subdir = "%s-%s.d" % (hpath, suffix)
4327
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
4328

    
4329
    results = []
4330

    
4331
    if not os.path.isdir(dir_name):
4332
      # for non-existing/non-dirs, we simply exit instead of logging a
4333
      # warning at every operation
4334
      return results
4335

    
4336
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
4337

    
4338
    for (relname, relstatus, runresult) in runparts_results:
4339
      if relstatus == constants.RUNPARTS_SKIP:
4340
        rrval = constants.HKR_SKIP
4341
        output = ""
4342
      elif relstatus == constants.RUNPARTS_ERR:
4343
        rrval = constants.HKR_FAIL
4344
        output = "Hook script execution error: %s" % runresult
4345
      elif relstatus == constants.RUNPARTS_RUN:
4346
        if runresult.failed:
4347
          rrval = constants.HKR_FAIL
4348
        else:
4349
          rrval = constants.HKR_SUCCESS
4350
        output = utils.SafeEncode(runresult.output.strip())
4351
      results.append(("%s/%s" % (subdir, relname), rrval, output))
4352

    
4353
    return results
4354

    
4355

    
4356
class IAllocatorRunner(object):
4357
  """IAllocator runner.
4358

4359
  This class is instantiated on the node side (ganeti-noded) and not on
4360
  the master side.
4361

4362
  """
4363
  @staticmethod
4364
  def Run(name, idata):
4365
    """Run an iallocator script.
4366

4367
    @type name: str
4368
    @param name: the iallocator script name
4369
    @type idata: str
4370
    @param idata: the allocator input data
4371

4372
    @rtype: tuple
4373
    @return: two element tuple of:
4374
       - status
4375
       - either error message or stdout of allocator (for success)
4376

4377
    """
4378
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
4379
                                  os.path.isfile)
4380
    if alloc_script is None:
4381
      _Fail("iallocator module '%s' not found in the search path", name)
4382

    
4383
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
4384
    try:
4385
      os.write(fd, idata)
4386
      os.close(fd)
4387
      result = utils.RunCmd([alloc_script, fin_name])
4388
      if result.failed:
4389
        _Fail("iallocator module '%s' failed: %s, output '%s'",
4390
              name, result.fail_reason, result.output)
4391
    finally:
4392
      os.unlink(fin_name)
4393

    
4394
    return result.stdout
4395

    
4396

    
4397
class DevCacheManager(object):
4398
  """Simple class for managing a cache of block device information.
4399

4400
  """
4401
  _DEV_PREFIX = "/dev/"
4402
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4403

    
4404
  @classmethod
4405
  def _ConvertPath(cls, dev_path):
4406
    """Converts a /dev/name path to the cache file name.
4407

4408
    This replaces slashes with underscores and strips the /dev
4409
    prefix. It then returns the full path to the cache file.
4410

4411
    @type dev_path: str
4412
    @param dev_path: the C{/dev/} path name
4413
    @rtype: str
4414
    @return: the converted path name
4415

4416
    """
4417
    if dev_path.startswith(cls._DEV_PREFIX):
4418
      dev_path = dev_path[len(cls._DEV_PREFIX):]
4419
    dev_path = dev_path.replace("/", "_")
4420
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4421
    return fpath
4422

    
4423
  @classmethod
4424
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4425
    """Updates the cache information for a given device.
4426

4427
    @type dev_path: str
4428
    @param dev_path: the pathname of the device
4429
    @type owner: str
4430
    @param owner: the owner (instance name) of the device
4431
    @type on_primary: bool
4432
    @param on_primary: whether this is the primary
4433
        node nor not
4434
    @type iv_name: str
4435
    @param iv_name: the instance-visible name of the
4436
        device, as in objects.Disk.iv_name
4437

4438
    @rtype: None
4439

4440
    """
4441
    if dev_path is None:
4442
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
4443
      return
4444
    fpath = cls._ConvertPath(dev_path)
4445
    if on_primary:
4446
      state = "primary"
4447
    else:
4448
      state = "secondary"
4449
    if iv_name is None:
4450
      iv_name = "not_visible"
4451
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4452
    try:
4453
      utils.WriteFile(fpath, data=fdata)
4454
    except EnvironmentError, err:
4455
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4456

    
4457
  @classmethod
4458
  def RemoveCache(cls, dev_path):
4459
    """Remove data for a dev_path.
4460

4461
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
4462
    path name and logging.
4463

4464
    @type dev_path: str
4465
    @param dev_path: the pathname of the device
4466

4467
    @rtype: None
4468

4469
    """
4470
    if dev_path is None:
4471
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
4472
      return
4473
    fpath = cls._ConvertPath(dev_path)
4474
    try:
4475
      utils.RemoveFile(fpath)
4476
    except EnvironmentError, err:
4477
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)