Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 3ae259d3

History | View | Annotate | Download (136.6 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 _GetLvmVgSpaceInfo(name, params):
598
  """Wrapper around C{_GetVgInfo} which checks the storage parameters.
599

600
  @type name: string
601
  @param name: name of the volume group
602
  @type params: list
603
  @param params: list of storage parameters, which in this case should be
604
    containing only one for exclusive storage
605

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

    
614

    
615
def _GetVgInfo(name, excl_stor):
616
  """Retrieves information about a LVM volume group.
617

618
  """
619
  # TODO: GetVGInfo supports returning information for multiple VGs at once
620
  vginfo = bdev.LogicalVolume.GetVGInfo([name], excl_stor)
621
  if vginfo:
622
    vg_free = int(round(vginfo[0][0], 0))
623
    vg_size = int(round(vginfo[0][1], 0))
624
  else:
625
    vg_free = None
626
    vg_size = None
627

    
628
  return {
629
    "type": constants.ST_LVM_VG,
630
    "name": name,
631
    "storage_free": vg_free,
632
    "storage_size": vg_size,
633
    }
634

    
635

    
636
def _GetVgSpindlesInfo(name, excl_stor):
637
  """Retrieves information about spindles in an LVM volume group.
638

639
  @type name: string
640
  @param name: VG name
641
  @type excl_stor: bool
642
  @param excl_stor: exclusive storage
643
  @rtype: dict
644
  @return: dictionary whose keys are "name", "vg_free", "vg_size" for VG name,
645
      free spindles, total spindles respectively
646

647
  """
648
  if excl_stor:
649
    (vg_free, vg_size) = bdev.LogicalVolume.GetVgSpindlesInfo(name)
650
  else:
651
    vg_free = 0
652
    vg_size = 0
653
  return {
654
    "type": constants.ST_LVM_PV,
655
    "name": name,
656
    "storage_free": vg_free,
657
    "storage_size": vg_size,
658
    }
659

    
660

    
661
def _GetHvInfo(name, hvparams, get_hv_fn=hypervisor.GetHypervisor):
662
  """Retrieves node information from a hypervisor.
663

664
  The information returned depends on the hypervisor. Common items:
665

666
    - vg_size is the size of the configured volume group in MiB
667
    - vg_free is the free size of the volume group in MiB
668
    - memory_dom0 is the memory allocated for domain0 in MiB
669
    - memory_free is the currently available (free) ram in MiB
670
    - memory_total is the total number of ram in MiB
671
    - hv_version: the hypervisor version, if available
672

673
  @type hvparams: dict of string
674
  @param hvparams: the hypervisor's hvparams
675

676
  """
677
  return get_hv_fn(name).GetNodeInfo(hvparams=hvparams)
678

    
679

    
680
def _GetHvInfoAll(hv_specs, get_hv_fn=hypervisor.GetHypervisor):
681
  """Retrieves node information for all hypervisors.
682

683
  See C{_GetHvInfo} for information on the output.
684

685
  @type hv_specs: list of pairs (string, dict of strings)
686
  @param hv_specs: list of pairs of a hypervisor's name and its hvparams
687

688
  """
689
  if hv_specs is None:
690
    return None
691

    
692
  result = []
693
  for hvname, hvparams in hv_specs:
694
    result.append(_GetHvInfo(hvname, hvparams, get_hv_fn))
695
  return result
696

    
697

    
698
def _GetNamedNodeInfo(names, fn):
699
  """Calls C{fn} for all names in C{names} and returns a dictionary.
700

701
  @rtype: None or dict
702

703
  """
704
  if names is None:
705
    return None
706
  else:
707
    return map(fn, names)
708

    
709

    
710
def GetNodeInfo(storage_units, hv_specs):
711
  """Gives back a hash with different information about the node.
712

713
  @type storage_units: list of tuples (string, string, list)
714
  @param storage_units: List of tuples (storage unit, identifier, parameters) to
715
    ask for disk space information. In case of lvm-vg, the identifier is
716
    the VG name. The parameters can contain additional, storage-type-specific
717
    parameters, for example exclusive storage for lvm storage.
718
  @type hv_specs: list of pairs (string, dict of strings)
719
  @param hv_specs: list of pairs of a hypervisor's name and its hvparams
720
  @rtype: tuple; (string, None/dict, None/dict)
721
  @return: Tuple containing boot ID, volume group information and hypervisor
722
    information
723

724
  """
725
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
726
  storage_info = _GetNamedNodeInfo(
727
    storage_units,
728
    (lambda (storage_type, storage_key, storage_params):
729
        _ApplyStorageInfoFunction(storage_type, storage_key, storage_params)))
730
  hv_info = _GetHvInfoAll(hv_specs)
731
  return (bootid, storage_info, hv_info)
732

    
733

    
734
def _GetFileStorageSpaceInfo(path, params):
735
  """Wrapper around filestorage.GetSpaceInfo.
736

737
  The purpose of this wrapper is to call filestorage.GetFileStorageSpaceInfo
738
  and ignore the *args parameter to not leak it into the filestorage
739
  module's code.
740

741
  @see: C{filestorage.GetFileStorageSpaceInfo} for description of the
742
    parameters.
743

744
  """
745
  _CheckStorageParams(params, 0)
746
  return filestorage.GetFileStorageSpaceInfo(path)
747

    
748

    
749
# FIXME: implement storage reporting for all missing storage types.
750
_STORAGE_TYPE_INFO_FN = {
751
  constants.ST_BLOCK: None,
752
  constants.ST_DISKLESS: None,
753
  constants.ST_EXT: None,
754
  constants.ST_FILE: _GetFileStorageSpaceInfo,
755
  constants.ST_LVM_PV: _GetVgSpindlesInfo,
756
  constants.ST_LVM_VG: _GetLvmVgSpaceInfo,
757
  constants.ST_RADOS: None,
758
}
759

    
760

    
761
def _ApplyStorageInfoFunction(storage_type, storage_key, *args):
762
  """Looks up and applies the correct function to calculate free and total
763
  storage for the given storage type.
764

765
  @type storage_type: string
766
  @param storage_type: the storage type for which the storage shall be reported.
767
  @type storage_key: string
768
  @param storage_key: identifier of a storage unit, e.g. the volume group name
769
    of an LVM storage unit
770
  @type args: any
771
  @param args: various parameters that can be used for storage reporting. These
772
    parameters and their semantics vary from storage type to storage type and
773
    are just propagated in this function.
774
  @return: the results of the application of the storage space function (see
775
    _STORAGE_TYPE_INFO_FN) if storage space reporting is implemented for that
776
    storage type
777
  @raises NotImplementedError: for storage types who don't support space
778
    reporting yet
779
  """
780
  fn = _STORAGE_TYPE_INFO_FN[storage_type]
781
  if fn is not None:
782
    return fn(storage_key, *args)
783
  else:
784
    raise NotImplementedError
785

    
786

    
787
def _CheckExclusivePvs(pvi_list):
788
  """Check that PVs are not shared among LVs
789

790
  @type pvi_list: list of L{objects.LvmPvInfo} objects
791
  @param pvi_list: information about the PVs
792

793
  @rtype: list of tuples (string, list of strings)
794
  @return: offending volumes, as tuples: (pv_name, [lv1_name, lv2_name...])
795

796
  """
797
  res = []
798
  for pvi in pvi_list:
799
    if len(pvi.lv_list) > 1:
800
      res.append((pvi.name, pvi.lv_list))
801
  return res
802

    
803

    
804
def _VerifyHypervisors(what, vm_capable, result, all_hvparams,
805
                       get_hv_fn=hypervisor.GetHypervisor):
806
  """Verifies the hypervisor. Appends the results to the 'results' list.
807

808
  @type what: C{dict}
809
  @param what: a dictionary of things to check
810
  @type vm_capable: boolean
811
  @param vm_capable: whether or not this node is vm capable
812
  @type result: dict
813
  @param result: dictionary of verification results; results of the
814
    verifications in this function will be added here
815
  @type all_hvparams: dict of dict of string
816
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
817
  @type get_hv_fn: function
818
  @param get_hv_fn: function to retrieve the hypervisor, to improve testability
819

820
  """
821
  if not vm_capable:
822
    return
823

    
824
  if constants.NV_HYPERVISOR in what:
825
    result[constants.NV_HYPERVISOR] = {}
826
    for hv_name in what[constants.NV_HYPERVISOR]:
827
      hvparams = all_hvparams[hv_name]
828
      try:
829
        val = get_hv_fn(hv_name).Verify(hvparams=hvparams)
830
      except errors.HypervisorError, err:
831
        val = "Error while checking hypervisor: %s" % str(err)
832
      result[constants.NV_HYPERVISOR][hv_name] = val
833

    
834

    
835
def _VerifyHvparams(what, vm_capable, result,
836
                    get_hv_fn=hypervisor.GetHypervisor):
837
  """Verifies the hvparams. Appends the results to the 'results' list.
838

839
  @type what: C{dict}
840
  @param what: a dictionary of things to check
841
  @type vm_capable: boolean
842
  @param vm_capable: whether or not this node is vm capable
843
  @type result: dict
844
  @param result: dictionary of verification results; results of the
845
    verifications in this function will be added here
846
  @type get_hv_fn: function
847
  @param get_hv_fn: function to retrieve the hypervisor, to improve testability
848

849
  """
850
  if not vm_capable:
851
    return
852

    
853
  if constants.NV_HVPARAMS in what:
854
    result[constants.NV_HVPARAMS] = []
855
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
856
      try:
857
        logging.info("Validating hv %s, %s", hv_name, hvparms)
858
        get_hv_fn(hv_name).ValidateParameters(hvparms)
859
      except errors.HypervisorError, err:
860
        result[constants.NV_HVPARAMS].append((source, hv_name, str(err)))
861

    
862

    
863
def _VerifyInstanceList(what, vm_capable, result, all_hvparams):
864
  """Verifies the instance list.
865

866
  @type what: C{dict}
867
  @param what: a dictionary of things to check
868
  @type vm_capable: boolean
869
  @param vm_capable: whether or not this node is vm capable
870
  @type result: dict
871
  @param result: dictionary of verification results; results of the
872
    verifications in this function will be added here
873
  @type all_hvparams: dict of dict of string
874
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
875

876
  """
877
  if constants.NV_INSTANCELIST in what and vm_capable:
878
    # GetInstanceList can fail
879
    try:
880
      val = GetInstanceList(what[constants.NV_INSTANCELIST],
881
                            all_hvparams=all_hvparams)
882
    except RPCFail, err:
883
      val = str(err)
884
    result[constants.NV_INSTANCELIST] = val
885

    
886

    
887
def _VerifyNodeInfo(what, vm_capable, result, all_hvparams):
888
  """Verifies the node info.
889

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

900
  """
901
  if constants.NV_HVINFO in what and vm_capable:
902
    hvname = what[constants.NV_HVINFO]
903
    hyper = hypervisor.GetHypervisor(hvname)
904
    hvparams = all_hvparams[hvname]
905
    result[constants.NV_HVINFO] = hyper.GetNodeInfo(hvparams=hvparams)
906

    
907

    
908
def VerifyNode(what, cluster_name, all_hvparams):
909
  """Verify the status of the local node.
910

911
  Based on the input L{what} parameter, various checks are done on the
912
  local node.
913

914
  If the I{filelist} key is present, this list of
915
  files is checksummed and the file/checksum pairs are returned.
916

917
  If the I{nodelist} key is present, we check that we have
918
  connectivity via ssh with the target nodes (and check the hostname
919
  report).
920

921
  If the I{node-net-test} key is present, we check that we have
922
  connectivity to the given nodes via both primary IP and, if
923
  applicable, secondary IPs.
924

925
  @type what: C{dict}
926
  @param what: a dictionary of things to check:
927
      - filelist: list of files for which to compute checksums
928
      - nodelist: list of nodes we should check ssh communication with
929
      - node-net-test: list of nodes we should check node daemon port
930
        connectivity with
931
      - hypervisor: list with hypervisors to run the verify for
932
  @type cluster_name: string
933
  @param cluster_name: the cluster's name
934
  @type all_hvparams: dict of dict of strings
935
  @param all_hvparams: a dictionary mapping hypervisor names to hvparams
936
  @rtype: dict
937
  @return: a dictionary with the same keys as the input dict, and
938
      values representing the result of the checks
939

940
  """
941
  result = {}
942
  my_name = netutils.Hostname.GetSysName()
943
  port = netutils.GetDaemonPort(constants.NODED)
944
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
945

    
946
  _VerifyHypervisors(what, vm_capable, result, all_hvparams)
947
  _VerifyHvparams(what, vm_capable, result)
948

    
949
  if constants.NV_FILELIST in what:
950
    fingerprints = utils.FingerprintFiles(map(vcluster.LocalizeVirtualPath,
951
                                              what[constants.NV_FILELIST]))
952
    result[constants.NV_FILELIST] = \
953
      dict((vcluster.MakeVirtualPath(key), value)
954
           for (key, value) in fingerprints.items())
955

    
956
  if constants.NV_NODELIST in what:
957
    (nodes, bynode) = what[constants.NV_NODELIST]
958

    
959
    # Add nodes from other groups (different for each node)
960
    try:
961
      nodes.extend(bynode[my_name])
962
    except KeyError:
963
      pass
964

    
965
    # Use a random order
966
    random.shuffle(nodes)
967

    
968
    # Try to contact all nodes
969
    val = {}
970
    for node in nodes:
971
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
972
      if not success:
973
        val[node] = message
974

    
975
    result[constants.NV_NODELIST] = val
976

    
977
  if constants.NV_NODENETTEST in what:
978
    result[constants.NV_NODENETTEST] = tmp = {}
979
    my_pip = my_sip = None
980
    for name, pip, sip in what[constants.NV_NODENETTEST]:
981
      if name == my_name:
982
        my_pip = pip
983
        my_sip = sip
984
        break
985
    if not my_pip:
986
      tmp[my_name] = ("Can't find my own primary/secondary IP"
987
                      " in the node list")
988
    else:
989
      for name, pip, sip in what[constants.NV_NODENETTEST]:
990
        fail = []
991
        if not netutils.TcpPing(pip, port, source=my_pip):
992
          fail.append("primary")
993
        if sip != pip:
994
          if not netutils.TcpPing(sip, port, source=my_sip):
995
            fail.append("secondary")
996
        if fail:
997
          tmp[name] = ("failure using the %s interface(s)" %
998
                       " and ".join(fail))
999

    
1000
  if constants.NV_MASTERIP in what:
1001
    # FIXME: add checks on incoming data structures (here and in the
1002
    # rest of the function)
1003
    master_name, master_ip = what[constants.NV_MASTERIP]
1004
    if master_name == my_name:
1005
      source = constants.IP4_ADDRESS_LOCALHOST
1006
    else:
1007
      source = None
1008
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
1009
                                                     source=source)
1010

    
1011
  if constants.NV_USERSCRIPTS in what:
1012
    result[constants.NV_USERSCRIPTS] = \
1013
      [script for script in what[constants.NV_USERSCRIPTS]
1014
       if not utils.IsExecutable(script)]
1015

    
1016
  if constants.NV_OOB_PATHS in what:
1017
    result[constants.NV_OOB_PATHS] = tmp = []
1018
    for path in what[constants.NV_OOB_PATHS]:
1019
      try:
1020
        st = os.stat(path)
1021
      except OSError, err:
1022
        tmp.append("error stating out of band helper: %s" % err)
1023
      else:
1024
        if stat.S_ISREG(st.st_mode):
1025
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
1026
            tmp.append(None)
1027
          else:
1028
            tmp.append("out of band helper %s is not executable" % path)
1029
        else:
1030
          tmp.append("out of band helper %s is not a file" % path)
1031

    
1032
  if constants.NV_LVLIST in what and vm_capable:
1033
    try:
1034
      val = GetVolumeList(utils.ListVolumeGroups().keys())
1035
    except RPCFail, err:
1036
      val = str(err)
1037
    result[constants.NV_LVLIST] = val
1038

    
1039
  _VerifyInstanceList(what, vm_capable, result, all_hvparams)
1040

    
1041
  if constants.NV_VGLIST in what and vm_capable:
1042
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
1043

    
1044
  if constants.NV_PVLIST in what and vm_capable:
1045
    check_exclusive_pvs = constants.NV_EXCLUSIVEPVS in what
1046
    val = bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
1047
                                       filter_allocatable=False,
1048
                                       include_lvs=check_exclusive_pvs)
1049
    if check_exclusive_pvs:
1050
      result[constants.NV_EXCLUSIVEPVS] = _CheckExclusivePvs(val)
1051
      for pvi in val:
1052
        # Avoid sending useless data on the wire
1053
        pvi.lv_list = []
1054
    result[constants.NV_PVLIST] = map(objects.LvmPvInfo.ToDict, val)
1055

    
1056
  if constants.NV_VERSION in what:
1057
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
1058
                                    constants.RELEASE_VERSION)
1059

    
1060
  _VerifyNodeInfo(what, vm_capable, result, all_hvparams)
1061

    
1062
  if constants.NV_DRBDVERSION in what and vm_capable:
1063
    try:
1064
      drbd_version = DRBD8.GetProcInfo().GetVersionString()
1065
    except errors.BlockDeviceError, err:
1066
      logging.warning("Can't get DRBD version", exc_info=True)
1067
      drbd_version = str(err)
1068
    result[constants.NV_DRBDVERSION] = drbd_version
1069

    
1070
  if constants.NV_DRBDLIST in what and vm_capable:
1071
    try:
1072
      used_minors = drbd.DRBD8.GetUsedDevs()
1073
    except errors.BlockDeviceError, err:
1074
      logging.warning("Can't get used minors list", exc_info=True)
1075
      used_minors = str(err)
1076
    result[constants.NV_DRBDLIST] = used_minors
1077

    
1078
  if constants.NV_DRBDHELPER in what and vm_capable:
1079
    status = True
1080
    try:
1081
      payload = drbd.DRBD8.GetUsermodeHelper()
1082
    except errors.BlockDeviceError, err:
1083
      logging.error("Can't get DRBD usermode helper: %s", str(err))
1084
      status = False
1085
      payload = str(err)
1086
    result[constants.NV_DRBDHELPER] = (status, payload)
1087

    
1088
  if constants.NV_NODESETUP in what:
1089
    result[constants.NV_NODESETUP] = tmpr = []
1090
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
1091
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
1092
                  " under /sys, missing required directories /sys/block"
1093
                  " and /sys/class/net")
1094
    if (not os.path.isdir("/proc/sys") or
1095
        not os.path.isfile("/proc/sysrq-trigger")):
1096
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
1097
                  " under /proc, missing required directory /proc/sys and"
1098
                  " the file /proc/sysrq-trigger")
1099

    
1100
  if constants.NV_TIME in what:
1101
    result[constants.NV_TIME] = utils.SplitTime(time.time())
1102

    
1103
  if constants.NV_OSLIST in what and vm_capable:
1104
    result[constants.NV_OSLIST] = DiagnoseOS()
1105

    
1106
  if constants.NV_BRIDGES in what and vm_capable:
1107
    result[constants.NV_BRIDGES] = [bridge
1108
                                    for bridge in what[constants.NV_BRIDGES]
1109
                                    if not utils.BridgeExists(bridge)]
1110

    
1111
  if what.get(constants.NV_FILE_STORAGE_PATHS) == my_name:
1112
    result[constants.NV_FILE_STORAGE_PATHS] = \
1113
      bdev.ComputeWrongFileStoragePaths()
1114

    
1115
  return result
1116

    
1117

    
1118
def GetBlockDevSizes(devices):
1119
  """Return the size of the given block devices
1120

1121
  @type devices: list
1122
  @param devices: list of block device nodes to query
1123
  @rtype: dict
1124
  @return:
1125
    dictionary of all block devices under /dev (key). The value is their
1126
    size in MiB.
1127

1128
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
1129

1130
  """
1131
  DEV_PREFIX = "/dev/"
1132
  blockdevs = {}
1133

    
1134
  for devpath in devices:
1135
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
1136
      continue
1137

    
1138
    try:
1139
      st = os.stat(devpath)
1140
    except EnvironmentError, err:
1141
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
1142
      continue
1143

    
1144
    if stat.S_ISBLK(st.st_mode):
1145
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
1146
      if result.failed:
1147
        # We don't want to fail, just do not list this device as available
1148
        logging.warning("Cannot get size for block device %s", devpath)
1149
        continue
1150

    
1151
      size = int(result.stdout) / (1024 * 1024)
1152
      blockdevs[devpath] = size
1153
  return blockdevs
1154

    
1155

    
1156
def GetVolumeList(vg_names):
1157
  """Compute list of logical volumes and their size.
1158

1159
  @type vg_names: list
1160
  @param vg_names: the volume groups whose LVs we should list, or
1161
      empty for all volume groups
1162
  @rtype: dict
1163
  @return:
1164
      dictionary of all partions (key) with value being a tuple of
1165
      their size (in MiB), inactive and online status::
1166

1167
        {'xenvg/test1': ('20.06', True, True)}
1168

1169
      in case of errors, a string is returned with the error
1170
      details.
1171

1172
  """
1173
  lvs = {}
1174
  sep = "|"
1175
  if not vg_names:
1176
    vg_names = []
1177
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1178
                         "--separator=%s" % sep,
1179
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
1180
  if result.failed:
1181
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
1182

    
1183
  for line in result.stdout.splitlines():
1184
    line = line.strip()
1185
    match = _LVSLINE_REGEX.match(line)
1186
    if not match:
1187
      logging.error("Invalid line returned from lvs output: '%s'", line)
1188
      continue
1189
    vg_name, name, size, attr = match.groups()
1190
    inactive = attr[4] == "-"
1191
    online = attr[5] == "o"
1192
    virtual = attr[0] == "v"
1193
    if virtual:
1194
      # we don't want to report such volumes as existing, since they
1195
      # don't really hold data
1196
      continue
1197
    lvs[vg_name + "/" + name] = (size, inactive, online)
1198

    
1199
  return lvs
1200

    
1201

    
1202
def ListVolumeGroups():
1203
  """List the volume groups and their size.
1204

1205
  @rtype: dict
1206
  @return: dictionary with keys volume name and values the
1207
      size of the volume
1208

1209
  """
1210
  return utils.ListVolumeGroups()
1211

    
1212

    
1213
def NodeVolumes():
1214
  """List all volumes on this node.
1215

1216
  @rtype: list
1217
  @return:
1218
    A list of dictionaries, each having four keys:
1219
      - name: the logical volume name,
1220
      - size: the size of the logical volume
1221
      - dev: the physical device on which the LV lives
1222
      - vg: the volume group to which it belongs
1223

1224
    In case of errors, we return an empty list and log the
1225
    error.
1226

1227
    Note that since a logical volume can live on multiple physical
1228
    volumes, the resulting list might include a logical volume
1229
    multiple times.
1230

1231
  """
1232
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1233
                         "--separator=|",
1234
                         "--options=lv_name,lv_size,devices,vg_name"])
1235
  if result.failed:
1236
    _Fail("Failed to list logical volumes, lvs output: %s",
1237
          result.output)
1238

    
1239
  def parse_dev(dev):
1240
    return dev.split("(")[0]
1241

    
1242
  def handle_dev(dev):
1243
    return [parse_dev(x) for x in dev.split(",")]
1244

    
1245
  def map_line(line):
1246
    line = [v.strip() for v in line]
1247
    return [{"name": line[0], "size": line[1],
1248
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
1249

    
1250
  all_devs = []
1251
  for line in result.stdout.splitlines():
1252
    if line.count("|") >= 3:
1253
      all_devs.extend(map_line(line.split("|")))
1254
    else:
1255
      logging.warning("Strange line in the output from lvs: '%s'", line)
1256
  return all_devs
1257

    
1258

    
1259
def BridgesExist(bridges_list):
1260
  """Check if a list of bridges exist on the current node.
1261

1262
  @rtype: boolean
1263
  @return: C{True} if all of them exist, C{False} otherwise
1264

1265
  """
1266
  missing = []
1267
  for bridge in bridges_list:
1268
    if not utils.BridgeExists(bridge):
1269
      missing.append(bridge)
1270

    
1271
  if missing:
1272
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
1273

    
1274

    
1275
def GetInstanceListForHypervisor(hname, hvparams=None,
1276
                                 get_hv_fn=hypervisor.GetHypervisor):
1277
  """Provides a list of instances of the given hypervisor.
1278

1279
  @type hname: string
1280
  @param hname: name of the hypervisor
1281
  @type hvparams: dict of strings
1282
  @param hvparams: hypervisor parameters for the given hypervisor
1283
  @type get_hv_fn: function
1284
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1285
    name; optional parameter to increase testability
1286

1287
  @rtype: list
1288
  @return: a list of all running instances on the current node
1289
    - instance1.example.com
1290
    - instance2.example.com
1291

1292
  """
1293
  results = []
1294
  try:
1295
    hv = get_hv_fn(hname)
1296
    names = hv.ListInstances(hvparams=hvparams)
1297
    results.extend(names)
1298
  except errors.HypervisorError, err:
1299
    _Fail("Error enumerating instances (hypervisor %s): %s",
1300
          hname, err, exc=True)
1301
  return results
1302

    
1303

    
1304
def GetInstanceList(hypervisor_list, all_hvparams=None,
1305
                    get_hv_fn=hypervisor.GetHypervisor):
1306
  """Provides a list of instances.
1307

1308
  @type hypervisor_list: list
1309
  @param hypervisor_list: the list of hypervisors to query information
1310
  @type all_hvparams: dict of dict of strings
1311
  @param all_hvparams: a dictionary mapping hypervisor types to respective
1312
    cluster-wide hypervisor parameters
1313
  @type get_hv_fn: function
1314
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1315
    name; optional parameter to increase testability
1316

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

1322
  """
1323
  results = []
1324
  for hname in hypervisor_list:
1325
    hvparams = all_hvparams[hname]
1326
    results.extend(GetInstanceListForHypervisor(hname, hvparams=hvparams,
1327
                                                get_hv_fn=get_hv_fn))
1328
  return results
1329

    
1330

    
1331
def GetInstanceInfo(instance, hname, hvparams=None):
1332
  """Gives back the information about an instance as a dictionary.
1333

1334
  @type instance: string
1335
  @param instance: the instance name
1336
  @type hname: string
1337
  @param hname: the hypervisor type of the instance
1338
  @type hvparams: dict of strings
1339
  @param hvparams: the instance's hvparams
1340

1341
  @rtype: dict
1342
  @return: dictionary with the following keys:
1343
      - memory: memory size of instance (int)
1344
      - state: xen state of instance (string)
1345
      - time: cpu time of instance (float)
1346
      - vcpus: the number of vcpus (int)
1347

1348
  """
1349
  output = {}
1350

    
1351
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance,
1352
                                                          hvparams=hvparams)
1353
  if iinfo is not None:
1354
    output["memory"] = iinfo[2]
1355
    output["vcpus"] = iinfo[3]
1356
    output["state"] = iinfo[4]
1357
    output["time"] = iinfo[5]
1358

    
1359
  return output
1360

    
1361

    
1362
def GetInstanceMigratable(instance):
1363
  """Computes whether an instance can be migrated.
1364

1365
  @type instance: L{objects.Instance}
1366
  @param instance: object representing the instance to be checked.
1367

1368
  @rtype: tuple
1369
  @return: tuple of (result, description) where:
1370
      - result: whether the instance can be migrated or not
1371
      - description: a description of the issue, if relevant
1372

1373
  """
1374
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1375
  iname = instance.name
1376
  if iname not in hyper.ListInstances(instance.hvparams):
1377
    _Fail("Instance %s is not running", iname)
1378

    
1379
  for idx in range(len(instance.disks)):
1380
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1381
    if not os.path.islink(link_name):
1382
      logging.warning("Instance %s is missing symlink %s for disk %d",
1383
                      iname, link_name, idx)
1384

    
1385

    
1386
def GetAllInstancesInfo(hypervisor_list, all_hvparams):
1387
  """Gather data about all instances.
1388

1389
  This is the equivalent of L{GetInstanceInfo}, except that it
1390
  computes data for all instances at once, thus being faster if one
1391
  needs data about more than one instance.
1392

1393
  @type hypervisor_list: list
1394
  @param hypervisor_list: list of hypervisors to query for instance data
1395
  @type all_hvparams: dict of dict of strings
1396
  @param all_hvparams: mapping of hypervisor names to hvparams
1397

1398
  @rtype: dict
1399
  @return: dictionary of instance: data, with data having the following keys:
1400
      - memory: memory size of instance (int)
1401
      - state: xen state of instance (string)
1402
      - time: cpu time of instance (float)
1403
      - vcpus: the number of vcpus
1404

1405
  """
1406
  output = {}
1407

    
1408
  for hname in hypervisor_list:
1409
    hvparams = all_hvparams[hname]
1410
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo(hvparams)
1411
    if iinfo:
1412
      for name, _, memory, vcpus, state, times in iinfo:
1413
        value = {
1414
          "memory": memory,
1415
          "vcpus": vcpus,
1416
          "state": state,
1417
          "time": times,
1418
          }
1419
        if name in output:
1420
          # we only check static parameters, like memory and vcpus,
1421
          # and not state and time which can change between the
1422
          # invocations of the different hypervisors
1423
          for key in "memory", "vcpus":
1424
            if value[key] != output[name][key]:
1425
              _Fail("Instance %s is running twice"
1426
                    " with different parameters", name)
1427
        output[name] = value
1428

    
1429
  return output
1430

    
1431

    
1432
def _InstanceLogName(kind, os_name, instance, component):
1433
  """Compute the OS log filename for a given instance and operation.
1434

1435
  The instance name and os name are passed in as strings since not all
1436
  operations have these as part of an instance object.
1437

1438
  @type kind: string
1439
  @param kind: the operation type (e.g. add, import, etc.)
1440
  @type os_name: string
1441
  @param os_name: the os name
1442
  @type instance: string
1443
  @param instance: the name of the instance being imported/added/etc.
1444
  @type component: string or None
1445
  @param component: the name of the component of the instance being
1446
      transferred
1447

1448
  """
1449
  # TODO: Use tempfile.mkstemp to create unique filename
1450
  if component:
1451
    assert "/" not in component
1452
    c_msg = "-%s" % component
1453
  else:
1454
    c_msg = ""
1455
  base = ("%s-%s-%s%s-%s.log" %
1456
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1457
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1458

    
1459

    
1460
def InstanceOsAdd(instance, reinstall, debug):
1461
  """Add an OS to an instance.
1462

1463
  @type instance: L{objects.Instance}
1464
  @param instance: Instance whose OS is to be installed
1465
  @type reinstall: boolean
1466
  @param reinstall: whether this is an instance reinstall
1467
  @type debug: integer
1468
  @param debug: debug level, passed to the OS scripts
1469
  @rtype: None
1470

1471
  """
1472
  inst_os = OSFromDisk(instance.os)
1473

    
1474
  create_env = OSEnvironment(instance, inst_os, debug)
1475
  if reinstall:
1476
    create_env["INSTANCE_REINSTALL"] = "1"
1477

    
1478
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1479

    
1480
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1481
                        cwd=inst_os.path, output=logfile, reset_env=True)
1482
  if result.failed:
1483
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1484
                  " output: %s", result.cmd, result.fail_reason, logfile,
1485
                  result.output)
1486
    lines = [utils.SafeEncode(val)
1487
             for val in utils.TailFile(logfile, lines=20)]
1488
    _Fail("OS create script failed (%s), last lines in the"
1489
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1490

    
1491

    
1492
def RunRenameInstance(instance, old_name, debug):
1493
  """Run the OS rename script for an instance.
1494

1495
  @type instance: L{objects.Instance}
1496
  @param instance: Instance whose OS is to be installed
1497
  @type old_name: string
1498
  @param old_name: previous instance name
1499
  @type debug: integer
1500
  @param debug: debug level, passed to the OS scripts
1501
  @rtype: boolean
1502
  @return: the success of the operation
1503

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

    
1507
  rename_env = OSEnvironment(instance, inst_os, debug)
1508
  rename_env["OLD_INSTANCE_NAME"] = old_name
1509

    
1510
  logfile = _InstanceLogName("rename", instance.os,
1511
                             "%s-%s" % (old_name, instance.name), None)
1512

    
1513
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1514
                        cwd=inst_os.path, output=logfile, reset_env=True)
1515

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

    
1524

    
1525
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1526
  """Returns symlink path for block device.
1527

1528
  """
1529
  if _dir is None:
1530
    _dir = pathutils.DISK_LINKS_DIR
1531

    
1532
  return utils.PathJoin(_dir,
1533
                        ("%s%s%s" %
1534
                         (instance_name, constants.DISK_SEPARATOR, idx)))
1535

    
1536

    
1537
def _SymlinkBlockDev(instance_name, device_path, idx):
1538
  """Set up symlinks to a instance's block device.
1539

1540
  This is an auxiliary function run when an instance is start (on the primary
1541
  node) or when an instance is migrated (on the target node).
1542

1543

1544
  @param instance_name: the name of the target instance
1545
  @param device_path: path of the physical block device, on the node
1546
  @param idx: the disk index
1547
  @return: absolute path to the disk's symlink
1548

1549
  """
1550
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1551
  try:
1552
    os.symlink(device_path, link_name)
1553
  except OSError, err:
1554
    if err.errno == errno.EEXIST:
1555
      if (not os.path.islink(link_name) or
1556
          os.readlink(link_name) != device_path):
1557
        os.remove(link_name)
1558
        os.symlink(device_path, link_name)
1559
    else:
1560
      raise
1561

    
1562
  return link_name
1563

    
1564

    
1565
def _RemoveBlockDevLinks(instance_name, disks):
1566
  """Remove the block device symlinks belonging to the given instance.
1567

1568
  """
1569
  for idx, _ in enumerate(disks):
1570
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1571
    if os.path.islink(link_name):
1572
      try:
1573
        os.remove(link_name)
1574
      except OSError:
1575
        logging.exception("Can't remove symlink '%s'", link_name)
1576

    
1577

    
1578
def _GatherAndLinkBlockDevs(instance):
1579
  """Set up an instance's block device(s).
1580

1581
  This is run on the primary node at instance startup. The block
1582
  devices must be already assembled.
1583

1584
  @type instance: L{objects.Instance}
1585
  @param instance: the instance whose disks we shoul assemble
1586
  @rtype: list
1587
  @return: list of (disk_object, device_path)
1588

1589
  """
1590
  block_devices = []
1591
  for idx, disk in enumerate(instance.disks):
1592
    device = _RecursiveFindBD(disk)
1593
    if device is None:
1594
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1595
                                    str(disk))
1596
    device.Open()
1597
    try:
1598
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1599
    except OSError, e:
1600
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1601
                                    e.strerror)
1602

    
1603
    block_devices.append((disk, link_name))
1604

    
1605
  return block_devices
1606

    
1607

    
1608
def StartInstance(instance, startup_paused, reason, store_reason=True):
1609
  """Start an instance.
1610

1611
  @type instance: L{objects.Instance}
1612
  @param instance: the instance object
1613
  @type startup_paused: bool
1614
  @param instance: pause instance at startup?
1615
  @type reason: list of reasons
1616
  @param reason: the reason trail for this startup
1617
  @type store_reason: boolean
1618
  @param store_reason: whether to store the shutdown reason trail on file
1619
  @rtype: None
1620

1621
  """
1622
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1623
                                                   instance.hvparams)
1624

    
1625
  if instance.name in running_instances:
1626
    logging.info("Instance %s already running, not starting", instance.name)
1627
    return
1628

    
1629
  try:
1630
    block_devices = _GatherAndLinkBlockDevs(instance)
1631
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1632
    hyper.StartInstance(instance, block_devices, startup_paused)
1633
    if store_reason:
1634
      _StoreInstReasonTrail(instance.name, reason)
1635
  except errors.BlockDeviceError, err:
1636
    _Fail("Block device error: %s", err, exc=True)
1637
  except errors.HypervisorError, err:
1638
    _RemoveBlockDevLinks(instance.name, instance.disks)
1639
    _Fail("Hypervisor error: %s", err, exc=True)
1640

    
1641

    
1642
def InstanceShutdown(instance, timeout, reason, store_reason=True):
1643
  """Shut an instance down.
1644

1645
  @note: this functions uses polling with a hardcoded timeout.
1646

1647
  @type instance: L{objects.Instance}
1648
  @param instance: the instance object
1649
  @type timeout: integer
1650
  @param timeout: maximum timeout for soft shutdown
1651
  @type reason: list of reasons
1652
  @param reason: the reason trail for this shutdown
1653
  @type store_reason: boolean
1654
  @param store_reason: whether to store the shutdown reason trail on file
1655
  @rtype: None
1656

1657
  """
1658
  hv_name = instance.hypervisor
1659
  hyper = hypervisor.GetHypervisor(hv_name)
1660
  iname = instance.name
1661

    
1662
  if instance.name not in hyper.ListInstances(instance.hvparams):
1663
    logging.info("Instance %s not running, doing nothing", iname)
1664
    return
1665

    
1666
  class _TryShutdown:
1667
    def __init__(self):
1668
      self.tried_once = False
1669

    
1670
    def __call__(self):
1671
      if iname not in hyper.ListInstances(instance.hvparams):
1672
        return
1673

    
1674
      try:
1675
        hyper.StopInstance(instance, retry=self.tried_once)
1676
        if store_reason:
1677
          _StoreInstReasonTrail(instance.name, reason)
1678
      except errors.HypervisorError, err:
1679
        if iname not in hyper.ListInstances(instance.hvparams):
1680
          # if the instance is no longer existing, consider this a
1681
          # success and go to cleanup
1682
          return
1683

    
1684
        _Fail("Failed to stop instance %s: %s", iname, err)
1685

    
1686
      self.tried_once = True
1687

    
1688
      raise utils.RetryAgain()
1689

    
1690
  try:
1691
    utils.Retry(_TryShutdown(), 5, timeout)
1692
  except utils.RetryTimeout:
1693
    # the shutdown did not succeed
1694
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1695

    
1696
    try:
1697
      hyper.StopInstance(instance, force=True)
1698
    except errors.HypervisorError, err:
1699
      if iname in hyper.ListInstances(instance.hvparams):
1700
        # only raise an error if the instance still exists, otherwise
1701
        # the error could simply be "instance ... unknown"!
1702
        _Fail("Failed to force stop instance %s: %s", iname, err)
1703

    
1704
    time.sleep(1)
1705

    
1706
    if iname in hyper.ListInstances(instance.hvparams):
1707
      _Fail("Could not shutdown instance %s even by destroy", iname)
1708

    
1709
  try:
1710
    hyper.CleanupInstance(instance.name)
1711
  except errors.HypervisorError, err:
1712
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1713

    
1714
  _RemoveBlockDevLinks(iname, instance.disks)
1715

    
1716

    
1717
def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1718
  """Reboot an instance.
1719

1720
  @type instance: L{objects.Instance}
1721
  @param instance: the instance object to reboot
1722
  @type reboot_type: str
1723
  @param reboot_type: the type of reboot, one the following
1724
    constants:
1725
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1726
        instance OS, do not recreate the VM
1727
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1728
        restart the VM (at the hypervisor level)
1729
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1730
        not accepted here, since that mode is handled differently, in
1731
        cmdlib, and translates into full stop and start of the
1732
        instance (instead of a call_instance_reboot RPC)
1733
  @type shutdown_timeout: integer
1734
  @param shutdown_timeout: maximum timeout for soft shutdown
1735
  @type reason: list of reasons
1736
  @param reason: the reason trail for this reboot
1737
  @rtype: None
1738

1739
  """
1740
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1741
                                                   instance.hvparams)
1742

    
1743
  if instance.name not in running_instances:
1744
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1745

    
1746
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1747
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1748
    try:
1749
      hyper.RebootInstance(instance)
1750
    except errors.HypervisorError, err:
1751
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1752
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1753
    try:
1754
      InstanceShutdown(instance, shutdown_timeout, reason, store_reason=False)
1755
      result = StartInstance(instance, False, reason, store_reason=False)
1756
      _StoreInstReasonTrail(instance.name, reason)
1757
      return result
1758
    except errors.HypervisorError, err:
1759
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1760
  else:
1761
    _Fail("Invalid reboot_type received: %s", reboot_type)
1762

    
1763

    
1764
def InstanceBalloonMemory(instance, memory):
1765
  """Resize an instance's memory.
1766

1767
  @type instance: L{objects.Instance}
1768
  @param instance: the instance object
1769
  @type memory: int
1770
  @param memory: new memory amount in MB
1771
  @rtype: None
1772

1773
  """
1774
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1775
  running = hyper.ListInstances(instance.hvparams)
1776
  if instance.name not in running:
1777
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1778
    return
1779
  try:
1780
    hyper.BalloonInstanceMemory(instance, memory)
1781
  except errors.HypervisorError, err:
1782
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1783

    
1784

    
1785
def MigrationInfo(instance):
1786
  """Gather information about an instance to be migrated.
1787

1788
  @type instance: L{objects.Instance}
1789
  @param instance: the instance definition
1790

1791
  """
1792
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1793
  try:
1794
    info = hyper.MigrationInfo(instance)
1795
  except errors.HypervisorError, err:
1796
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1797
  return info
1798

    
1799

    
1800
def AcceptInstance(instance, info, target):
1801
  """Prepare the node to accept an instance.
1802

1803
  @type instance: L{objects.Instance}
1804
  @param instance: the instance definition
1805
  @type info: string/data (opaque)
1806
  @param info: migration information, from the source node
1807
  @type target: string
1808
  @param target: target host (usually ip), on this node
1809

1810
  """
1811
  # TODO: why is this required only for DTS_EXT_MIRROR?
1812
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1813
    # Create the symlinks, as the disks are not active
1814
    # in any way
1815
    try:
1816
      _GatherAndLinkBlockDevs(instance)
1817
    except errors.BlockDeviceError, err:
1818
      _Fail("Block device error: %s", err, exc=True)
1819

    
1820
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1821
  try:
1822
    hyper.AcceptInstance(instance, info, target)
1823
  except errors.HypervisorError, err:
1824
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1825
      _RemoveBlockDevLinks(instance.name, instance.disks)
1826
    _Fail("Failed to accept instance: %s", err, exc=True)
1827

    
1828

    
1829
def FinalizeMigrationDst(instance, info, success):
1830
  """Finalize any preparation to accept an instance.
1831

1832
  @type instance: L{objects.Instance}
1833
  @param instance: the instance definition
1834
  @type info: string/data (opaque)
1835
  @param info: migration information, from the source node
1836
  @type success: boolean
1837
  @param success: whether the migration was a success or a failure
1838

1839
  """
1840
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1841
  try:
1842
    hyper.FinalizeMigrationDst(instance, info, success)
1843
  except errors.HypervisorError, err:
1844
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1845

    
1846

    
1847
def MigrateInstance(cluster_name, instance, target, live):
1848
  """Migrates an instance to another node.
1849

1850
  @type cluster_name: string
1851
  @param cluster_name: name of the cluster
1852
  @type instance: L{objects.Instance}
1853
  @param instance: the instance definition
1854
  @type target: string
1855
  @param target: the target node name
1856
  @type live: boolean
1857
  @param live: whether the migration should be done live or not (the
1858
      interpretation of this parameter is left to the hypervisor)
1859
  @raise RPCFail: if migration fails for some reason
1860

1861
  """
1862
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1863

    
1864
  try:
1865
    hyper.MigrateInstance(cluster_name, instance, target, live)
1866
  except errors.HypervisorError, err:
1867
    _Fail("Failed to migrate instance: %s", err, exc=True)
1868

    
1869

    
1870
def FinalizeMigrationSource(instance, success, live):
1871
  """Finalize the instance migration on the source node.
1872

1873
  @type instance: L{objects.Instance}
1874
  @param instance: the instance definition of the migrated instance
1875
  @type success: bool
1876
  @param success: whether the migration succeeded or not
1877
  @type live: bool
1878
  @param live: whether the user requested a live migration or not
1879
  @raise RPCFail: If the execution fails for some reason
1880

1881
  """
1882
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1883

    
1884
  try:
1885
    hyper.FinalizeMigrationSource(instance, success, live)
1886
  except Exception, err:  # pylint: disable=W0703
1887
    _Fail("Failed to finalize the migration on the source node: %s", err,
1888
          exc=True)
1889

    
1890

    
1891
def GetMigrationStatus(instance):
1892
  """Get the migration status
1893

1894
  @type instance: L{objects.Instance}
1895
  @param instance: the instance that is being migrated
1896
  @rtype: L{objects.MigrationStatus}
1897
  @return: the status of the current migration (one of
1898
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1899
           progress info that can be retrieved from the hypervisor
1900
  @raise RPCFail: If the migration status cannot be retrieved
1901

1902
  """
1903
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1904
  try:
1905
    return hyper.GetMigrationStatus(instance)
1906
  except Exception, err:  # pylint: disable=W0703
1907
    _Fail("Failed to get migration status: %s", err, exc=True)
1908

    
1909

    
1910
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
1911
  """Creates a block device for an instance.
1912

1913
  @type disk: L{objects.Disk}
1914
  @param disk: the object describing the disk we should create
1915
  @type size: int
1916
  @param size: the size of the physical underlying device, in MiB
1917
  @type owner: str
1918
  @param owner: the name of the instance for which disk is created,
1919
      used for device cache data
1920
  @type on_primary: boolean
1921
  @param on_primary:  indicates if it is the primary node or not
1922
  @type info: string
1923
  @param info: string that will be sent to the physical device
1924
      creation, used for example to set (LVM) tags on LVs
1925
  @type excl_stor: boolean
1926
  @param excl_stor: Whether exclusive_storage is active
1927

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

1932
  """
1933
  # TODO: remove the obsolete "size" argument
1934
  # pylint: disable=W0613
1935
  clist = []
1936
  if disk.children:
1937
    for child in disk.children:
1938
      try:
1939
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1940
      except errors.BlockDeviceError, err:
1941
        _Fail("Can't assemble device %s: %s", child, err)
1942
      if on_primary or disk.AssembleOnSecondary():
1943
        # we need the children open in case the device itself has to
1944
        # be assembled
1945
        try:
1946
          # pylint: disable=E1103
1947
          crdev.Open()
1948
        except errors.BlockDeviceError, err:
1949
          _Fail("Can't make child '%s' read-write: %s", child, err)
1950
      clist.append(crdev)
1951

    
1952
  try:
1953
    device = bdev.Create(disk, clist, excl_stor)
1954
  except errors.BlockDeviceError, err:
1955
    _Fail("Can't create block device: %s", err)
1956

    
1957
  if on_primary or disk.AssembleOnSecondary():
1958
    try:
1959
      device.Assemble()
1960
    except errors.BlockDeviceError, err:
1961
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1962
    if on_primary or disk.OpenOnSecondary():
1963
      try:
1964
        device.Open(force=True)
1965
      except errors.BlockDeviceError, err:
1966
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1967
    DevCacheManager.UpdateCache(device.dev_path, owner,
1968
                                on_primary, disk.iv_name)
1969

    
1970
  device.SetInfo(info)
1971

    
1972
  return device.unique_id
1973

    
1974

    
1975
def _WipeDevice(path, offset, size):
1976
  """This function actually wipes the device.
1977

1978
  @param path: The path to the device to wipe
1979
  @param offset: The offset in MiB in the file
1980
  @param size: The size in MiB to write
1981

1982
  """
1983
  # Internal sizes are always in Mebibytes; if the following "dd" command
1984
  # should use a different block size the offset and size given to this
1985
  # function must be adjusted accordingly before being passed to "dd".
1986
  block_size = 1024 * 1024
1987

    
1988
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1989
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
1990
         "count=%d" % size]
1991
  result = utils.RunCmd(cmd)
1992

    
1993
  if result.failed:
1994
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1995
          result.fail_reason, result.output)
1996

    
1997

    
1998
def BlockdevWipe(disk, offset, size):
1999
  """Wipes a block device.
2000

2001
  @type disk: L{objects.Disk}
2002
  @param disk: the disk object we want to wipe
2003
  @type offset: int
2004
  @param offset: The offset in MiB in the file
2005
  @type size: int
2006
  @param size: The size in MiB to write
2007

2008
  """
2009
  try:
2010
    rdev = _RecursiveFindBD(disk)
2011
  except errors.BlockDeviceError:
2012
    rdev = None
2013

    
2014
  if not rdev:
2015
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
2016

    
2017
  # Do cross verify some of the parameters
2018
  if offset < 0:
2019
    _Fail("Negative offset")
2020
  if size < 0:
2021
    _Fail("Negative size")
2022
  if offset > rdev.size:
2023
    _Fail("Offset is bigger than device size")
2024
  if (offset + size) > rdev.size:
2025
    _Fail("The provided offset and size to wipe is bigger than device size")
2026

    
2027
  _WipeDevice(rdev.dev_path, offset, size)
2028

    
2029

    
2030
def BlockdevPauseResumeSync(disks, pause):
2031
  """Pause or resume the sync of the block device.
2032

2033
  @type disks: list of L{objects.Disk}
2034
  @param disks: the disks object we want to pause/resume
2035
  @type pause: bool
2036
  @param pause: Wheater to pause or resume
2037

2038
  """
2039
  success = []
2040
  for disk in disks:
2041
    try:
2042
      rdev = _RecursiveFindBD(disk)
2043
    except errors.BlockDeviceError:
2044
      rdev = None
2045

    
2046
    if not rdev:
2047
      success.append((False, ("Cannot change sync for device %s:"
2048
                              " device not found" % disk.iv_name)))
2049
      continue
2050

    
2051
    result = rdev.PauseResumeSync(pause)
2052

    
2053
    if result:
2054
      success.append((result, None))
2055
    else:
2056
      if pause:
2057
        msg = "Pause"
2058
      else:
2059
        msg = "Resume"
2060
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
2061

    
2062
  return success
2063

    
2064

    
2065
def BlockdevRemove(disk):
2066
  """Remove a block device.
2067

2068
  @note: This is intended to be called recursively.
2069

2070
  @type disk: L{objects.Disk}
2071
  @param disk: the disk object we should remove
2072
  @rtype: boolean
2073
  @return: the success of the operation
2074

2075
  """
2076
  msgs = []
2077
  try:
2078
    rdev = _RecursiveFindBD(disk)
2079
  except errors.BlockDeviceError, err:
2080
    # probably can't attach
2081
    logging.info("Can't attach to device %s in remove", disk)
2082
    rdev = None
2083
  if rdev is not None:
2084
    r_path = rdev.dev_path
2085
    try:
2086
      rdev.Remove()
2087
    except errors.BlockDeviceError, err:
2088
      msgs.append(str(err))
2089
    if not msgs:
2090
      DevCacheManager.RemoveCache(r_path)
2091

    
2092
  if disk.children:
2093
    for child in disk.children:
2094
      try:
2095
        BlockdevRemove(child)
2096
      except RPCFail, err:
2097
        msgs.append(str(err))
2098

    
2099
  if msgs:
2100
    _Fail("; ".join(msgs))
2101

    
2102

    
2103
def _RecursiveAssembleBD(disk, owner, as_primary):
2104
  """Activate a block device for an instance.
2105

2106
  This is run on the primary and secondary nodes for an instance.
2107

2108
  @note: this function is called recursively.
2109

2110
  @type disk: L{objects.Disk}
2111
  @param disk: the disk we try to assemble
2112
  @type owner: str
2113
  @param owner: the name of the instance which owns the disk
2114
  @type as_primary: boolean
2115
  @param as_primary: if we should make the block device
2116
      read/write
2117

2118
  @return: the assembled device or None (in case no device
2119
      was assembled)
2120
  @raise errors.BlockDeviceError: in case there is an error
2121
      during the activation of the children or the device
2122
      itself
2123

2124
  """
2125
  children = []
2126
  if disk.children:
2127
    mcn = disk.ChildrenNeeded()
2128
    if mcn == -1:
2129
      mcn = 0 # max number of Nones allowed
2130
    else:
2131
      mcn = len(disk.children) - mcn # max number of Nones
2132
    for chld_disk in disk.children:
2133
      try:
2134
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
2135
      except errors.BlockDeviceError, err:
2136
        if children.count(None) >= mcn:
2137
          raise
2138
        cdev = None
2139
        logging.error("Error in child activation (but continuing): %s",
2140
                      str(err))
2141
      children.append(cdev)
2142

    
2143
  if as_primary or disk.AssembleOnSecondary():
2144
    r_dev = bdev.Assemble(disk, children)
2145
    result = r_dev
2146
    if as_primary or disk.OpenOnSecondary():
2147
      r_dev.Open()
2148
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
2149
                                as_primary, disk.iv_name)
2150

    
2151
  else:
2152
    result = True
2153
  return result
2154

    
2155

    
2156
def BlockdevAssemble(disk, owner, as_primary, idx):
2157
  """Activate a block device for an instance.
2158

2159
  This is a wrapper over _RecursiveAssembleBD.
2160

2161
  @rtype: str or boolean
2162
  @return: a C{/dev/...} path for primary nodes, and
2163
      C{True} for secondary nodes
2164

2165
  """
2166
  try:
2167
    result = _RecursiveAssembleBD(disk, owner, as_primary)
2168
    if isinstance(result, BlockDev):
2169
      # pylint: disable=E1103
2170
      result = result.dev_path
2171
      if as_primary:
2172
        _SymlinkBlockDev(owner, result, idx)
2173
  except errors.BlockDeviceError, err:
2174
    _Fail("Error while assembling disk: %s", err, exc=True)
2175
  except OSError, err:
2176
    _Fail("Error while symlinking disk: %s", err, exc=True)
2177

    
2178
  return result
2179

    
2180

    
2181
def BlockdevShutdown(disk):
2182
  """Shut down a block device.
2183

2184
  First, if the device is assembled (Attach() is successful), then
2185
  the device is shutdown. Then the children of the device are
2186
  shutdown.
2187

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

2192
  @type disk: L{objects.Disk}
2193
  @param disk: the description of the disk we should
2194
      shutdown
2195
  @rtype: None
2196

2197
  """
2198
  msgs = []
2199
  r_dev = _RecursiveFindBD(disk)
2200
  if r_dev is not None:
2201
    r_path = r_dev.dev_path
2202
    try:
2203
      r_dev.Shutdown()
2204
      DevCacheManager.RemoveCache(r_path)
2205
    except errors.BlockDeviceError, err:
2206
      msgs.append(str(err))
2207

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

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

    
2218

    
2219
def BlockdevAddchildren(parent_cdev, new_cdevs):
2220
  """Extend a mirrored block device.
2221

2222
  @type parent_cdev: L{objects.Disk}
2223
  @param parent_cdev: the disk to which we should add children
2224
  @type new_cdevs: list of L{objects.Disk}
2225
  @param new_cdevs: the list of children which we should add
2226
  @rtype: None
2227

2228
  """
2229
  parent_bdev = _RecursiveFindBD(parent_cdev)
2230
  if parent_bdev is None:
2231
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
2232
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
2233
  if new_bdevs.count(None) > 0:
2234
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
2235
  parent_bdev.AddChildren(new_bdevs)
2236

    
2237

    
2238
def BlockdevRemovechildren(parent_cdev, new_cdevs):
2239
  """Shrink a mirrored block device.
2240

2241
  @type parent_cdev: L{objects.Disk}
2242
  @param parent_cdev: the disk from which we should remove children
2243
  @type new_cdevs: list of L{objects.Disk}
2244
  @param new_cdevs: the list of children which we should remove
2245
  @rtype: None
2246

2247
  """
2248
  parent_bdev = _RecursiveFindBD(parent_cdev)
2249
  if parent_bdev is None:
2250
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
2251
  devs = []
2252
  for disk in new_cdevs:
2253
    rpath = disk.StaticDevPath()
2254
    if rpath is None:
2255
      bd = _RecursiveFindBD(disk)
2256
      if bd is None:
2257
        _Fail("Can't find device %s while removing children", disk)
2258
      else:
2259
        devs.append(bd.dev_path)
2260
    else:
2261
      if not utils.IsNormAbsPath(rpath):
2262
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
2263
      devs.append(rpath)
2264
  parent_bdev.RemoveChildren(devs)
2265

    
2266

    
2267
def BlockdevGetmirrorstatus(disks):
2268
  """Get the mirroring status of a list of devices.
2269

2270
  @type disks: list of L{objects.Disk}
2271
  @param disks: the list of disks which we should query
2272
  @rtype: disk
2273
  @return: List of L{objects.BlockDevStatus}, one for each disk
2274
  @raise errors.BlockDeviceError: if any of the disks cannot be
2275
      found
2276

2277
  """
2278
  stats = []
2279
  for dsk in disks:
2280
    rbd = _RecursiveFindBD(dsk)
2281
    if rbd is None:
2282
      _Fail("Can't find device %s", dsk)
2283

    
2284
    stats.append(rbd.CombinedSyncStatus())
2285

    
2286
  return stats
2287

    
2288

    
2289
def BlockdevGetmirrorstatusMulti(disks):
2290
  """Get the mirroring status of a list of devices.
2291

2292
  @type disks: list of L{objects.Disk}
2293
  @param disks: the list of disks which we should query
2294
  @rtype: disk
2295
  @return: List of tuples, (bool, status), one for each disk; bool denotes
2296
    success/failure, status is L{objects.BlockDevStatus} on success, string
2297
    otherwise
2298

2299
  """
2300
  result = []
2301
  for disk in disks:
2302
    try:
2303
      rbd = _RecursiveFindBD(disk)
2304
      if rbd is None:
2305
        result.append((False, "Can't find device %s" % disk))
2306
        continue
2307

    
2308
      status = rbd.CombinedSyncStatus()
2309
    except errors.BlockDeviceError, err:
2310
      logging.exception("Error while getting disk status")
2311
      result.append((False, str(err)))
2312
    else:
2313
      result.append((True, status))
2314

    
2315
  assert len(disks) == len(result)
2316

    
2317
  return result
2318

    
2319

    
2320
def _RecursiveFindBD(disk):
2321
  """Check if a device is activated.
2322

2323
  If so, return information about the real device.
2324

2325
  @type disk: L{objects.Disk}
2326
  @param disk: the disk object we need to find
2327

2328
  @return: None if the device can't be found,
2329
      otherwise the device instance
2330

2331
  """
2332
  children = []
2333
  if disk.children:
2334
    for chdisk in disk.children:
2335
      children.append(_RecursiveFindBD(chdisk))
2336

    
2337
  return bdev.FindDevice(disk, children)
2338

    
2339

    
2340
def _OpenRealBD(disk):
2341
  """Opens the underlying block device of a disk.
2342

2343
  @type disk: L{objects.Disk}
2344
  @param disk: the disk object we want to open
2345

2346
  """
2347
  real_disk = _RecursiveFindBD(disk)
2348
  if real_disk is None:
2349
    _Fail("Block device '%s' is not set up", disk)
2350

    
2351
  real_disk.Open()
2352

    
2353
  return real_disk
2354

    
2355

    
2356
def BlockdevFind(disk):
2357
  """Check if a device is activated.
2358

2359
  If it is, return information about the real device.
2360

2361
  @type disk: L{objects.Disk}
2362
  @param disk: the disk to find
2363
  @rtype: None or objects.BlockDevStatus
2364
  @return: None if the disk cannot be found, otherwise a the current
2365
           information
2366

2367
  """
2368
  try:
2369
    rbd = _RecursiveFindBD(disk)
2370
  except errors.BlockDeviceError, err:
2371
    _Fail("Failed to find device: %s", err, exc=True)
2372

    
2373
  if rbd is None:
2374
    return None
2375

    
2376
  return rbd.GetSyncStatus()
2377

    
2378

    
2379
def BlockdevGetdimensions(disks):
2380
  """Computes the size of the given disks.
2381

2382
  If a disk is not found, returns None instead.
2383

2384
  @type disks: list of L{objects.Disk}
2385
  @param disks: the list of disk to compute the size for
2386
  @rtype: list
2387
  @return: list with elements None if the disk cannot be found,
2388
      otherwise the pair (size, spindles), where spindles is None if the
2389
      device doesn't support that
2390

2391
  """
2392
  result = []
2393
  for cf in disks:
2394
    try:
2395
      rbd = _RecursiveFindBD(cf)
2396
    except errors.BlockDeviceError:
2397
      result.append(None)
2398
      continue
2399
    if rbd is None:
2400
      result.append(None)
2401
    else:
2402
      result.append(rbd.GetActualDimensions())
2403
  return result
2404

    
2405

    
2406
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2407
  """Export a block device to a remote node.
2408

2409
  @type disk: L{objects.Disk}
2410
  @param disk: the description of the disk to export
2411
  @type dest_node: str
2412
  @param dest_node: the destination node to export to
2413
  @type dest_path: str
2414
  @param dest_path: the destination path on the target node
2415
  @type cluster_name: str
2416
  @param cluster_name: the cluster name, needed for SSH hostalias
2417
  @rtype: None
2418

2419
  """
2420
  real_disk = _OpenRealBD(disk)
2421

    
2422
  # the block size on the read dd is 1MiB to match our units
2423
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2424
                               "dd if=%s bs=1048576 count=%s",
2425
                               real_disk.dev_path, str(disk.size))
2426

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

    
2436
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2437
                                                   constants.SSH_LOGIN_USER,
2438
                                                   destcmd)
2439

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

    
2443
  result = utils.RunCmd(["bash", "-c", command])
2444

    
2445
  if result.failed:
2446
    _Fail("Disk copy command '%s' returned error: %s"
2447
          " output: %s", command, result.fail_reason, result.output)
2448

    
2449

    
2450
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2451
  """Write a file to the filesystem.
2452

2453
  This allows the master to overwrite(!) a file. It will only perform
2454
  the operation if the file belongs to a list of configuration files.
2455

2456
  @type file_name: str
2457
  @param file_name: the target file name
2458
  @type data: str
2459
  @param data: the new contents of the file
2460
  @type mode: int
2461
  @param mode: the mode to give the file (can be None)
2462
  @type uid: string
2463
  @param uid: the owner of the file
2464
  @type gid: string
2465
  @param gid: the group of the file
2466
  @type atime: float
2467
  @param atime: the atime to set on the file (can be None)
2468
  @type mtime: float
2469
  @param mtime: the mtime to set on the file (can be None)
2470
  @rtype: None
2471

2472
  """
2473
  file_name = vcluster.LocalizeVirtualPath(file_name)
2474

    
2475
  if not os.path.isabs(file_name):
2476
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2477

    
2478
  if file_name not in _ALLOWED_UPLOAD_FILES:
2479
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2480
          file_name)
2481

    
2482
  raw_data = _Decompress(data)
2483

    
2484
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2485
    _Fail("Invalid username/groupname type")
2486

    
2487
  getents = runtime.GetEnts()
2488
  uid = getents.LookupUser(uid)
2489
  gid = getents.LookupGroup(gid)
2490

    
2491
  utils.SafeWriteFile(file_name, None,
2492
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2493
                      atime=atime, mtime=mtime)
2494

    
2495

    
2496
def RunOob(oob_program, command, node, timeout):
2497
  """Executes oob_program with given command on given node.
2498

2499
  @param oob_program: The path to the executable oob_program
2500
  @param command: The command to invoke on oob_program
2501
  @param node: The node given as an argument to the program
2502
  @param timeout: Timeout after which we kill the oob program
2503

2504
  @return: stdout
2505
  @raise RPCFail: If execution fails for some reason
2506

2507
  """
2508
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2509

    
2510
  if result.failed:
2511
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2512
          result.fail_reason, result.output)
2513

    
2514
  return result.stdout
2515

    
2516

    
2517
def _OSOndiskAPIVersion(os_dir):
2518
  """Compute and return the API version of a given OS.
2519

2520
  This function will try to read the API version of the OS residing in
2521
  the 'os_dir' directory.
2522

2523
  @type os_dir: str
2524
  @param os_dir: the directory in which we should look for the OS
2525
  @rtype: tuple
2526
  @return: tuple (status, data) with status denoting the validity and
2527
      data holding either the vaid versions or an error message
2528

2529
  """
2530
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2531

    
2532
  try:
2533
    st = os.stat(api_file)
2534
  except EnvironmentError, err:
2535
    return False, ("Required file '%s' not found under path %s: %s" %
2536
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2537

    
2538
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2539
    return False, ("File '%s' in %s is not a regular file" %
2540
                   (constants.OS_API_FILE, os_dir))
2541

    
2542
  try:
2543
    api_versions = utils.ReadFile(api_file).splitlines()
2544
  except EnvironmentError, err:
2545
    return False, ("Error while reading the API version file at %s: %s" %
2546
                   (api_file, utils.ErrnoOrStr(err)))
2547

    
2548
  try:
2549
    api_versions = [int(version.strip()) for version in api_versions]
2550
  except (TypeError, ValueError), err:
2551
    return False, ("API version(s) can't be converted to integer: %s" %
2552
                   str(err))
2553

    
2554
  return True, api_versions
2555

    
2556

    
2557
def DiagnoseOS(top_dirs=None):
2558
  """Compute the validity for all OSes.
2559

2560
  @type top_dirs: list
2561
  @param top_dirs: the list of directories in which to
2562
      search (if not given defaults to
2563
      L{pathutils.OS_SEARCH_PATH})
2564
  @rtype: list of L{objects.OS}
2565
  @return: a list of tuples (name, path, status, diagnose, variants,
2566
      parameters, api_version) for all (potential) OSes under all
2567
      search paths, where:
2568
          - name is the (potential) OS name
2569
          - path is the full path to the OS
2570
          - status True/False is the validity of the OS
2571
          - diagnose is the error message for an invalid OS, otherwise empty
2572
          - variants is a list of supported OS variants, if any
2573
          - parameters is a list of (name, help) parameters, if any
2574
          - api_version is a list of support OS API versions
2575

2576
  """
2577
  if top_dirs is None:
2578
    top_dirs = pathutils.OS_SEARCH_PATH
2579

    
2580
  result = []
2581
  for dir_name in top_dirs:
2582
    if os.path.isdir(dir_name):
2583
      try:
2584
        f_names = utils.ListVisibleFiles(dir_name)
2585
      except EnvironmentError, err:
2586
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2587
        break
2588
      for name in f_names:
2589
        os_path = utils.PathJoin(dir_name, name)
2590
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2591
        if status:
2592
          diagnose = ""
2593
          variants = os_inst.supported_variants
2594
          parameters = os_inst.supported_parameters
2595
          api_versions = os_inst.api_versions
2596
        else:
2597
          diagnose = os_inst
2598
          variants = parameters = api_versions = []
2599
        result.append((name, os_path, status, diagnose, variants,
2600
                       parameters, api_versions))
2601

    
2602
  return result
2603

    
2604

    
2605
def _TryOSFromDisk(name, base_dir=None):
2606
  """Create an OS instance from disk.
2607

2608
  This function will return an OS instance if the given name is a
2609
  valid OS name.
2610

2611
  @type base_dir: string
2612
  @keyword base_dir: Base directory containing OS installations.
2613
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2614
  @rtype: tuple
2615
  @return: success and either the OS instance if we find a valid one,
2616
      or error message
2617

2618
  """
2619
  if base_dir is None:
2620
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2621
  else:
2622
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2623

    
2624
  if os_dir is None:
2625
    return False, "Directory for OS %s not found in search path" % name
2626

    
2627
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2628
  if not status:
2629
    # push the error up
2630
    return status, api_versions
2631

    
2632
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2633
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2634
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2635

    
2636
  # OS Files dictionary, we will populate it with the absolute path
2637
  # names; if the value is True, then it is a required file, otherwise
2638
  # an optional one
2639
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2640

    
2641
  if max(api_versions) >= constants.OS_API_V15:
2642
    os_files[constants.OS_VARIANTS_FILE] = False
2643

    
2644
  if max(api_versions) >= constants.OS_API_V20:
2645
    os_files[constants.OS_PARAMETERS_FILE] = True
2646
  else:
2647
    del os_files[constants.OS_SCRIPT_VERIFY]
2648

    
2649
  for (filename, required) in os_files.items():
2650
    os_files[filename] = utils.PathJoin(os_dir, filename)
2651

    
2652
    try:
2653
      st = os.stat(os_files[filename])
2654
    except EnvironmentError, err:
2655
      if err.errno == errno.ENOENT and not required:
2656
        del os_files[filename]
2657
        continue
2658
      return False, ("File '%s' under path '%s' is missing (%s)" %
2659
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2660

    
2661
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2662
      return False, ("File '%s' under path '%s' is not a regular file" %
2663
                     (filename, os_dir))
2664

    
2665
    if filename in constants.OS_SCRIPTS:
2666
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2667
        return False, ("File '%s' under path '%s' is not executable" %
2668
                       (filename, os_dir))
2669

    
2670
  variants = []
2671
  if constants.OS_VARIANTS_FILE in os_files:
2672
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2673
    try:
2674
      variants = \
2675
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2676
    except EnvironmentError, err:
2677
      # we accept missing files, but not other errors
2678
      if err.errno != errno.ENOENT:
2679
        return False, ("Error while reading the OS variants file at %s: %s" %
2680
                       (variants_file, utils.ErrnoOrStr(err)))
2681

    
2682
  parameters = []
2683
  if constants.OS_PARAMETERS_FILE in os_files:
2684
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2685
    try:
2686
      parameters = utils.ReadFile(parameters_file).splitlines()
2687
    except EnvironmentError, err:
2688
      return False, ("Error while reading the OS parameters file at %s: %s" %
2689
                     (parameters_file, utils.ErrnoOrStr(err)))
2690
    parameters = [v.split(None, 1) for v in parameters]
2691

    
2692
  os_obj = objects.OS(name=name, path=os_dir,
2693
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2694
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2695
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2696
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2697
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2698
                                                 None),
2699
                      supported_variants=variants,
2700
                      supported_parameters=parameters,
2701
                      api_versions=api_versions)
2702
  return True, os_obj
2703

    
2704

    
2705
def OSFromDisk(name, base_dir=None):
2706
  """Create an OS instance from disk.
2707

2708
  This function will return an OS instance if the given name is a
2709
  valid OS name. Otherwise, it will raise an appropriate
2710
  L{RPCFail} exception, detailing why this is not a valid OS.
2711

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

2715
  @type base_dir: string
2716
  @keyword base_dir: Base directory containing OS installations.
2717
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2718
  @rtype: L{objects.OS}
2719
  @return: the OS instance if we find a valid one
2720
  @raise RPCFail: if we don't find a valid OS
2721

2722
  """
2723
  name_only = objects.OS.GetName(name)
2724
  status, payload = _TryOSFromDisk(name_only, base_dir)
2725

    
2726
  if not status:
2727
    _Fail(payload)
2728

    
2729
  return payload
2730

    
2731

    
2732
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2733
  """Calculate the basic environment for an os script.
2734

2735
  @type os_name: str
2736
  @param os_name: full operating system name (including variant)
2737
  @type inst_os: L{objects.OS}
2738
  @param inst_os: operating system for which the environment is being built
2739
  @type os_params: dict
2740
  @param os_params: the OS parameters
2741
  @type debug: integer
2742
  @param debug: debug level (0 or 1, for OS Api 10)
2743
  @rtype: dict
2744
  @return: dict of environment variables
2745
  @raise errors.BlockDeviceError: if the block device
2746
      cannot be found
2747

2748
  """
2749
  result = {}
2750
  api_version = \
2751
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2752
  result["OS_API_VERSION"] = "%d" % api_version
2753
  result["OS_NAME"] = inst_os.name
2754
  result["DEBUG_LEVEL"] = "%d" % debug
2755

    
2756
  # OS variants
2757
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2758
    variant = objects.OS.GetVariant(os_name)
2759
    if not variant:
2760
      variant = inst_os.supported_variants[0]
2761
  else:
2762
    variant = ""
2763
  result["OS_VARIANT"] = variant
2764

    
2765
  # OS params
2766
  for pname, pvalue in os_params.items():
2767
    result["OSP_%s" % pname.upper()] = pvalue
2768

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

    
2774
  return result
2775

    
2776

    
2777
def OSEnvironment(instance, inst_os, debug=0):
2778
  """Calculate the environment for an os script.
2779

2780
  @type instance: L{objects.Instance}
2781
  @param instance: target instance for the os script run
2782
  @type inst_os: L{objects.OS}
2783
  @param inst_os: operating system for which the environment is being built
2784
  @type debug: integer
2785
  @param debug: debug level (0 or 1, for OS Api 10)
2786
  @rtype: dict
2787
  @return: dict of environment variables
2788
  @raise errors.BlockDeviceError: if the block device
2789
      cannot be found
2790

2791
  """
2792
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2793

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

    
2797
  result["HYPERVISOR"] = instance.hypervisor
2798
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2799
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2800
  result["INSTANCE_SECONDARY_NODES"] = \
2801
      ("%s" % " ".join(instance.secondary_nodes))
2802

    
2803
  # Disks
2804
  for idx, disk in enumerate(instance.disks):
2805
    real_disk = _OpenRealBD(disk)
2806
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2807
    result["DISK_%d_ACCESS" % idx] = disk.mode
2808
    result["DISK_%d_UUID" % idx] = disk.uuid
2809
    if disk.name:
2810
      result["DISK_%d_NAME" % idx] = disk.name
2811
    if constants.HV_DISK_TYPE in instance.hvparams:
2812
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2813
        instance.hvparams[constants.HV_DISK_TYPE]
2814
    if disk.dev_type in constants.LDS_BLOCK:
2815
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2816
    elif disk.dev_type == constants.LD_FILE:
2817
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2818
        "file:%s" % disk.physical_id[0]
2819

    
2820
  # NICs
2821
  for idx, nic in enumerate(instance.nics):
2822
    result["NIC_%d_MAC" % idx] = nic.mac
2823
    result["NIC_%d_UUID" % idx] = nic.uuid
2824
    if nic.name:
2825
      result["NIC_%d_NAME" % idx] = nic.name
2826
    if nic.ip:
2827
      result["NIC_%d_IP" % idx] = nic.ip
2828
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2829
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2830
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2831
    if nic.nicparams[constants.NIC_LINK]:
2832
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2833
    if nic.netinfo:
2834
      nobj = objects.Network.FromDict(nic.netinfo)
2835
      result.update(nobj.HooksDict("NIC_%d_" % idx))
2836
    if constants.HV_NIC_TYPE in instance.hvparams:
2837
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2838
        instance.hvparams[constants.HV_NIC_TYPE]
2839

    
2840
  # HV/BE params
2841
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2842
    for key, value in source.items():
2843
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2844

    
2845
  return result
2846

    
2847

    
2848
def DiagnoseExtStorage(top_dirs=None):
2849
  """Compute the validity for all ExtStorage Providers.
2850

2851
  @type top_dirs: list
2852
  @param top_dirs: the list of directories in which to
2853
      search (if not given defaults to
2854
      L{pathutils.ES_SEARCH_PATH})
2855
  @rtype: list of L{objects.ExtStorage}
2856
  @return: a list of tuples (name, path, status, diagnose, parameters)
2857
      for all (potential) ExtStorage Providers under all
2858
      search paths, where:
2859
          - name is the (potential) ExtStorage Provider
2860
          - path is the full path to the ExtStorage Provider
2861
          - status True/False is the validity of the ExtStorage Provider
2862
          - diagnose is the error message for an invalid ExtStorage Provider,
2863
            otherwise empty
2864
          - parameters is a list of (name, help) parameters, if any
2865

2866
  """
2867
  if top_dirs is None:
2868
    top_dirs = pathutils.ES_SEARCH_PATH
2869

    
2870
  result = []
2871
  for dir_name in top_dirs:
2872
    if os.path.isdir(dir_name):
2873
      try:
2874
        f_names = utils.ListVisibleFiles(dir_name)
2875
      except EnvironmentError, err:
2876
        logging.exception("Can't list the ExtStorage directory %s: %s",
2877
                          dir_name, err)
2878
        break
2879
      for name in f_names:
2880
        es_path = utils.PathJoin(dir_name, name)
2881
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2882
        if status:
2883
          diagnose = ""
2884
          parameters = es_inst.supported_parameters
2885
        else:
2886
          diagnose = es_inst
2887
          parameters = []
2888
        result.append((name, es_path, status, diagnose, parameters))
2889

    
2890
  return result
2891

    
2892

    
2893
def BlockdevGrow(disk, amount, dryrun, backingstore, excl_stor):
2894
  """Grow a stack of block devices.
2895

2896
  This function is called recursively, with the childrens being the
2897
  first ones to resize.
2898

2899
  @type disk: L{objects.Disk}
2900
  @param disk: the disk to be grown
2901
  @type amount: integer
2902
  @param amount: the amount (in mebibytes) to grow with
2903
  @type dryrun: boolean
2904
  @param dryrun: whether to execute the operation in simulation mode
2905
      only, without actually increasing the size
2906
  @param backingstore: whether to execute the operation on backing storage
2907
      only, or on "logical" storage only; e.g. DRBD is logical storage,
2908
      whereas LVM, file, RBD are backing storage
2909
  @rtype: (status, result)
2910
  @type excl_stor: boolean
2911
  @param excl_stor: Whether exclusive_storage is active
2912
  @return: a tuple with the status of the operation (True/False), and
2913
      the errors message if status is False
2914

2915
  """
2916
  r_dev = _RecursiveFindBD(disk)
2917
  if r_dev is None:
2918
    _Fail("Cannot find block device %s", disk)
2919

    
2920
  try:
2921
    r_dev.Grow(amount, dryrun, backingstore, excl_stor)
2922
  except errors.BlockDeviceError, err:
2923
    _Fail("Failed to grow block device: %s", err, exc=True)
2924

    
2925

    
2926
def BlockdevSnapshot(disk):
2927
  """Create a snapshot copy of a block device.
2928

2929
  This function is called recursively, and the snapshot is actually created
2930
  just for the leaf lvm backend device.
2931

2932
  @type disk: L{objects.Disk}
2933
  @param disk: the disk to be snapshotted
2934
  @rtype: string
2935
  @return: snapshot disk ID as (vg, lv)
2936

2937
  """
2938
  if disk.dev_type == constants.LD_DRBD8:
2939
    if not disk.children:
2940
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2941
            disk.unique_id)
2942
    return BlockdevSnapshot(disk.children[0])
2943
  elif disk.dev_type == constants.LD_LV:
2944
    r_dev = _RecursiveFindBD(disk)
2945
    if r_dev is not None:
2946
      # FIXME: choose a saner value for the snapshot size
2947
      # let's stay on the safe side and ask for the full size, for now
2948
      return r_dev.Snapshot(disk.size)
2949
    else:
2950
      _Fail("Cannot find block device %s", disk)
2951
  else:
2952
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2953
          disk.unique_id, disk.dev_type)
2954

    
2955

    
2956
def BlockdevSetInfo(disk, info):
2957
  """Sets 'metadata' information on block devices.
2958

2959
  This function sets 'info' metadata on block devices. Initial
2960
  information is set at device creation; this function should be used
2961
  for example after renames.
2962

2963
  @type disk: L{objects.Disk}
2964
  @param disk: the disk to be grown
2965
  @type info: string
2966
  @param info: new 'info' metadata
2967
  @rtype: (status, result)
2968
  @return: a tuple with the status of the operation (True/False), and
2969
      the errors message if status is False
2970

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

    
2976
  try:
2977
    r_dev.SetInfo(info)
2978
  except errors.BlockDeviceError, err:
2979
    _Fail("Failed to set information on block device: %s", err, exc=True)
2980

    
2981

    
2982
def FinalizeExport(instance, snap_disks):
2983
  """Write out the export configuration information.
2984

2985
  @type instance: L{objects.Instance}
2986
  @param instance: the instance which we export, used for
2987
      saving configuration
2988
  @type snap_disks: list of L{objects.Disk}
2989
  @param snap_disks: list of snapshot block devices, which
2990
      will be used to get the actual name of the dump file
2991

2992
  @rtype: None
2993

2994
  """
2995
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
2996
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
2997

    
2998
  config = objects.SerializableConfigParser()
2999

    
3000
  config.add_section(constants.INISECT_EXP)
3001
  config.set(constants.INISECT_EXP, "version", "0")
3002
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
3003
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
3004
  config.set(constants.INISECT_EXP, "os", instance.os)
3005
  config.set(constants.INISECT_EXP, "compression", "none")
3006

    
3007
  config.add_section(constants.INISECT_INS)
3008
  config.set(constants.INISECT_INS, "name", instance.name)
3009
  config.set(constants.INISECT_INS, "maxmem", "%d" %
3010
             instance.beparams[constants.BE_MAXMEM])
3011
  config.set(constants.INISECT_INS, "minmem", "%d" %
3012
             instance.beparams[constants.BE_MINMEM])
3013
  # "memory" is deprecated, but useful for exporting to old ganeti versions
3014
  config.set(constants.INISECT_INS, "memory", "%d" %
3015
             instance.beparams[constants.BE_MAXMEM])
3016
  config.set(constants.INISECT_INS, "vcpus", "%d" %
3017
             instance.beparams[constants.BE_VCPUS])
3018
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
3019
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
3020
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
3021

    
3022
  nic_total = 0
3023
  for nic_count, nic in enumerate(instance.nics):
3024
    nic_total += 1
3025
    config.set(constants.INISECT_INS, "nic%d_mac" %
3026
               nic_count, "%s" % nic.mac)
3027
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
3028
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
3029
               "%s" % nic.network)
3030
    for param in constants.NICS_PARAMETER_TYPES:
3031
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
3032
                 "%s" % nic.nicparams.get(param, None))
3033
  # TODO: redundant: on load can read nics until it doesn't exist
3034
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
3035

    
3036
  disk_total = 0
3037
  for disk_count, disk in enumerate(snap_disks):
3038
    if disk:
3039
      disk_total += 1
3040
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
3041
                 ("%s" % disk.iv_name))
3042
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
3043
                 ("%s" % disk.physical_id[1]))
3044
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
3045
                 ("%d" % disk.size))
3046

    
3047
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
3048

    
3049
  # New-style hypervisor/backend parameters
3050

    
3051
  config.add_section(constants.INISECT_HYP)
3052
  for name, value in instance.hvparams.items():
3053
    if name not in constants.HVC_GLOBALS:
3054
      config.set(constants.INISECT_HYP, name, str(value))
3055

    
3056
  config.add_section(constants.INISECT_BEP)
3057
  for name, value in instance.beparams.items():
3058
    config.set(constants.INISECT_BEP, name, str(value))
3059

    
3060
  config.add_section(constants.INISECT_OSP)
3061
  for name, value in instance.osparams.items():
3062
    config.set(constants.INISECT_OSP, name, str(value))
3063

    
3064
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
3065
                  data=config.Dumps())
3066
  shutil.rmtree(finaldestdir, ignore_errors=True)
3067
  shutil.move(destdir, finaldestdir)
3068

    
3069

    
3070
def ExportInfo(dest):
3071
  """Get export configuration information.
3072

3073
  @type dest: str
3074
  @param dest: directory containing the export
3075

3076
  @rtype: L{objects.SerializableConfigParser}
3077
  @return: a serializable config file containing the
3078
      export info
3079

3080
  """
3081
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
3082

    
3083
  config = objects.SerializableConfigParser()
3084
  config.read(cff)
3085

    
3086
  if (not config.has_section(constants.INISECT_EXP) or
3087
      not config.has_section(constants.INISECT_INS)):
3088
    _Fail("Export info file doesn't have the required fields")
3089

    
3090
  return config.Dumps()
3091

    
3092

    
3093
def ListExports():
3094
  """Return a list of exports currently available on this machine.
3095

3096
  @rtype: list
3097
  @return: list of the exports
3098

3099
  """
3100
  if os.path.isdir(pathutils.EXPORT_DIR):
3101
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
3102
  else:
3103
    _Fail("No exports directory")
3104

    
3105

    
3106
def RemoveExport(export):
3107
  """Remove an existing export from the node.
3108

3109
  @type export: str
3110
  @param export: the name of the export to remove
3111
  @rtype: None
3112

3113
  """
3114
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
3115

    
3116
  try:
3117
    shutil.rmtree(target)
3118
  except EnvironmentError, err:
3119
    _Fail("Error while removing the export: %s", err, exc=True)
3120

    
3121

    
3122
def BlockdevRename(devlist):
3123
  """Rename a list of block devices.
3124

3125
  @type devlist: list of tuples
3126
  @param devlist: list of tuples of the form  (disk,
3127
      new_logical_id, new_physical_id); disk is an
3128
      L{objects.Disk} object describing the current disk,
3129
      and new logical_id/physical_id is the name we
3130
      rename it to
3131
  @rtype: boolean
3132
  @return: True if all renames succeeded, False otherwise
3133

3134
  """
3135
  msgs = []
3136
  result = True
3137
  for disk, unique_id in devlist:
3138
    dev = _RecursiveFindBD(disk)
3139
    if dev is None:
3140
      msgs.append("Can't find device %s in rename" % str(disk))
3141
      result = False
3142
      continue
3143
    try:
3144
      old_rpath = dev.dev_path
3145
      dev.Rename(unique_id)
3146
      new_rpath = dev.dev_path
3147
      if old_rpath != new_rpath:
3148
        DevCacheManager.RemoveCache(old_rpath)
3149
        # FIXME: we should add the new cache information here, like:
3150
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
3151
        # but we don't have the owner here - maybe parse from existing
3152
        # cache? for now, we only lose lvm data when we rename, which
3153
        # is less critical than DRBD or MD
3154
    except errors.BlockDeviceError, err:
3155
      msgs.append("Can't rename device '%s' to '%s': %s" %
3156
                  (dev, unique_id, err))
3157
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
3158
      result = False
3159
  if not result:
3160
    _Fail("; ".join(msgs))
3161

    
3162

    
3163
def _TransformFileStorageDir(fs_dir):
3164
  """Checks whether given file_storage_dir is valid.
3165

3166
  Checks wheter the given fs_dir is within the cluster-wide default
3167
  file_storage_dir or the shared_file_storage_dir, which are stored in
3168
  SimpleStore. Only paths under those directories are allowed.
3169

3170
  @type fs_dir: str
3171
  @param fs_dir: the path to check
3172

3173
  @return: the normalized path if valid, None otherwise
3174

3175
  """
3176
  if not (constants.ENABLE_FILE_STORAGE or
3177
          constants.ENABLE_SHARED_FILE_STORAGE):
3178
    _Fail("File storage disabled at configure time")
3179

    
3180
  bdev.CheckFileStoragePath(fs_dir)
3181

    
3182
  return os.path.normpath(fs_dir)
3183

    
3184

    
3185
def CreateFileStorageDir(file_storage_dir):
3186
  """Create file storage directory.
3187

3188
  @type file_storage_dir: str
3189
  @param file_storage_dir: directory to create
3190

3191
  @rtype: tuple
3192
  @return: tuple with first element a boolean indicating wheter dir
3193
      creation was successful or not
3194

3195
  """
3196
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3197
  if os.path.exists(file_storage_dir):
3198
    if not os.path.isdir(file_storage_dir):
3199
      _Fail("Specified storage dir '%s' is not a directory",
3200
            file_storage_dir)
3201
  else:
3202
    try:
3203
      os.makedirs(file_storage_dir, 0750)
3204
    except OSError, err:
3205
      _Fail("Cannot create file storage directory '%s': %s",
3206
            file_storage_dir, err, exc=True)
3207

    
3208

    
3209
def RemoveFileStorageDir(file_storage_dir):
3210
  """Remove file storage directory.
3211

3212
  Remove it only if it's empty. If not log an error and return.
3213

3214
  @type file_storage_dir: str
3215
  @param file_storage_dir: the directory we should cleanup
3216
  @rtype: tuple (success,)
3217
  @return: tuple of one element, C{success}, denoting
3218
      whether the operation was successful
3219

3220
  """
3221
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3222
  if os.path.exists(file_storage_dir):
3223
    if not os.path.isdir(file_storage_dir):
3224
      _Fail("Specified Storage directory '%s' is not a directory",
3225
            file_storage_dir)
3226
    # deletes dir only if empty, otherwise we want to fail the rpc call
3227
    try:
3228
      os.rmdir(file_storage_dir)
3229
    except OSError, err:
3230
      _Fail("Cannot remove file storage directory '%s': %s",
3231
            file_storage_dir, err)
3232

    
3233

    
3234
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
3235
  """Rename the file storage directory.
3236

3237
  @type old_file_storage_dir: str
3238
  @param old_file_storage_dir: the current path
3239
  @type new_file_storage_dir: str
3240
  @param new_file_storage_dir: the name we should rename to
3241
  @rtype: tuple (success,)
3242
  @return: tuple of one element, C{success}, denoting
3243
      whether the operation was successful
3244

3245
  """
3246
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
3247
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
3248
  if not os.path.exists(new_file_storage_dir):
3249
    if os.path.isdir(old_file_storage_dir):
3250
      try:
3251
        os.rename(old_file_storage_dir, new_file_storage_dir)
3252
      except OSError, err:
3253
        _Fail("Cannot rename '%s' to '%s': %s",
3254
              old_file_storage_dir, new_file_storage_dir, err)
3255
    else:
3256
      _Fail("Specified storage dir '%s' is not a directory",
3257
            old_file_storage_dir)
3258
  else:
3259
    if os.path.exists(old_file_storage_dir):
3260
      _Fail("Cannot rename '%s' to '%s': both locations exist",
3261
            old_file_storage_dir, new_file_storage_dir)
3262

    
3263

    
3264
def _EnsureJobQueueFile(file_name):
3265
  """Checks whether the given filename is in the queue directory.
3266

3267
  @type file_name: str
3268
  @param file_name: the file name we should check
3269
  @rtype: None
3270
  @raises RPCFail: if the file is not valid
3271

3272
  """
3273
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
3274
    _Fail("Passed job queue file '%s' does not belong to"
3275
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
3276

    
3277

    
3278
def JobQueueUpdate(file_name, content):
3279
  """Updates a file in the queue directory.
3280

3281
  This is just a wrapper over L{utils.io.WriteFile}, with proper
3282
  checking.
3283

3284
  @type file_name: str
3285
  @param file_name: the job file name
3286
  @type content: str
3287
  @param content: the new job contents
3288
  @rtype: boolean
3289
  @return: the success of the operation
3290

3291
  """
3292
  file_name = vcluster.LocalizeVirtualPath(file_name)
3293

    
3294
  _EnsureJobQueueFile(file_name)
3295
  getents = runtime.GetEnts()
3296

    
3297
  # Write and replace the file atomically
3298
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3299
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3300

    
3301

    
3302
def JobQueueRename(old, new):
3303
  """Renames a job queue file.
3304

3305
  This is just a wrapper over os.rename with proper checking.
3306

3307
  @type old: str
3308
  @param old: the old (actual) file name
3309
  @type new: str
3310
  @param new: the desired file name
3311
  @rtype: tuple
3312
  @return: the success of the operation and payload
3313

3314
  """
3315
  old = vcluster.LocalizeVirtualPath(old)
3316
  new = vcluster.LocalizeVirtualPath(new)
3317

    
3318
  _EnsureJobQueueFile(old)
3319
  _EnsureJobQueueFile(new)
3320

    
3321
  getents = runtime.GetEnts()
3322

    
3323
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3324
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3325

    
3326

    
3327
def BlockdevClose(instance_name, disks):
3328
  """Closes the given block devices.
3329

3330
  This means they will be switched to secondary mode (in case of
3331
  DRBD).
3332

3333
  @param instance_name: if the argument is not empty, the symlinks
3334
      of this instance will be removed
3335
  @type disks: list of L{objects.Disk}
3336
  @param disks: the list of disks to be closed
3337
  @rtype: tuple (success, message)
3338
  @return: a tuple of success and message, where success
3339
      indicates the succes of the operation, and message
3340
      which will contain the error details in case we
3341
      failed
3342

3343
  """
3344
  bdevs = []
3345
  for cf in disks:
3346
    rd = _RecursiveFindBD(cf)
3347
    if rd is None:
3348
      _Fail("Can't find device %s", cf)
3349
    bdevs.append(rd)
3350

    
3351
  msg = []
3352
  for rd in bdevs:
3353
    try:
3354
      rd.Close()
3355
    except errors.BlockDeviceError, err:
3356
      msg.append(str(err))
3357
  if msg:
3358
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3359
  else:
3360
    if instance_name:
3361
      _RemoveBlockDevLinks(instance_name, disks)
3362

    
3363

    
3364
def ValidateHVParams(hvname, hvparams):
3365
  """Validates the given hypervisor parameters.
3366

3367
  @type hvname: string
3368
  @param hvname: the hypervisor name
3369
  @type hvparams: dict
3370
  @param hvparams: the hypervisor parameters to be validated
3371
  @rtype: None
3372

3373
  """
3374
  try:
3375
    hv_type = hypervisor.GetHypervisor(hvname)
3376
    hv_type.ValidateParameters(hvparams)
3377
  except errors.HypervisorError, err:
3378
    _Fail(str(err), log=False)
3379

    
3380

    
3381
def _CheckOSPList(os_obj, parameters):
3382
  """Check whether a list of parameters is supported by the OS.
3383

3384
  @type os_obj: L{objects.OS}
3385
  @param os_obj: OS object to check
3386
  @type parameters: list
3387
  @param parameters: the list of parameters to check
3388

3389
  """
3390
  supported = [v[0] for v in os_obj.supported_parameters]
3391
  delta = frozenset(parameters).difference(supported)
3392
  if delta:
3393
    _Fail("The following parameters are not supported"
3394
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3395

    
3396

    
3397
def ValidateOS(required, osname, checks, osparams):
3398
  """Validate the given OS' parameters.
3399

3400
  @type required: boolean
3401
  @param required: whether absence of the OS should translate into
3402
      failure or not
3403
  @type osname: string
3404
  @param osname: the OS to be validated
3405
  @type checks: list
3406
  @param checks: list of the checks to run (currently only 'parameters')
3407
  @type osparams: dict
3408
  @param osparams: dictionary with OS parameters
3409
  @rtype: boolean
3410
  @return: True if the validation passed, or False if the OS was not
3411
      found and L{required} was false
3412

3413
  """
3414
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3415
    _Fail("Unknown checks required for OS %s: %s", osname,
3416
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3417

    
3418
  name_only = objects.OS.GetName(osname)
3419
  status, tbv = _TryOSFromDisk(name_only, None)
3420

    
3421
  if not status:
3422
    if required:
3423
      _Fail(tbv)
3424
    else:
3425
      return False
3426

    
3427
  if max(tbv.api_versions) < constants.OS_API_V20:
3428
    return True
3429

    
3430
  if constants.OS_VALIDATE_PARAMETERS in checks:
3431
    _CheckOSPList(tbv, osparams.keys())
3432

    
3433
  validate_env = OSCoreEnv(osname, tbv, osparams)
3434
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3435
                        cwd=tbv.path, reset_env=True)
3436
  if result.failed:
3437
    logging.error("os validate command '%s' returned error: %s output: %s",
3438
                  result.cmd, result.fail_reason, result.output)
3439
    _Fail("OS validation script failed (%s), output: %s",
3440
          result.fail_reason, result.output, log=False)
3441

    
3442
  return True
3443

    
3444

    
3445
def DemoteFromMC():
3446
  """Demotes the current node from master candidate role.
3447

3448
  """
3449
  # try to ensure we're not the master by mistake
3450
  master, myself = ssconf.GetMasterAndMyself()
3451
  if master == myself:
3452
    _Fail("ssconf status shows I'm the master node, will not demote")
3453

    
3454
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3455
  if not result.failed:
3456
    _Fail("The master daemon is running, will not demote")
3457

    
3458
  try:
3459
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3460
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3461
  except EnvironmentError, err:
3462
    if err.errno != errno.ENOENT:
3463
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3464

    
3465
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3466

    
3467

    
3468
def _GetX509Filenames(cryptodir, name):
3469
  """Returns the full paths for the private key and certificate.
3470

3471
  """
3472
  return (utils.PathJoin(cryptodir, name),
3473
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3474
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3475

    
3476

    
3477
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3478
  """Creates a new X509 certificate for SSL/TLS.
3479

3480
  @type validity: int
3481
  @param validity: Validity in seconds
3482
  @rtype: tuple; (string, string)
3483
  @return: Certificate name and public part
3484

3485
  """
3486
  (key_pem, cert_pem) = \
3487
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3488
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3489

    
3490
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3491
                              prefix="x509-%s-" % utils.TimestampForFilename())
3492
  try:
3493
    name = os.path.basename(cert_dir)
3494
    assert len(name) > 5
3495

    
3496
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3497

    
3498
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3499
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3500

    
3501
    # Never return private key as it shouldn't leave the node
3502
    return (name, cert_pem)
3503
  except Exception:
3504
    shutil.rmtree(cert_dir, ignore_errors=True)
3505
    raise
3506

    
3507

    
3508
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3509
  """Removes a X509 certificate.
3510

3511
  @type name: string
3512
  @param name: Certificate name
3513

3514
  """
3515
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3516

    
3517
  utils.RemoveFile(key_file)
3518
  utils.RemoveFile(cert_file)
3519

    
3520
  try:
3521
    os.rmdir(cert_dir)
3522
  except EnvironmentError, err:
3523
    _Fail("Cannot remove certificate directory '%s': %s",
3524
          cert_dir, err)
3525

    
3526

    
3527
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3528
  """Returns the command for the requested input/output.
3529

3530
  @type instance: L{objects.Instance}
3531
  @param instance: The instance object
3532
  @param mode: Import/export mode
3533
  @param ieio: Input/output type
3534
  @param ieargs: Input/output arguments
3535

3536
  """
3537
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3538

    
3539
  env = None
3540
  prefix = None
3541
  suffix = None
3542
  exp_size = None
3543

    
3544
  if ieio == constants.IEIO_FILE:
3545
    (filename, ) = ieargs
3546

    
3547
    if not utils.IsNormAbsPath(filename):
3548
      _Fail("Path '%s' is not normalized or absolute", filename)
3549

    
3550
    real_filename = os.path.realpath(filename)
3551
    directory = os.path.dirname(real_filename)
3552

    
3553
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3554
      _Fail("File '%s' is not under exports directory '%s': %s",
3555
            filename, pathutils.EXPORT_DIR, real_filename)
3556

    
3557
    # Create directory
3558
    utils.Makedirs(directory, mode=0750)
3559

    
3560
    quoted_filename = utils.ShellQuote(filename)
3561

    
3562
    if mode == constants.IEM_IMPORT:
3563
      suffix = "> %s" % quoted_filename
3564
    elif mode == constants.IEM_EXPORT:
3565
      suffix = "< %s" % quoted_filename
3566

    
3567
      # Retrieve file size
3568
      try:
3569
        st = os.stat(filename)
3570
      except EnvironmentError, err:
3571
        logging.error("Can't stat(2) %s: %s", filename, err)
3572
      else:
3573
        exp_size = utils.BytesToMebibyte(st.st_size)
3574

    
3575
  elif ieio == constants.IEIO_RAW_DISK:
3576
    (disk, ) = ieargs
3577

    
3578
    real_disk = _OpenRealBD(disk)
3579

    
3580
    if mode == constants.IEM_IMPORT:
3581
      # we set here a smaller block size as, due to transport buffering, more
3582
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3583
      # is not already there or we pass a wrong path; we use notrunc to no
3584
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3585
      # much memory; this means that at best, we flush every 64k, which will
3586
      # not be very fast
3587
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3588
                                    " bs=%s oflag=dsync"),
3589
                                    real_disk.dev_path,
3590
                                    str(64 * 1024))
3591

    
3592
    elif mode == constants.IEM_EXPORT:
3593
      # the block size on the read dd is 1MiB to match our units
3594
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3595
                                   real_disk.dev_path,
3596
                                   str(1024 * 1024), # 1 MB
3597
                                   str(disk.size))
3598
      exp_size = disk.size
3599

    
3600
  elif ieio == constants.IEIO_SCRIPT:
3601
    (disk, disk_index, ) = ieargs
3602

    
3603
    assert isinstance(disk_index, (int, long))
3604

    
3605
    real_disk = _OpenRealBD(disk)
3606

    
3607
    inst_os = OSFromDisk(instance.os)
3608
    env = OSEnvironment(instance, inst_os)
3609

    
3610
    if mode == constants.IEM_IMPORT:
3611
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3612
      env["IMPORT_INDEX"] = str(disk_index)
3613
      script = inst_os.import_script
3614

    
3615
    elif mode == constants.IEM_EXPORT:
3616
      env["EXPORT_DEVICE"] = real_disk.dev_path
3617
      env["EXPORT_INDEX"] = str(disk_index)
3618
      script = inst_os.export_script
3619

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

    
3623
    if mode == constants.IEM_IMPORT:
3624
      suffix = "| %s" % script_cmd
3625

    
3626
    elif mode == constants.IEM_EXPORT:
3627
      prefix = "%s |" % script_cmd
3628

    
3629
    # Let script predict size
3630
    exp_size = constants.IE_CUSTOM_SIZE
3631

    
3632
  else:
3633
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3634

    
3635
  return (env, prefix, suffix, exp_size)
3636

    
3637

    
3638
def _CreateImportExportStatusDir(prefix):
3639
  """Creates status directory for import/export.
3640

3641
  """
3642
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3643
                          prefix=("%s-%s-" %
3644
                                  (prefix, utils.TimestampForFilename())))
3645

    
3646

    
3647
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3648
                            ieio, ieioargs):
3649
  """Starts an import or export daemon.
3650

3651
  @param mode: Import/output mode
3652
  @type opts: L{objects.ImportExportOptions}
3653
  @param opts: Daemon options
3654
  @type host: string
3655
  @param host: Remote host for export (None for import)
3656
  @type port: int
3657
  @param port: Remote port for export (None for import)
3658
  @type instance: L{objects.Instance}
3659
  @param instance: Instance object
3660
  @type component: string
3661
  @param component: which part of the instance is transferred now,
3662
      e.g. 'disk/0'
3663
  @param ieio: Input/output type
3664
  @param ieioargs: Input/output arguments
3665

3666
  """
3667
  if mode == constants.IEM_IMPORT:
3668
    prefix = "import"
3669

    
3670
    if not (host is None and port is None):
3671
      _Fail("Can not specify host or port on import")
3672

    
3673
  elif mode == constants.IEM_EXPORT:
3674
    prefix = "export"
3675

    
3676
    if host is None or port is None:
3677
      _Fail("Host and port must be specified for an export")
3678

    
3679
  else:
3680
    _Fail("Invalid mode %r", mode)
3681

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

    
3685
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3686
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3687

    
3688
  if opts.key_name is None:
3689
    # Use server.pem
3690
    key_path = pathutils.NODED_CERT_FILE
3691
    cert_path = pathutils.NODED_CERT_FILE
3692
    assert opts.ca_pem is None
3693
  else:
3694
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3695
                                                 opts.key_name)
3696
    assert opts.ca_pem is not None
3697

    
3698
  for i in [key_path, cert_path]:
3699
    if not os.path.exists(i):
3700
      _Fail("File '%s' does not exist" % i)
3701

    
3702
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3703
  try:
3704
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3705
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3706
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3707

    
3708
    if opts.ca_pem is None:
3709
      # Use server.pem
3710
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3711
    else:
3712
      ca = opts.ca_pem
3713

    
3714
    # Write CA file
3715
    utils.WriteFile(ca_file, data=ca, mode=0400)
3716

    
3717
    cmd = [
3718
      pathutils.IMPORT_EXPORT_DAEMON,
3719
      status_file, mode,
3720
      "--key=%s" % key_path,
3721
      "--cert=%s" % cert_path,
3722
      "--ca=%s" % ca_file,
3723
      ]
3724

    
3725
    if host:
3726
      cmd.append("--host=%s" % host)
3727

    
3728
    if port:
3729
      cmd.append("--port=%s" % port)
3730

    
3731
    if opts.ipv6:
3732
      cmd.append("--ipv6")
3733
    else:
3734
      cmd.append("--ipv4")
3735

    
3736
    if opts.compress:
3737
      cmd.append("--compress=%s" % opts.compress)
3738

    
3739
    if opts.magic:
3740
      cmd.append("--magic=%s" % opts.magic)
3741

    
3742
    if exp_size is not None:
3743
      cmd.append("--expected-size=%s" % exp_size)
3744

    
3745
    if cmd_prefix:
3746
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3747

    
3748
    if cmd_suffix:
3749
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3750

    
3751
    if mode == constants.IEM_EXPORT:
3752
      # Retry connection a few times when connecting to remote peer
3753
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3754
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3755
    elif opts.connect_timeout is not None:
3756
      assert mode == constants.IEM_IMPORT
3757
      # Overall timeout for establishing connection while listening
3758
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3759

    
3760
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3761

    
3762
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3763
    # support for receiving a file descriptor for output
3764
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3765
                      output=logfile)
3766

    
3767
    # The import/export name is simply the status directory name
3768
    return os.path.basename(status_dir)
3769

    
3770
  except Exception:
3771
    shutil.rmtree(status_dir, ignore_errors=True)
3772
    raise
3773

    
3774

    
3775
def GetImportExportStatus(names):
3776
  """Returns import/export daemon status.
3777

3778
  @type names: sequence
3779
  @param names: List of names
3780
  @rtype: List of dicts
3781
  @return: Returns a list of the state of each named import/export or None if a
3782
           status couldn't be read
3783

3784
  """
3785
  result = []
3786

    
3787
  for name in names:
3788
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3789
                                 _IES_STATUS_FILE)
3790

    
3791
    try:
3792
      data = utils.ReadFile(status_file)
3793
    except EnvironmentError, err:
3794
      if err.errno != errno.ENOENT:
3795
        raise
3796
      data = None
3797

    
3798
    if not data:
3799
      result.append(None)
3800
      continue
3801

    
3802
    result.append(serializer.LoadJson(data))
3803

    
3804
  return result
3805

    
3806

    
3807
def AbortImportExport(name):
3808
  """Sends SIGTERM to a running import/export daemon.
3809

3810
  """
3811
  logging.info("Abort import/export %s", name)
3812

    
3813
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3814
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3815

    
3816
  if pid:
3817
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3818
                 name, pid)
3819
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3820

    
3821

    
3822
def CleanupImportExport(name):
3823
  """Cleanup after an import or export.
3824

3825
  If the import/export daemon is still running it's killed. Afterwards the
3826
  whole status directory is removed.
3827

3828
  """
3829
  logging.info("Finalizing import/export %s", name)
3830

    
3831
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3832

    
3833
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3834

    
3835
  if pid:
3836
    logging.info("Import/export %s is still running with PID %s",
3837
                 name, pid)
3838
    utils.KillProcess(pid, waitpid=False)
3839

    
3840
  shutil.rmtree(status_dir, ignore_errors=True)
3841

    
3842

    
3843
def _SetPhysicalId(target_node_uuid, nodes_ip, disks):
3844
  """Sets the correct physical ID on all passed disks.
3845

3846
  """
3847
  for cf in disks:
3848
    cf.SetPhysicalID(target_node_uuid, nodes_ip)
3849

    
3850

    
3851
def _FindDisks(target_node_uuid, nodes_ip, disks):
3852
  """Sets the physical ID on disks and returns the block devices.
3853

3854
  """
3855
  _SetPhysicalId(target_node_uuid, nodes_ip, disks)
3856

    
3857
  bdevs = []
3858

    
3859
  for cf in disks:
3860
    rd = _RecursiveFindBD(cf)
3861
    if rd is None:
3862
      _Fail("Can't find device %s", cf)
3863
    bdevs.append(rd)
3864
  return bdevs
3865

    
3866

    
3867
def DrbdDisconnectNet(target_node_uuid, nodes_ip, disks):
3868
  """Disconnects the network on a list of drbd devices.
3869

3870
  """
3871
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3872

    
3873
  # disconnect disks
3874
  for rd in bdevs:
3875
    try:
3876
      rd.DisconnectNet()
3877
    except errors.BlockDeviceError, err:
3878
      _Fail("Can't change network configuration to standalone mode: %s",
3879
            err, exc=True)
3880

    
3881

    
3882
def DrbdAttachNet(target_node_uuid, nodes_ip, disks, instance_name,
3883
                  multimaster):
3884
  """Attaches the network on a list of drbd devices.
3885

3886
  """
3887
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3888

    
3889
  if multimaster:
3890
    for idx, rd in enumerate(bdevs):
3891
      try:
3892
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3893
      except EnvironmentError, err:
3894
        _Fail("Can't create symlink: %s", err)
3895
  # reconnect disks, switch to new master configuration and if
3896
  # needed primary mode
3897
  for rd in bdevs:
3898
    try:
3899
      rd.AttachNet(multimaster)
3900
    except errors.BlockDeviceError, err:
3901
      _Fail("Can't change network configuration: %s", err)
3902

    
3903
  # wait until the disks are connected; we need to retry the re-attach
3904
  # if the device becomes standalone, as this might happen if the one
3905
  # node disconnects and reconnects in a different mode before the
3906
  # other node reconnects; in this case, one or both of the nodes will
3907
  # decide it has wrong configuration and switch to standalone
3908

    
3909
  def _Attach():
3910
    all_connected = True
3911

    
3912
    for rd in bdevs:
3913
      stats = rd.GetProcStatus()
3914

    
3915
      all_connected = (all_connected and
3916
                       (stats.is_connected or stats.is_in_resync))
3917

    
3918
      if stats.is_standalone:
3919
        # peer had different config info and this node became
3920
        # standalone, even though this should not happen with the
3921
        # new staged way of changing disk configs
3922
        try:
3923
          rd.AttachNet(multimaster)
3924
        except errors.BlockDeviceError, err:
3925
          _Fail("Can't change network configuration: %s", err)
3926

    
3927
    if not all_connected:
3928
      raise utils.RetryAgain()
3929

    
3930
  try:
3931
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3932
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3933
  except utils.RetryTimeout:
3934
    _Fail("Timeout in disk reconnecting")
3935

    
3936
  if multimaster:
3937
    # change to primary mode
3938
    for rd in bdevs:
3939
      try:
3940
        rd.Open()
3941
      except errors.BlockDeviceError, err:
3942
        _Fail("Can't change to primary mode: %s", err)
3943

    
3944

    
3945
def DrbdWaitSync(target_node_uuid, nodes_ip, disks):
3946
  """Wait until DRBDs have synchronized.
3947

3948
  """
3949
  def _helper(rd):
3950
    stats = rd.GetProcStatus()
3951
    if not (stats.is_connected or stats.is_in_resync):
3952
      raise utils.RetryAgain()
3953
    return stats
3954

    
3955
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3956

    
3957
  min_resync = 100
3958
  alldone = True
3959
  for rd in bdevs:
3960
    try:
3961
      # poll each second for 15 seconds
3962
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3963
    except utils.RetryTimeout:
3964
      stats = rd.GetProcStatus()
3965
      # last check
3966
      if not (stats.is_connected or stats.is_in_resync):
3967
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3968
    alldone = alldone and (not stats.is_in_resync)
3969
    if stats.sync_percent is not None:
3970
      min_resync = min(min_resync, stats.sync_percent)
3971

    
3972
  return (alldone, min_resync)
3973

    
3974

    
3975
def DrbdNeedsActivation(target_node_uuid, nodes_ip, disks):
3976
  """Checks which of the passed disks needs activation and returns their UUIDs.
3977

3978
  """
3979
  _SetPhysicalId(target_node_uuid, nodes_ip, disks)
3980
  faulty_disks = []
3981

    
3982
  for disk in disks:
3983
    rd = _RecursiveFindBD(disk)
3984
    if rd is None:
3985
      faulty_disks.append(disk)
3986
      continue
3987

    
3988
    stats = rd.GetProcStatus()
3989
    if stats.is_standalone or stats.is_diskless:
3990
      faulty_disks.append(disk)
3991

    
3992
  return [disk.uuid for disk in faulty_disks]
3993

    
3994

    
3995
def GetDrbdUsermodeHelper():
3996
  """Returns DRBD usermode helper currently configured.
3997

3998
  """
3999
  try:
4000
    return drbd.DRBD8.GetUsermodeHelper()
4001
  except errors.BlockDeviceError, err:
4002
    _Fail(str(err))
4003

    
4004

    
4005
def PowercycleNode(hypervisor_type, hvparams=None):
4006
  """Hard-powercycle the node.
4007

4008
  Because we need to return first, and schedule the powercycle in the
4009
  background, we won't be able to report failures nicely.
4010

4011
  """
4012
  hyper = hypervisor.GetHypervisor(hypervisor_type)
4013
  try:
4014
    pid = os.fork()
4015
  except OSError:
4016
    # if we can't fork, we'll pretend that we're in the child process
4017
    pid = 0
4018
  if pid > 0:
4019
    return "Reboot scheduled in 5 seconds"
4020
  # ensure the child is running on ram
4021
  try:
4022
    utils.Mlockall()
4023
  except Exception: # pylint: disable=W0703
4024
    pass
4025
  time.sleep(5)
4026
  hyper.PowercycleNode(hvparams=hvparams)
4027

    
4028

    
4029
def _VerifyRestrictedCmdName(cmd):
4030
  """Verifies a restricted command name.
4031

4032
  @type cmd: string
4033
  @param cmd: Command name
4034
  @rtype: tuple; (boolean, string or None)
4035
  @return: The tuple's first element is the status; if C{False}, the second
4036
    element is an error message string, otherwise it's C{None}
4037

4038
  """
4039
  if not cmd.strip():
4040
    return (False, "Missing command name")
4041

    
4042
  if os.path.basename(cmd) != cmd:
4043
    return (False, "Invalid command name")
4044

    
4045
  if not constants.EXT_PLUGIN_MASK.match(cmd):
4046
    return (False, "Command name contains forbidden characters")
4047

    
4048
  return (True, None)
4049

    
4050

    
4051
def _CommonRestrictedCmdCheck(path, owner):
4052
  """Common checks for restricted command file system directories and files.
4053

4054
  @type path: string
4055
  @param path: Path to check
4056
  @param owner: C{None} or tuple containing UID and GID
4057
  @rtype: tuple; (boolean, string or C{os.stat} result)
4058
  @return: The tuple's first element is the status; if C{False}, the second
4059
    element is an error message string, otherwise it's the result of C{os.stat}
4060

4061
  """
4062
  if owner is None:
4063
    # Default to root as owner
4064
    owner = (0, 0)
4065

    
4066
  try:
4067
    st = os.stat(path)
4068
  except EnvironmentError, err:
4069
    return (False, "Can't stat(2) '%s': %s" % (path, err))
4070

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

    
4074
  if (st.st_uid, st.st_gid) != owner:
4075
    (owner_uid, owner_gid) = owner
4076
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
4077

    
4078
  return (True, st)
4079

    
4080

    
4081
def _VerifyRestrictedCmdDirectory(path, _owner=None):
4082
  """Verifies restricted command directory.
4083

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

4090
  """
4091
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
4092

    
4093
  if not status:
4094
    return (False, value)
4095

    
4096
  if not stat.S_ISDIR(value.st_mode):
4097
    return (False, "Path '%s' is not a directory" % path)
4098

    
4099
  return (True, None)
4100

    
4101

    
4102
def _VerifyRestrictedCmd(path, cmd, _owner=None):
4103
  """Verifies a whole restricted command and returns its executable filename.
4104

4105
  @type path: string
4106
  @param path: Directory containing restricted commands
4107
  @type cmd: string
4108
  @param cmd: Command name
4109
  @rtype: tuple; (boolean, string)
4110
  @return: The tuple's first element is the status; if C{False}, the second
4111
    element is an error message string, otherwise the second element is the
4112
    absolute path to the executable
4113

4114
  """
4115
  executable = utils.PathJoin(path, cmd)
4116

    
4117
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
4118

    
4119
  if not status:
4120
    return (False, msg)