Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 790d491c

History | View | Annotate | Download (135 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 _GetVgInfo(name, excl_stor):
577
  """Retrieves information about a LVM volume group.
578

579
  """
580
  # TODO: GetVGInfo supports returning information for multiple VGs at once
581
  vginfo = bdev.LogicalVolume.GetVGInfo([name], excl_stor)
582
  if vginfo:
583
    vg_free = int(round(vginfo[0][0], 0))
584
    vg_size = int(round(vginfo[0][1], 0))
585
  else:
586
    vg_free = None
587
    vg_size = None
588

    
589
  return {
590
    "type": constants.ST_LVM_VG,
591
    "name": name,
592
    "storage_free": vg_free,
593
    "storage_size": vg_size,
594
    }
595

    
596

    
597
def _GetVgSpindlesInfo(name, excl_stor):
598
  """Retrieves information about spindles in an LVM volume group.
599

600
  @type name: string
601
  @param name: VG name
602
  @type excl_stor: bool
603
  @param excl_stor: exclusive storage
604
  @rtype: dict
605
  @return: dictionary whose keys are "name", "vg_free", "vg_size" for VG name,
606
      free spindles, total spindles respectively
607

608
  """
609
  if excl_stor:
610
    (vg_free, vg_size) = bdev.LogicalVolume.GetVgSpindlesInfo(name)
611
  else:
612
    vg_free = 0
613
    vg_size = 0
614
  return {
615
    "type": constants.ST_LVM_PV,
616
    "name": name,
617
    "storage_free": vg_free,
618
    "storage_size": vg_size,
619
    }
620

    
621

    
622
def _GetHvInfo(name, hvparams, get_hv_fn=hypervisor.GetHypervisor):
623
  """Retrieves node information from a hypervisor.
624

625
  The information returned depends on the hypervisor. Common items:
626

627
    - vg_size is the size of the configured volume group in MiB
628
    - vg_free is the free size of the volume group in MiB
629
    - memory_dom0 is the memory allocated for domain0 in MiB
630
    - memory_free is the currently available (free) ram in MiB
631
    - memory_total is the total number of ram in MiB
632
    - hv_version: the hypervisor version, if available
633

634
  @type hvparams: dict of string
635
  @param hvparams: the hypervisor's hvparams
636

637
  """
638
  return get_hv_fn(name).GetNodeInfo(hvparams=hvparams)
639

    
640

    
641
def _GetHvInfoAll(hv_specs, get_hv_fn=hypervisor.GetHypervisor):
642
  """Retrieves node information for all hypervisors.
643

644
  See C{_GetHvInfo} for information on the output.
645

646
  @type hv_specs: list of pairs (string, dict of strings)
647
  @param hv_specs: list of pairs of a hypervisor's name and its hvparams
648

649
  """
650
  if hv_specs is None:
651
    return None
652

    
653
  result = []
654
  for hvname, hvparams in hv_specs:
655
    result.append(_GetHvInfo(hvname, hvparams, get_hv_fn))
656
  return result
657

    
658

    
659
def _GetNamedNodeInfo(names, fn):
660
  """Calls C{fn} for all names in C{names} and returns a dictionary.
661

662
  @rtype: None or dict
663

664
  """
665
  if names is None:
666
    return None
667
  else:
668
    return map(fn, names)
669

    
670

    
671
def GetNodeInfo(storage_units, hv_specs, excl_stor):
672
  """Gives back a hash with different information about the node.
673

674
  @type storage_units: list of pairs (string, string)
675
  @param storage_units: List of pairs (storage unit, identifier) to ask for disk
676
                        space information. In case of lvm-vg, the identifier is
677
                        the VG name.
678
  @type hv_specs: list of pairs (string, dict of strings)
679
  @param hv_specs: list of pairs of a hypervisor's name and its hvparams
680
  @type excl_stor: boolean
681
  @param excl_stor: Whether exclusive_storage is active
682
  @rtype: tuple; (string, None/dict, None/dict)
683
  @return: Tuple containing boot ID, volume group information and hypervisor
684
    information
685

686
  """
687
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
688
  storage_info = _GetNamedNodeInfo(
689
    storage_units,
690
    (lambda storage_unit: _ApplyStorageInfoFunction(storage_unit[0],
691
                                                    storage_unit[1],
692
                                                    excl_stor)))
693
  hv_info = _GetHvInfoAll(hv_specs)
694
  return (bootid, storage_info, hv_info)
695

    
696

    
697
# pylint: disable=W0613
698
def _GetFileStorageSpaceInfo(path, *args):
699
  """Wrapper around filestorage.GetSpaceInfo.
700

701
  The purpose of this wrapper is to call filestorage.GetFileStorageSpaceInfo
702
  and ignore the *args parameter to not leak it into the filestorage
703
  module's code.
704

705
  @see: C{filestorage.GetFileStorageSpaceInfo} for description of the
706
    parameters.
707

708
  """
709
  return filestorage.GetFileStorageSpaceInfo(path)
710

    
711

    
712
# FIXME: implement storage reporting for all missing storage types.
713
_STORAGE_TYPE_INFO_FN = {
714
  constants.ST_BLOCK: None,
715
  constants.ST_DISKLESS: None,
716
  constants.ST_EXT: None,
717
  constants.ST_FILE: _GetFileStorageSpaceInfo,
718
  constants.ST_LVM_PV: _GetVgSpindlesInfo,
719
  constants.ST_LVM_VG: _GetVgInfo,
720
  constants.ST_RADOS: None,
721
}
722

    
723

    
724
def _ApplyStorageInfoFunction(storage_type, storage_key, *args):
725
  """Looks up and applies the correct function to calculate free and total
726
  storage for the given storage type.
727

728
  @type storage_type: string
729
  @param storage_type: the storage type for which the storage shall be reported.
730
  @type storage_key: string
731
  @param storage_key: identifier of a storage unit, e.g. the volume group name
732
    of an LVM storage unit
733
  @type args: any
734
  @param args: various parameters that can be used for storage reporting. These
735
    parameters and their semantics vary from storage type to storage type and
736
    are just propagated in this function.
737
  @return: the results of the application of the storage space function (see
738
    _STORAGE_TYPE_INFO_FN) if storage space reporting is implemented for that
739
    storage type
740
  @raises NotImplementedError: for storage types who don't support space
741
    reporting yet
742
  """
743
  fn = _STORAGE_TYPE_INFO_FN[storage_type]
744
  if fn is not None:
745
    return fn(storage_key, *args)
746
  else:
747
    raise NotImplementedError
748

    
749

    
750
def _CheckExclusivePvs(pvi_list):
751
  """Check that PVs are not shared among LVs
752

753
  @type pvi_list: list of L{objects.LvmPvInfo} objects
754
  @param pvi_list: information about the PVs
755

756
  @rtype: list of tuples (string, list of strings)
757
  @return: offending volumes, as tuples: (pv_name, [lv1_name, lv2_name...])
758

759
  """
760
  res = []
761
  for pvi in pvi_list:
762
    if len(pvi.lv_list) > 1:
763
      res.append((pvi.name, pvi.lv_list))
764
  return res
765

    
766

    
767
def _VerifyHypervisors(what, vm_capable, result, all_hvparams,
768
                       get_hv_fn=hypervisor.GetHypervisor):
769
  """Verifies the hypervisor. Appends the results to the 'results' list.
770

771
  @type what: C{dict}
772
  @param what: a dictionary of things to check
773
  @type vm_capable: boolean
774
  @param vm_capable: whether or not this node is vm capable
775
  @type result: dict
776
  @param result: dictionary of verification results; results of the
777
    verifications in this function will be added here
778
  @type all_hvparams: dict of dict of string
779
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
780
  @type get_hv_fn: function
781
  @param get_hv_fn: function to retrieve the hypervisor, to improve testability
782

783
  """
784
  if not vm_capable:
785
    return
786

    
787
  if constants.NV_HYPERVISOR in what:
788
    result[constants.NV_HYPERVISOR] = {}
789
    for hv_name in what[constants.NV_HYPERVISOR]:
790
      hvparams = all_hvparams[hv_name]
791
      try:
792
        val = get_hv_fn(hv_name).Verify(hvparams=hvparams)
793
      except errors.HypervisorError, err:
794
        val = "Error while checking hypervisor: %s" % str(err)
795
      result[constants.NV_HYPERVISOR][hv_name] = val
796

    
797

    
798
def _VerifyHvparams(what, vm_capable, result,
799
                    get_hv_fn=hypervisor.GetHypervisor):
800
  """Verifies the hvparams. Appends the results to the 'results' list.
801

802
  @type what: C{dict}
803
  @param what: a dictionary of things to check
804
  @type vm_capable: boolean
805
  @param vm_capable: whether or not this node is vm capable
806
  @type result: dict
807
  @param result: dictionary of verification results; results of the
808
    verifications in this function will be added here
809
  @type get_hv_fn: function
810
  @param get_hv_fn: function to retrieve the hypervisor, to improve testability
811

812
  """
813
  if not vm_capable:
814
    return
815

    
816
  if constants.NV_HVPARAMS in what:
817
    result[constants.NV_HVPARAMS] = []
818
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
819
      try:
820
        logging.info("Validating hv %s, %s", hv_name, hvparms)
821
        get_hv_fn(hv_name).ValidateParameters(hvparms)
822
      except errors.HypervisorError, err:
823
        result[constants.NV_HVPARAMS].append((source, hv_name, str(err)))
824

    
825

    
826
def _VerifyInstanceList(what, vm_capable, result, all_hvparams):
827
  """Verifies the instance list.
828

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

839
  """
840
  if constants.NV_INSTANCELIST in what and vm_capable:
841
    # GetInstanceList can fail
842
    try:
843
      val = GetInstanceList(what[constants.NV_INSTANCELIST],
844
                            all_hvparams=all_hvparams)
845
    except RPCFail, err:
846
      val = str(err)
847
    result[constants.NV_INSTANCELIST] = val
848

    
849

    
850
def _VerifyNodeInfo(what, vm_capable, result, all_hvparams):
851
  """Verifies the node info.
852

853
  @type what: C{dict}
854
  @param what: a dictionary of things to check
855
  @type vm_capable: boolean
856
  @param vm_capable: whether or not this node is vm capable
857
  @type result: dict
858
  @param result: dictionary of verification results; results of the
859
    verifications in this function will be added here
860
  @type all_hvparams: dict of dict of string
861
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
862

863
  """
864
  if constants.NV_HVINFO in what and vm_capable:
865
    hvname = what[constants.NV_HVINFO]
866
    hyper = hypervisor.GetHypervisor(hvname)
867
    hvparams = all_hvparams[hvname]
868
    result[constants.NV_HVINFO] = hyper.GetNodeInfo(hvparams=hvparams)
869

    
870

    
871
def VerifyNode(what, cluster_name, all_hvparams):
872
  """Verify the status of the local node.
873

874
  Based on the input L{what} parameter, various checks are done on the
875
  local node.
876

877
  If the I{filelist} key is present, this list of
878
  files is checksummed and the file/checksum pairs are returned.
879

880
  If the I{nodelist} key is present, we check that we have
881
  connectivity via ssh with the target nodes (and check the hostname
882
  report).
883

884
  If the I{node-net-test} key is present, we check that we have
885
  connectivity to the given nodes via both primary IP and, if
886
  applicable, secondary IPs.
887

888
  @type what: C{dict}
889
  @param what: a dictionary of things to check:
890
      - filelist: list of files for which to compute checksums
891
      - nodelist: list of nodes we should check ssh communication with
892
      - node-net-test: list of nodes we should check node daemon port
893
        connectivity with
894
      - hypervisor: list with hypervisors to run the verify for
895
  @type cluster_name: string
896
  @param cluster_name: the cluster's name
897
  @type all_hvparams: dict of dict of strings
898
  @param all_hvparams: a dictionary mapping hypervisor names to hvparams
899
  @rtype: dict
900
  @return: a dictionary with the same keys as the input dict, and
901
      values representing the result of the checks
902

903
  """
904
  result = {}
905
  my_name = netutils.Hostname.GetSysName()
906
  port = netutils.GetDaemonPort(constants.NODED)
907
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
908

    
909
  _VerifyHypervisors(what, vm_capable, result, all_hvparams)
910
  _VerifyHvparams(what, vm_capable, result)
911

    
912
  if constants.NV_FILELIST in what:
913
    fingerprints = utils.FingerprintFiles(map(vcluster.LocalizeVirtualPath,
914
                                              what[constants.NV_FILELIST]))
915
    result[constants.NV_FILELIST] = \
916
      dict((vcluster.MakeVirtualPath(key), value)
917
           for (key, value) in fingerprints.items())
918

    
919
  if constants.NV_NODELIST in what:
920
    (nodes, bynode) = what[constants.NV_NODELIST]
921

    
922
    # Add nodes from other groups (different for each node)
923
    try:
924
      nodes.extend(bynode[my_name])
925
    except KeyError:
926
      pass
927

    
928
    # Use a random order
929
    random.shuffle(nodes)
930

    
931
    # Try to contact all nodes
932
    val = {}
933
    for node in nodes:
934
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
935
      if not success:
936
        val[node] = message
937

    
938
    result[constants.NV_NODELIST] = val
939

    
940
  if constants.NV_NODENETTEST in what:
941
    result[constants.NV_NODENETTEST] = tmp = {}
942
    my_pip = my_sip = None
943
    for name, pip, sip in what[constants.NV_NODENETTEST]:
944
      if name == my_name:
945
        my_pip = pip
946
        my_sip = sip
947
        break
948
    if not my_pip:
949
      tmp[my_name] = ("Can't find my own primary/secondary IP"
950
                      " in the node list")
951
    else:
952
      for name, pip, sip in what[constants.NV_NODENETTEST]:
953
        fail = []
954
        if not netutils.TcpPing(pip, port, source=my_pip):
955
          fail.append("primary")
956
        if sip != pip:
957
          if not netutils.TcpPing(sip, port, source=my_sip):
958
            fail.append("secondary")
959
        if fail:
960
          tmp[name] = ("failure using the %s interface(s)" %
961
                       " and ".join(fail))
962

    
963
  if constants.NV_MASTERIP in what:
964
    # FIXME: add checks on incoming data structures (here and in the
965
    # rest of the function)
966
    master_name, master_ip = what[constants.NV_MASTERIP]
967
    if master_name == my_name:
968
      source = constants.IP4_ADDRESS_LOCALHOST
969
    else:
970
      source = None
971
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
972
                                                     source=source)
973

    
974
  if constants.NV_USERSCRIPTS in what:
975
    result[constants.NV_USERSCRIPTS] = \
976
      [script for script in what[constants.NV_USERSCRIPTS]
977
       if not utils.IsExecutable(script)]
978

    
979
  if constants.NV_OOB_PATHS in what:
980
    result[constants.NV_OOB_PATHS] = tmp = []
981
    for path in what[constants.NV_OOB_PATHS]:
982
      try:
983
        st = os.stat(path)
984
      except OSError, err:
985
        tmp.append("error stating out of band helper: %s" % err)
986
      else:
987
        if stat.S_ISREG(st.st_mode):
988
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
989
            tmp.append(None)
990
          else:
991
            tmp.append("out of band helper %s is not executable" % path)
992
        else:
993
          tmp.append("out of band helper %s is not a file" % path)
994

    
995
  if constants.NV_LVLIST in what and vm_capable:
996
    try:
997
      val = GetVolumeList(utils.ListVolumeGroups().keys())
998
    except RPCFail, err:
999
      val = str(err)
1000
    result[constants.NV_LVLIST] = val
1001

    
1002
  _VerifyInstanceList(what, vm_capable, result, all_hvparams)
1003

    
1004
  if constants.NV_VGLIST in what and vm_capable:
1005
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
1006

    
1007
  if constants.NV_PVLIST in what and vm_capable:
1008
    check_exclusive_pvs = constants.NV_EXCLUSIVEPVS in what
1009
    val = bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
1010
                                       filter_allocatable=False,
1011
                                       include_lvs=check_exclusive_pvs)
1012
    if check_exclusive_pvs:
1013
      result[constants.NV_EXCLUSIVEPVS] = _CheckExclusivePvs(val)
1014
      for pvi in val:
1015
        # Avoid sending useless data on the wire
1016
        pvi.lv_list = []
1017
    result[constants.NV_PVLIST] = map(objects.LvmPvInfo.ToDict, val)
1018

    
1019
  if constants.NV_VERSION in what:
1020
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
1021
                                    constants.RELEASE_VERSION)
1022

    
1023
  _VerifyNodeInfo(what, vm_capable, result, all_hvparams)
1024

    
1025
  if constants.NV_DRBDVERSION in what and vm_capable:
1026
    try:
1027
      drbd_version = DRBD8.GetProcInfo().GetVersionString()
1028
    except errors.BlockDeviceError, err:
1029
      logging.warning("Can't get DRBD version", exc_info=True)
1030
      drbd_version = str(err)
1031
    result[constants.NV_DRBDVERSION] = drbd_version
1032

    
1033
  if constants.NV_DRBDLIST in what and vm_capable:
1034
    try:
1035
      used_minors = drbd.DRBD8.GetUsedDevs()
1036
    except errors.BlockDeviceError, err:
1037
      logging.warning("Can't get used minors list", exc_info=True)
1038
      used_minors = str(err)
1039
    result[constants.NV_DRBDLIST] = used_minors
1040

    
1041
  if constants.NV_DRBDHELPER in what and vm_capable:
1042
    status = True
1043
    try:
1044
      payload = drbd.DRBD8.GetUsermodeHelper()
1045
    except errors.BlockDeviceError, err:
1046
      logging.error("Can't get DRBD usermode helper: %s", str(err))
1047
      status = False
1048
      payload = str(err)
1049
    result[constants.NV_DRBDHELPER] = (status, payload)
1050

    
1051
  if constants.NV_NODESETUP in what:
1052
    result[constants.NV_NODESETUP] = tmpr = []
1053
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
1054
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
1055
                  " under /sys, missing required directories /sys/block"
1056
                  " and /sys/class/net")
1057
    if (not os.path.isdir("/proc/sys") or
1058
        not os.path.isfile("/proc/sysrq-trigger")):
1059
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
1060
                  " under /proc, missing required directory /proc/sys and"
1061
                  " the file /proc/sysrq-trigger")
1062

    
1063
  if constants.NV_TIME in what:
1064
    result[constants.NV_TIME] = utils.SplitTime(time.time())
1065

    
1066
  if constants.NV_OSLIST in what and vm_capable:
1067
    result[constants.NV_OSLIST] = DiagnoseOS()
1068

    
1069
  if constants.NV_BRIDGES in what and vm_capable:
1070
    result[constants.NV_BRIDGES] = [bridge
1071
                                    for bridge in what[constants.NV_BRIDGES]
1072
                                    if not utils.BridgeExists(bridge)]
1073

    
1074
  if what.get(constants.NV_FILE_STORAGE_PATHS) == my_name:
1075
    result[constants.NV_FILE_STORAGE_PATHS] = \
1076
      bdev.ComputeWrongFileStoragePaths()
1077

    
1078
  return result
1079

    
1080

    
1081
def GetBlockDevSizes(devices):
1082
  """Return the size of the given block devices
1083

1084
  @type devices: list
1085
  @param devices: list of block device nodes to query
1086
  @rtype: dict
1087
  @return:
1088
    dictionary of all block devices under /dev (key). The value is their
1089
    size in MiB.
1090

1091
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
1092

1093
  """
1094
  DEV_PREFIX = "/dev/"
1095
  blockdevs = {}
1096

    
1097
  for devpath in devices:
1098
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
1099
      continue
1100

    
1101
    try:
1102
      st = os.stat(devpath)
1103
    except EnvironmentError, err:
1104
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
1105
      continue
1106

    
1107
    if stat.S_ISBLK(st.st_mode):
1108
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
1109
      if result.failed:
1110
        # We don't want to fail, just do not list this device as available
1111
        logging.warning("Cannot get size for block device %s", devpath)
1112
        continue
1113

    
1114
      size = int(result.stdout) / (1024 * 1024)
1115
      blockdevs[devpath] = size
1116
  return blockdevs
1117

    
1118

    
1119
def GetVolumeList(vg_names):
1120
  """Compute list of logical volumes and their size.
1121

1122
  @type vg_names: list
1123
  @param vg_names: the volume groups whose LVs we should list, or
1124
      empty for all volume groups
1125
  @rtype: dict
1126
  @return:
1127
      dictionary of all partions (key) with value being a tuple of
1128
      their size (in MiB), inactive and online status::
1129

1130
        {'xenvg/test1': ('20.06', True, True)}
1131

1132
      in case of errors, a string is returned with the error
1133
      details.
1134

1135
  """
1136
  lvs = {}
1137
  sep = "|"
1138
  if not vg_names:
1139
    vg_names = []
1140
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1141
                         "--separator=%s" % sep,
1142
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
1143
  if result.failed:
1144
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
1145

    
1146
  for line in result.stdout.splitlines():
1147
    line = line.strip()
1148
    match = _LVSLINE_REGEX.match(line)
1149
    if not match:
1150
      logging.error("Invalid line returned from lvs output: '%s'", line)
1151
      continue
1152
    vg_name, name, size, attr = match.groups()
1153
    inactive = attr[4] == "-"
1154
    online = attr[5] == "o"
1155
    virtual = attr[0] == "v"
1156
    if virtual:
1157
      # we don't want to report such volumes as existing, since they
1158
      # don't really hold data
1159
      continue
1160
    lvs[vg_name + "/" + name] = (size, inactive, online)
1161

    
1162
  return lvs
1163

    
1164

    
1165
def ListVolumeGroups():
1166
  """List the volume groups and their size.
1167

1168
  @rtype: dict
1169
  @return: dictionary with keys volume name and values the
1170
      size of the volume
1171

1172
  """
1173
  return utils.ListVolumeGroups()
1174

    
1175

    
1176
def NodeVolumes():
1177
  """List all volumes on this node.
1178

1179
  @rtype: list
1180
  @return:
1181
    A list of dictionaries, each having four keys:
1182
      - name: the logical volume name,
1183
      - size: the size of the logical volume
1184
      - dev: the physical device on which the LV lives
1185
      - vg: the volume group to which it belongs
1186

1187
    In case of errors, we return an empty list and log the
1188
    error.
1189

1190
    Note that since a logical volume can live on multiple physical
1191
    volumes, the resulting list might include a logical volume
1192
    multiple times.
1193

1194
  """
1195
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1196
                         "--separator=|",
1197
                         "--options=lv_name,lv_size,devices,vg_name"])
1198
  if result.failed:
1199
    _Fail("Failed to list logical volumes, lvs output: %s",
1200
          result.output)
1201

    
1202
  def parse_dev(dev):
1203
    return dev.split("(")[0]
1204

    
1205
  def handle_dev(dev):
1206
    return [parse_dev(x) for x in dev.split(",")]
1207

    
1208
  def map_line(line):
1209
    line = [v.strip() for v in line]
1210
    return [{"name": line[0], "size": line[1],
1211
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
1212

    
1213
  all_devs = []
1214
  for line in result.stdout.splitlines():
1215
    if line.count("|") >= 3:
1216
      all_devs.extend(map_line(line.split("|")))
1217
    else:
1218
      logging.warning("Strange line in the output from lvs: '%s'", line)
1219
  return all_devs
1220

    
1221

    
1222
def BridgesExist(bridges_list):
1223
  """Check if a list of bridges exist on the current node.
1224

1225
  @rtype: boolean
1226
  @return: C{True} if all of them exist, C{False} otherwise
1227

1228
  """
1229
  missing = []
1230
  for bridge in bridges_list:
1231
    if not utils.BridgeExists(bridge):
1232
      missing.append(bridge)
1233

    
1234
  if missing:
1235
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
1236

    
1237

    
1238
def GetInstanceListForHypervisor(hname, hvparams=None,
1239
                                 get_hv_fn=hypervisor.GetHypervisor):
1240
  """Provides a list of instances of the given hypervisor.
1241

1242
  @type hname: string
1243
  @param hname: name of the hypervisor
1244
  @type hvparams: dict of strings
1245
  @param hvparams: hypervisor parameters for the given hypervisor
1246
  @type get_hv_fn: function
1247
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1248
    name; optional parameter to increase testability
1249

1250
  @rtype: list
1251
  @return: a list of all running instances on the current node
1252
    - instance1.example.com
1253
    - instance2.example.com
1254

1255
  """
1256
  results = []
1257
  try:
1258
    hv = get_hv_fn(hname)
1259
    names = hv.ListInstances(hvparams=hvparams)
1260
    results.extend(names)
1261
  except errors.HypervisorError, err:
1262
    _Fail("Error enumerating instances (hypervisor %s): %s",
1263
          hname, err, exc=True)
1264
  return results
1265

    
1266

    
1267
def GetInstanceList(hypervisor_list, all_hvparams=None,
1268
                    get_hv_fn=hypervisor.GetHypervisor):
1269
  """Provides a list of instances.
1270

1271
  @type hypervisor_list: list
1272
  @param hypervisor_list: the list of hypervisors to query information
1273
  @type all_hvparams: dict of dict of strings
1274
  @param all_hvparams: a dictionary mapping hypervisor types to respective
1275
    cluster-wide hypervisor parameters
1276
  @type get_hv_fn: function
1277
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1278
    name; optional parameter to increase testability
1279

1280
  @rtype: list
1281
  @return: a list of all running instances on the current node
1282
    - instance1.example.com
1283
    - instance2.example.com
1284

1285
  """
1286
  results = []
1287
  for hname in hypervisor_list:
1288
    hvparams = all_hvparams[hname]
1289
    results.extend(GetInstanceListForHypervisor(hname, hvparams=hvparams,
1290
                                                get_hv_fn=get_hv_fn))
1291
  return results
1292

    
1293

    
1294
def GetInstanceInfo(instance, hname, hvparams=None):
1295
  """Gives back the information about an instance as a dictionary.
1296

1297
  @type instance: string
1298
  @param instance: the instance name
1299
  @type hname: string
1300
  @param hname: the hypervisor type of the instance
1301
  @type hvparams: dict of strings
1302
  @param hvparams: the instance's hvparams
1303

1304
  @rtype: dict
1305
  @return: dictionary with the following keys:
1306
      - memory: memory size of instance (int)
1307
      - state: xen state of instance (string)
1308
      - time: cpu time of instance (float)
1309
      - vcpus: the number of vcpus (int)
1310

1311
  """
1312
  output = {}
1313

    
1314
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance,
1315
                                                          hvparams=hvparams)
1316
  if iinfo is not None:
1317
    output["memory"] = iinfo[2]
1318
    output["vcpus"] = iinfo[3]
1319
    output["state"] = iinfo[4]
1320
    output["time"] = iinfo[5]
1321

    
1322
  return output
1323

    
1324

    
1325
def GetInstanceMigratable(instance):
1326
  """Computes whether an instance can be migrated.
1327

1328
  @type instance: L{objects.Instance}
1329
  @param instance: object representing the instance to be checked.
1330

1331
  @rtype: tuple
1332
  @return: tuple of (result, description) where:
1333
      - result: whether the instance can be migrated or not
1334
      - description: a description of the issue, if relevant
1335

1336
  """
1337
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1338
  iname = instance.name
1339
  if iname not in hyper.ListInstances(instance.hvparams):
1340
    _Fail("Instance %s is not running", iname)
1341

    
1342
  for idx in range(len(instance.disks)):
1343
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1344
    if not os.path.islink(link_name):
1345
      logging.warning("Instance %s is missing symlink %s for disk %d",
1346
                      iname, link_name, idx)
1347

    
1348

    
1349
def GetAllInstancesInfo(hypervisor_list, all_hvparams):
1350
  """Gather data about all instances.
1351

1352
  This is the equivalent of L{GetInstanceInfo}, except that it
1353
  computes data for all instances at once, thus being faster if one
1354
  needs data about more than one instance.
1355

1356
  @type hypervisor_list: list
1357
  @param hypervisor_list: list of hypervisors to query for instance data
1358
  @type all_hvparams: dict of dict of strings
1359
  @param all_hvparams: mapping of hypervisor names to hvparams
1360

1361
  @rtype: dict
1362
  @return: dictionary of instance: data, with data having the following keys:
1363
      - memory: memory size of instance (int)
1364
      - state: xen state of instance (string)
1365
      - time: cpu time of instance (float)
1366
      - vcpus: the number of vcpus
1367

1368
  """
1369
  output = {}
1370

    
1371
  for hname in hypervisor_list:
1372
    hvparams = all_hvparams[hname]
1373
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo(hvparams)
1374
    if iinfo:
1375
      for name, _, memory, vcpus, state, times in iinfo:
1376
        value = {
1377
          "memory": memory,
1378
          "vcpus": vcpus,
1379
          "state": state,
1380
          "time": times,
1381
          }
1382
        if name in output:
1383
          # we only check static parameters, like memory and vcpus,
1384
          # and not state and time which can change between the
1385
          # invocations of the different hypervisors
1386
          for key in "memory", "vcpus":
1387
            if value[key] != output[name][key]:
1388
              _Fail("Instance %s is running twice"
1389
                    " with different parameters", name)
1390
        output[name] = value
1391

    
1392
  return output
1393

    
1394

    
1395
def _InstanceLogName(kind, os_name, instance, component):
1396
  """Compute the OS log filename for a given instance and operation.
1397

1398
  The instance name and os name are passed in as strings since not all
1399
  operations have these as part of an instance object.
1400

1401
  @type kind: string
1402
  @param kind: the operation type (e.g. add, import, etc.)
1403
  @type os_name: string
1404
  @param os_name: the os name
1405
  @type instance: string
1406
  @param instance: the name of the instance being imported/added/etc.
1407
  @type component: string or None
1408
  @param component: the name of the component of the instance being
1409
      transferred
1410

1411
  """
1412
  # TODO: Use tempfile.mkstemp to create unique filename
1413
  if component:
1414
    assert "/" not in component
1415
    c_msg = "-%s" % component
1416
  else:
1417
    c_msg = ""
1418
  base = ("%s-%s-%s%s-%s.log" %
1419
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1420
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1421

    
1422

    
1423
def InstanceOsAdd(instance, reinstall, debug):
1424
  """Add an OS to an instance.
1425

1426
  @type instance: L{objects.Instance}
1427
  @param instance: Instance whose OS is to be installed
1428
  @type reinstall: boolean
1429
  @param reinstall: whether this is an instance reinstall
1430
  @type debug: integer
1431
  @param debug: debug level, passed to the OS scripts
1432
  @rtype: None
1433

1434
  """
1435
  inst_os = OSFromDisk(instance.os)
1436

    
1437
  create_env = OSEnvironment(instance, inst_os, debug)
1438
  if reinstall:
1439
    create_env["INSTANCE_REINSTALL"] = "1"
1440

    
1441
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1442

    
1443
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1444
                        cwd=inst_os.path, output=logfile, reset_env=True)
1445
  if result.failed:
1446
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1447
                  " output: %s", result.cmd, result.fail_reason, logfile,
1448
                  result.output)
1449
    lines = [utils.SafeEncode(val)
1450
             for val in utils.TailFile(logfile, lines=20)]
1451
    _Fail("OS create script failed (%s), last lines in the"
1452
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1453

    
1454

    
1455
def RunRenameInstance(instance, old_name, debug):
1456
  """Run the OS rename script for an instance.
1457

1458
  @type instance: L{objects.Instance}
1459
  @param instance: Instance whose OS is to be installed
1460
  @type old_name: string
1461
  @param old_name: previous instance name
1462
  @type debug: integer
1463
  @param debug: debug level, passed to the OS scripts
1464
  @rtype: boolean
1465
  @return: the success of the operation
1466

1467
  """
1468
  inst_os = OSFromDisk(instance.os)
1469

    
1470
  rename_env = OSEnvironment(instance, inst_os, debug)
1471
  rename_env["OLD_INSTANCE_NAME"] = old_name
1472

    
1473
  logfile = _InstanceLogName("rename", instance.os,
1474
                             "%s-%s" % (old_name, instance.name), None)
1475

    
1476
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1477
                        cwd=inst_os.path, output=logfile, reset_env=True)
1478

    
1479
  if result.failed:
1480
    logging.error("os create command '%s' returned error: %s output: %s",
1481
                  result.cmd, result.fail_reason, result.output)
1482
    lines = [utils.SafeEncode(val)
1483
             for val in utils.TailFile(logfile, lines=20)]
1484
    _Fail("OS rename script failed (%s), last lines in the"
1485
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1486

    
1487

    
1488
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1489
  """Returns symlink path for block device.
1490

1491
  """
1492
  if _dir is None:
1493
    _dir = pathutils.DISK_LINKS_DIR
1494

    
1495
  return utils.PathJoin(_dir,
1496
                        ("%s%s%s" %
1497
                         (instance_name, constants.DISK_SEPARATOR, idx)))
1498

    
1499

    
1500
def _SymlinkBlockDev(instance_name, device_path, idx):
1501
  """Set up symlinks to a instance's block device.
1502

1503
  This is an auxiliary function run when an instance is start (on the primary
1504
  node) or when an instance is migrated (on the target node).
1505

1506

1507
  @param instance_name: the name of the target instance
1508
  @param device_path: path of the physical block device, on the node
1509
  @param idx: the disk index
1510
  @return: absolute path to the disk's symlink
1511

1512
  """
1513
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1514
  try:
1515
    os.symlink(device_path, link_name)
1516
  except OSError, err:
1517
    if err.errno == errno.EEXIST:
1518
      if (not os.path.islink(link_name) or
1519
          os.readlink(link_name) != device_path):
1520
        os.remove(link_name)
1521
        os.symlink(device_path, link_name)
1522
    else:
1523
      raise
1524

    
1525
  return link_name
1526

    
1527

    
1528
def _RemoveBlockDevLinks(instance_name, disks):
1529
  """Remove the block device symlinks belonging to the given instance.
1530

1531
  """
1532
  for idx, _ in enumerate(disks):
1533
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1534
    if os.path.islink(link_name):
1535
      try:
1536
        os.remove(link_name)
1537
      except OSError:
1538
        logging.exception("Can't remove symlink '%s'", link_name)
1539

    
1540

    
1541
def _GatherAndLinkBlockDevs(instance):
1542
  """Set up an instance's block device(s).
1543

1544
  This is run on the primary node at instance startup. The block
1545
  devices must be already assembled.
1546

1547
  @type instance: L{objects.Instance}
1548
  @param instance: the instance whose disks we shoul assemble
1549
  @rtype: list
1550
  @return: list of (disk_object, device_path)
1551

1552
  """
1553
  block_devices = []
1554
  for idx, disk in enumerate(instance.disks):
1555
    device = _RecursiveFindBD(disk)
1556
    if device is None:
1557
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1558
                                    str(disk))
1559
    device.Open()
1560
    try:
1561
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1562
    except OSError, e:
1563
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1564
                                    e.strerror)
1565

    
1566
    block_devices.append((disk, link_name))
1567

    
1568
  return block_devices
1569

    
1570

    
1571
def StartInstance(instance, startup_paused, reason, store_reason=True):
1572
  """Start an instance.
1573

1574
  @type instance: L{objects.Instance}
1575
  @param instance: the instance object
1576
  @type startup_paused: bool
1577
  @param instance: pause instance at startup?
1578
  @type reason: list of reasons
1579
  @param reason: the reason trail for this startup
1580
  @type store_reason: boolean
1581
  @param store_reason: whether to store the shutdown reason trail on file
1582
  @rtype: None
1583

1584
  """
1585
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1586
                                                   instance.hvparams)
1587

    
1588
  if instance.name in running_instances:
1589
    logging.info("Instance %s already running, not starting", instance.name)
1590
    return
1591

    
1592
  try:
1593
    block_devices = _GatherAndLinkBlockDevs(instance)
1594
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1595
    hyper.StartInstance(instance, block_devices, startup_paused)
1596
    if store_reason:
1597
      _StoreInstReasonTrail(instance.name, reason)
1598
  except errors.BlockDeviceError, err:
1599
    _Fail("Block device error: %s", err, exc=True)
1600
  except errors.HypervisorError, err:
1601
    _RemoveBlockDevLinks(instance.name, instance.disks)
1602
    _Fail("Hypervisor error: %s", err, exc=True)
1603

    
1604

    
1605
def InstanceShutdown(instance, timeout, reason, store_reason=True):
1606
  """Shut an instance down.
1607

1608
  @note: this functions uses polling with a hardcoded timeout.
1609

1610
  @type instance: L{objects.Instance}
1611
  @param instance: the instance object
1612
  @type timeout: integer
1613
  @param timeout: maximum timeout for soft shutdown
1614
  @type reason: list of reasons
1615
  @param reason: the reason trail for this shutdown
1616
  @type store_reason: boolean
1617
  @param store_reason: whether to store the shutdown reason trail on file
1618
  @rtype: None
1619

1620
  """
1621
  hv_name = instance.hypervisor
1622
  hyper = hypervisor.GetHypervisor(hv_name)
1623
  iname = instance.name
1624

    
1625
  if instance.name not in hyper.ListInstances(instance.hvparams):
1626
    logging.info("Instance %s not running, doing nothing", iname)
1627
    return
1628

    
1629
  class _TryShutdown:
1630
    def __init__(self):
1631
      self.tried_once = False
1632

    
1633
    def __call__(self):
1634
      if iname not in hyper.ListInstances(instance.hvparams):
1635
        return
1636

    
1637
      try:
1638
        hyper.StopInstance(instance, retry=self.tried_once)
1639
        if store_reason:
1640
          _StoreInstReasonTrail(instance.name, reason)
1641
      except errors.HypervisorError, err:
1642
        if iname not in hyper.ListInstances(instance.hvparams):
1643
          # if the instance is no longer existing, consider this a
1644
          # success and go to cleanup
1645
          return
1646

    
1647
        _Fail("Failed to stop instance %s: %s", iname, err)
1648

    
1649
      self.tried_once = True
1650

    
1651
      raise utils.RetryAgain()
1652

    
1653
  try:
1654
    utils.Retry(_TryShutdown(), 5, timeout)
1655
  except utils.RetryTimeout:
1656
    # the shutdown did not succeed
1657
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1658

    
1659
    try:
1660
      hyper.StopInstance(instance, force=True)
1661
    except errors.HypervisorError, err:
1662
      if iname in hyper.ListInstances(instance.hvparams):
1663
        # only raise an error if the instance still exists, otherwise
1664
        # the error could simply be "instance ... unknown"!
1665
        _Fail("Failed to force stop instance %s: %s", iname, err)
1666

    
1667
    time.sleep(1)
1668

    
1669
    if iname in hyper.ListInstances(instance.hvparams):
1670
      _Fail("Could not shutdown instance %s even by destroy", iname)
1671

    
1672
  try:
1673
    hyper.CleanupInstance(instance.name)
1674
  except errors.HypervisorError, err:
1675
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1676

    
1677
  _RemoveBlockDevLinks(iname, instance.disks)
1678

    
1679

    
1680
def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1681
  """Reboot an instance.
1682

1683
  @type instance: L{objects.Instance}
1684
  @param instance: the instance object to reboot
1685
  @type reboot_type: str
1686
  @param reboot_type: the type of reboot, one the following
1687
    constants:
1688
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1689
        instance OS, do not recreate the VM
1690
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1691
        restart the VM (at the hypervisor level)
1692
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1693
        not accepted here, since that mode is handled differently, in
1694
        cmdlib, and translates into full stop and start of the
1695
        instance (instead of a call_instance_reboot RPC)
1696
  @type shutdown_timeout: integer
1697
  @param shutdown_timeout: maximum timeout for soft shutdown
1698
  @type reason: list of reasons
1699
  @param reason: the reason trail for this reboot
1700
  @rtype: None
1701

1702
  """
1703
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1704
                                                   instance.hvparams)
1705

    
1706
  if instance.name not in running_instances:
1707
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1708

    
1709
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1710
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1711
    try:
1712
      hyper.RebootInstance(instance)
1713
    except errors.HypervisorError, err:
1714
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1715
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1716
    try:
1717
      InstanceShutdown(instance, shutdown_timeout, reason, store_reason=False)
1718
      result = StartInstance(instance, False, reason, store_reason=False)
1719
      _StoreInstReasonTrail(instance.name, reason)
1720
      return result
1721
    except errors.HypervisorError, err:
1722
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1723
  else:
1724
    _Fail("Invalid reboot_type received: %s", reboot_type)
1725

    
1726

    
1727
def InstanceBalloonMemory(instance, memory):
1728
  """Resize an instance's memory.
1729

1730
  @type instance: L{objects.Instance}
1731
  @param instance: the instance object
1732
  @type memory: int
1733
  @param memory: new memory amount in MB
1734
  @rtype: None
1735

1736
  """
1737
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1738
  running = hyper.ListInstances(instance.hvparams)
1739
  if instance.name not in running:
1740
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1741
    return
1742
  try:
1743
    hyper.BalloonInstanceMemory(instance, memory)
1744
  except errors.HypervisorError, err:
1745
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1746

    
1747

    
1748
def MigrationInfo(instance):
1749
  """Gather information about an instance to be migrated.
1750

1751
  @type instance: L{objects.Instance}
1752
  @param instance: the instance definition
1753

1754
  """
1755
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1756
  try:
1757
    info = hyper.MigrationInfo(instance)
1758
  except errors.HypervisorError, err:
1759
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1760
  return info
1761

    
1762

    
1763
def AcceptInstance(instance, info, target):
1764
  """Prepare the node to accept an instance.
1765

1766
  @type instance: L{objects.Instance}
1767
  @param instance: the instance definition
1768
  @type info: string/data (opaque)
1769
  @param info: migration information, from the source node
1770
  @type target: string
1771
  @param target: target host (usually ip), on this node
1772

1773
  """
1774
  # TODO: why is this required only for DTS_EXT_MIRROR?
1775
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1776
    # Create the symlinks, as the disks are not active
1777
    # in any way
1778
    try:
1779
      _GatherAndLinkBlockDevs(instance)
1780
    except errors.BlockDeviceError, err:
1781
      _Fail("Block device error: %s", err, exc=True)
1782

    
1783
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1784
  try:
1785
    hyper.AcceptInstance(instance, info, target)
1786
  except errors.HypervisorError, err:
1787
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1788
      _RemoveBlockDevLinks(instance.name, instance.disks)
1789
    _Fail("Failed to accept instance: %s", err, exc=True)
1790

    
1791

    
1792
def FinalizeMigrationDst(instance, info, success):
1793
  """Finalize any preparation to accept an instance.
1794

1795
  @type instance: L{objects.Instance}
1796
  @param instance: the instance definition
1797
  @type info: string/data (opaque)
1798
  @param info: migration information, from the source node
1799
  @type success: boolean
1800
  @param success: whether the migration was a success or a failure
1801

1802
  """
1803
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1804
  try:
1805
    hyper.FinalizeMigrationDst(instance, info, success)
1806
  except errors.HypervisorError, err:
1807
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1808

    
1809

    
1810
def MigrateInstance(cluster_name, instance, target, live):
1811
  """Migrates an instance to another node.
1812

1813
  @type cluster_name: string
1814
  @param cluster_name: name of the cluster
1815
  @type instance: L{objects.Instance}
1816
  @param instance: the instance definition
1817
  @type target: string
1818
  @param target: the target node name
1819
  @type live: boolean
1820
  @param live: whether the migration should be done live or not (the
1821
      interpretation of this parameter is left to the hypervisor)
1822
  @raise RPCFail: if migration fails for some reason
1823

1824
  """
1825
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1826

    
1827
  try:
1828
    hyper.MigrateInstance(cluster_name, instance, target, live)
1829
  except errors.HypervisorError, err:
1830
    _Fail("Failed to migrate instance: %s", err, exc=True)
1831

    
1832

    
1833
def FinalizeMigrationSource(instance, success, live):
1834
  """Finalize the instance migration on the source node.
1835

1836
  @type instance: L{objects.Instance}
1837
  @param instance: the instance definition of the migrated instance
1838
  @type success: bool
1839
  @param success: whether the migration succeeded or not
1840
  @type live: bool
1841
  @param live: whether the user requested a live migration or not
1842
  @raise RPCFail: If the execution fails for some reason
1843

1844
  """
1845
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1846

    
1847
  try:
1848
    hyper.FinalizeMigrationSource(instance, success, live)
1849
  except Exception, err:  # pylint: disable=W0703
1850
    _Fail("Failed to finalize the migration on the source node: %s", err,
1851
          exc=True)
1852

    
1853

    
1854
def GetMigrationStatus(instance):
1855
  """Get the migration status
1856

1857
  @type instance: L{objects.Instance}
1858
  @param instance: the instance that is being migrated
1859
  @rtype: L{objects.MigrationStatus}
1860
  @return: the status of the current migration (one of
1861
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1862
           progress info that can be retrieved from the hypervisor
1863
  @raise RPCFail: If the migration status cannot be retrieved
1864

1865
  """
1866
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1867
  try:
1868
    return hyper.GetMigrationStatus(instance)
1869
  except Exception, err:  # pylint: disable=W0703
1870
    _Fail("Failed to get migration status: %s", err, exc=True)
1871

    
1872
def HotplugDevice(instance, action, dev_type, device, extra, seq):
1873
  """Hotplug a device
1874

1875
  """
1876
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1877
  try:
1878
    getattr(hyper, "HotplugDevice")
1879
  except NameError:
1880
    _Fail("Hotplug is not supported for %s hypervisor",
1881
          instance.hypervisor, exc=True )
1882
  return hyper.HotplugDevice(instance, action, dev_type, device, extra, seq)
1883

    
1884
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
1885
  """Creates a block device for an instance.
1886

1887
  @type disk: L{objects.Disk}
1888
  @param disk: the object describing the disk we should create
1889
  @type size: int
1890
  @param size: the size of the physical underlying device, in MiB
1891
  @type owner: str
1892
  @param owner: the name of the instance for which disk is created,
1893
      used for device cache data
1894
  @type on_primary: boolean
1895
  @param on_primary:  indicates if it is the primary node or not
1896
  @type info: string
1897
  @param info: string that will be sent to the physical device
1898
      creation, used for example to set (LVM) tags on LVs
1899
  @type excl_stor: boolean
1900
  @param excl_stor: Whether exclusive_storage is active
1901

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

1906
  """
1907
  # TODO: remove the obsolete "size" argument
1908
  # pylint: disable=W0613
1909
  clist = []
1910
  if disk.children:
1911
    for child in disk.children:
1912
      try:
1913
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1914
      except errors.BlockDeviceError, err:
1915
        _Fail("Can't assemble device %s: %s", child, err)
1916
      if on_primary or disk.AssembleOnSecondary():
1917
        # we need the children open in case the device itself has to
1918
        # be assembled
1919
        try:
1920
          # pylint: disable=E1103
1921
          crdev.Open()
1922
        except errors.BlockDeviceError, err:
1923
          _Fail("Can't make child '%s' read-write: %s", child, err)
1924
      clist.append(crdev)
1925

    
1926
  try:
1927
    device = bdev.Create(disk, clist, excl_stor)
1928
  except errors.BlockDeviceError, err:
1929
    _Fail("Can't create block device: %s", err)
1930

    
1931
  if on_primary or disk.AssembleOnSecondary():
1932
    try:
1933
      device.Assemble()
1934
    except errors.BlockDeviceError, err:
1935
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1936
    if on_primary or disk.OpenOnSecondary():
1937
      try:
1938
        device.Open(force=True)
1939
      except errors.BlockDeviceError, err:
1940
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1941
    DevCacheManager.UpdateCache(device.dev_path, owner,
1942
                                on_primary, disk.iv_name)
1943

    
1944
  device.SetInfo(info)
1945

    
1946
  return device.unique_id
1947

    
1948

    
1949
def _WipeDevice(path, offset, size):
1950
  """This function actually wipes the device.
1951

1952
  @param path: The path to the device to wipe
1953
  @param offset: The offset in MiB in the file
1954
  @param size: The size in MiB to write
1955

1956
  """
1957
  # Internal sizes are always in Mebibytes; if the following "dd" command
1958
  # should use a different block size the offset and size given to this
1959
  # function must be adjusted accordingly before being passed to "dd".
1960
  block_size = 1024 * 1024
1961

    
1962
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1963
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
1964
         "count=%d" % size]
1965
  result = utils.RunCmd(cmd)
1966

    
1967
  if result.failed:
1968
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1969
          result.fail_reason, result.output)
1970

    
1971

    
1972
def BlockdevWipe(disk, offset, size):
1973
  """Wipes a block device.
1974

1975
  @type disk: L{objects.Disk}
1976
  @param disk: the disk object we want to wipe
1977
  @type offset: int
1978
  @param offset: The offset in MiB in the file
1979
  @type size: int
1980
  @param size: The size in MiB to write
1981

1982
  """
1983
  try:
1984
    rdev = _RecursiveFindBD(disk)
1985
  except errors.BlockDeviceError:
1986
    rdev = None
1987

    
1988
  if not rdev:
1989
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1990

    
1991
  # Do cross verify some of the parameters
1992
  if offset < 0:
1993
    _Fail("Negative offset")
1994
  if size < 0:
1995
    _Fail("Negative size")
1996
  if offset > rdev.size:
1997
    _Fail("Offset is bigger than device size")
1998
  if (offset + size) > rdev.size:
1999
    _Fail("The provided offset and size to wipe is bigger than device size")
2000

    
2001
  _WipeDevice(rdev.dev_path, offset, size)
2002

    
2003

    
2004
def BlockdevPauseResumeSync(disks, pause):
2005
  """Pause or resume the sync of the block device.
2006

2007
  @type disks: list of L{objects.Disk}
2008
  @param disks: the disks object we want to pause/resume
2009
  @type pause: bool
2010
  @param pause: Wheater to pause or resume
2011

2012
  """
2013
  success = []
2014
  for disk in disks:
2015
    try:
2016
      rdev = _RecursiveFindBD(disk)
2017
    except errors.BlockDeviceError:
2018
      rdev = None
2019

    
2020
    if not rdev:
2021
      success.append((False, ("Cannot change sync for device %s:"
2022
                              " device not found" % disk.iv_name)))
2023
      continue
2024

    
2025
    result = rdev.PauseResumeSync(pause)
2026

    
2027
    if result:
2028
      success.append((result, None))
2029
    else:
2030
      if pause:
2031
        msg = "Pause"
2032
      else:
2033
        msg = "Resume"
2034
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
2035

    
2036
  return success
2037

    
2038

    
2039
def BlockdevRemove(disk):
2040
  """Remove a block device.
2041

2042
  @note: This is intended to be called recursively.
2043

2044
  @type disk: L{objects.Disk}
2045
  @param disk: the disk object we should remove
2046
  @rtype: boolean
2047
  @return: the success of the operation
2048

2049
  """
2050
  msgs = []
2051
  try:
2052
    rdev = _RecursiveFindBD(disk)
2053
  except errors.BlockDeviceError, err:
2054
    # probably can't attach
2055
    logging.info("Can't attach to device %s in remove", disk)
2056
    rdev = None
2057
  if rdev is not None:
2058
    r_path = rdev.dev_path
2059
    try:
2060
      rdev.Remove()
2061
    except errors.BlockDeviceError, err:
2062
      msgs.append(str(err))
2063
    if not msgs:
2064
      DevCacheManager.RemoveCache(r_path)
2065

    
2066
  if disk.children:
2067
    for child in disk.children:
2068
      try:
2069
        BlockdevRemove(child)
2070
      except RPCFail, err:
2071
        msgs.append(str(err))
2072

    
2073
  if msgs:
2074
    _Fail("; ".join(msgs))
2075

    
2076

    
2077
def _RecursiveAssembleBD(disk, owner, as_primary):
2078
  """Activate a block device for an instance.
2079

2080
  This is run on the primary and secondary nodes for an instance.
2081

2082
  @note: this function is called recursively.
2083

2084
  @type disk: L{objects.Disk}
2085
  @param disk: the disk we try to assemble
2086
  @type owner: str
2087
  @param owner: the name of the instance which owns the disk
2088
  @type as_primary: boolean
2089
  @param as_primary: if we should make the block device
2090
      read/write
2091

2092
  @return: the assembled device or None (in case no device
2093
      was assembled)
2094
  @raise errors.BlockDeviceError: in case there is an error
2095
      during the activation of the children or the device
2096
      itself
2097

2098
  """
2099
  children = []
2100
  if disk.children:
2101
    mcn = disk.ChildrenNeeded()
2102
    if mcn == -1:
2103
      mcn = 0 # max number of Nones allowed
2104
    else:
2105
      mcn = len(disk.children) - mcn # max number of Nones
2106
    for chld_disk in disk.children:
2107
      try:
2108
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
2109
      except errors.BlockDeviceError, err:
2110
        if children.count(None) >= mcn:
2111
          raise
2112
        cdev = None
2113
        logging.error("Error in child activation (but continuing): %s",
2114
                      str(err))
2115
      children.append(cdev)
2116

    
2117
  if as_primary or disk.AssembleOnSecondary():
2118
    r_dev = bdev.Assemble(disk, children)
2119
    result = r_dev
2120
    if as_primary or disk.OpenOnSecondary():
2121
      r_dev.Open()
2122
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
2123
                                as_primary, disk.iv_name)
2124

    
2125
  else:
2126
    result = True
2127
  return result
2128

    
2129

    
2130
def BlockdevAssemble(disk, owner, as_primary, idx):
2131
  """Activate a block device for an instance.
2132

2133
  This is a wrapper over _RecursiveAssembleBD.
2134

2135
  @rtype: str or boolean
2136
  @return: a C{/dev/...} path for primary nodes, and
2137
      C{True} for secondary nodes
2138

2139
  """
2140
  try:
2141
    result = _RecursiveAssembleBD(disk, owner, as_primary)
2142
    if isinstance(result, BlockDev):
2143
      # pylint: disable=E1103
2144
      result = result.dev_path
2145
      if as_primary:
2146
        _SymlinkBlockDev(owner, result, idx)
2147
  except errors.BlockDeviceError, err:
2148
    _Fail("Error while assembling disk: %s", err, exc=True)
2149
  except OSError, err:
2150
    _Fail("Error while symlinking disk: %s", err, exc=True)
2151

    
2152
  return result
2153

    
2154

    
2155
def BlockdevShutdown(disk):
2156
  """Shut down a block device.
2157

2158
  First, if the device is assembled (Attach() is successful), then
2159
  the device is shutdown. Then the children of the device are
2160
  shutdown.
2161

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

2166
  @type disk: L{objects.Disk}
2167
  @param disk: the description of the disk we should
2168
      shutdown
2169
  @rtype: None
2170

2171
  """
2172
  msgs = []
2173
  r_dev = _RecursiveFindBD(disk)
2174
  if r_dev is not None:
2175
    r_path = r_dev.dev_path
2176
    try:
2177
      r_dev.Shutdown()
2178
      DevCacheManager.RemoveCache(r_path)
2179
    except errors.BlockDeviceError, err:
2180
      msgs.append(str(err))
2181

    
2182
  if disk.children:
2183
    for child in disk.children:
2184
      try:
2185
        BlockdevShutdown(child)
2186
      except RPCFail, err:
2187
        msgs.append(str(err))
2188

    
2189
  if msgs:
2190
    _Fail("; ".join(msgs))
2191

    
2192

    
2193
def BlockdevAddchildren(parent_cdev, new_cdevs):
2194
  """Extend a mirrored block device.
2195

2196
  @type parent_cdev: L{objects.Disk}
2197
  @param parent_cdev: the disk to which we should add children
2198
  @type new_cdevs: list of L{objects.Disk}
2199
  @param new_cdevs: the list of children which we should add
2200
  @rtype: None
2201

2202
  """
2203
  parent_bdev = _RecursiveFindBD(parent_cdev)
2204
  if parent_bdev is None:
2205
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
2206
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
2207
  if new_bdevs.count(None) > 0:
2208
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
2209
  parent_bdev.AddChildren(new_bdevs)
2210

    
2211

    
2212
def BlockdevRemovechildren(parent_cdev, new_cdevs):
2213
  """Shrink a mirrored block device.
2214

2215
  @type parent_cdev: L{objects.Disk}
2216
  @param parent_cdev: the disk from which we should remove children
2217
  @type new_cdevs: list of L{objects.Disk}
2218
  @param new_cdevs: the list of children which we should remove
2219
  @rtype: None
2220

2221
  """
2222
  parent_bdev = _RecursiveFindBD(parent_cdev)
2223
  if parent_bdev is None:
2224
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
2225
  devs = []
2226
  for disk in new_cdevs:
2227
    rpath = disk.StaticDevPath()
2228
    if rpath is None:
2229
      bd = _RecursiveFindBD(disk)
2230
      if bd is None:
2231
        _Fail("Can't find device %s while removing children", disk)
2232
      else:
2233
        devs.append(bd.dev_path)
2234
    else:
2235
      if not utils.IsNormAbsPath(rpath):
2236
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
2237
      devs.append(rpath)
2238
  parent_bdev.RemoveChildren(devs)
2239

    
2240

    
2241
def BlockdevGetmirrorstatus(disks):
2242
  """Get the mirroring status of a list of devices.
2243

2244
  @type disks: list of L{objects.Disk}
2245
  @param disks: the list of disks which we should query
2246
  @rtype: disk
2247
  @return: List of L{objects.BlockDevStatus}, one for each disk
2248
  @raise errors.BlockDeviceError: if any of the disks cannot be
2249
      found
2250

2251
  """
2252
  stats = []
2253
  for dsk in disks:
2254
    rbd = _RecursiveFindBD(dsk)
2255
    if rbd is None:
2256
      _Fail("Can't find device %s", dsk)
2257

    
2258
    stats.append(rbd.CombinedSyncStatus())
2259

    
2260
  return stats
2261

    
2262

    
2263
def BlockdevGetmirrorstatusMulti(disks):
2264
  """Get the mirroring status of a list of devices.
2265

2266
  @type disks: list of L{objects.Disk}
2267
  @param disks: the list of disks which we should query
2268
  @rtype: disk
2269
  @return: List of tuples, (bool, status), one for each disk; bool denotes
2270
    success/failure, status is L{objects.BlockDevStatus} on success, string
2271
    otherwise
2272

2273
  """
2274
  result = []
2275
  for disk in disks:
2276
    try:
2277
      rbd = _RecursiveFindBD(disk)
2278
      if rbd is None:
2279
        result.append((False, "Can't find device %s" % disk))
2280
        continue
2281

    
2282
      status = rbd.CombinedSyncStatus()
2283
    except errors.BlockDeviceError, err:
2284
      logging.exception("Error while getting disk status")
2285
      result.append((False, str(err)))
2286
    else:
2287
      result.append((True, status))
2288

    
2289
  assert len(disks) == len(result)
2290

    
2291
  return result
2292

    
2293

    
2294
def _RecursiveFindBD(disk):
2295
  """Check if a device is activated.
2296

2297
  If so, return information about the real device.
2298

2299
  @type disk: L{objects.Disk}
2300
  @param disk: the disk object we need to find
2301

2302
  @return: None if the device can't be found,
2303
      otherwise the device instance
2304

2305
  """
2306
  children = []
2307
  if disk.children:
2308
    for chdisk in disk.children:
2309
      children.append(_RecursiveFindBD(chdisk))
2310

    
2311
  return bdev.FindDevice(disk, children)
2312

    
2313

    
2314
def _OpenRealBD(disk):
2315
  """Opens the underlying block device of a disk.
2316

2317
  @type disk: L{objects.Disk}
2318
  @param disk: the disk object we want to open
2319

2320
  """
2321
  real_disk = _RecursiveFindBD(disk)
2322
  if real_disk is None:
2323
    _Fail("Block device '%s' is not set up", disk)
2324

    
2325
  real_disk.Open()
2326

    
2327
  return real_disk
2328

    
2329

    
2330
def BlockdevFind(disk):
2331
  """Check if a device is activated.
2332

2333
  If it is, return information about the real device.
2334

2335
  @type disk: L{objects.Disk}
2336
  @param disk: the disk to find
2337
  @rtype: None or objects.BlockDevStatus
2338
  @return: None if the disk cannot be found, otherwise a the current
2339
           information
2340

2341
  """
2342
  try:
2343
    rbd = _RecursiveFindBD(disk)
2344
  except errors.BlockDeviceError, err:
2345
    _Fail("Failed to find device: %s", err, exc=True)
2346

    
2347
  if rbd is None:
2348
    return None
2349

    
2350
  return rbd.GetSyncStatus()
2351

    
2352

    
2353
def BlockdevGetdimensions(disks):
2354
  """Computes the size of the given disks.
2355

2356
  If a disk is not found, returns None instead.
2357

2358
  @type disks: list of L{objects.Disk}
2359
  @param disks: the list of disk to compute the size for
2360
  @rtype: list
2361
  @return: list with elements None if the disk cannot be found,
2362
      otherwise the pair (size, spindles), where spindles is None if the
2363
      device doesn't support that
2364

2365
  """
2366
  result = []
2367
  for cf in disks:
2368
    try:
2369
      rbd = _RecursiveFindBD(cf)
2370
    except errors.BlockDeviceError:
2371
      result.append(None)
2372
      continue
2373
    if rbd is None:
2374
      result.append(None)
2375
    else:
2376
      result.append(rbd.GetActualDimensions())
2377
  return result
2378

    
2379

    
2380
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2381
  """Export a block device to a remote node.
2382

2383
  @type disk: L{objects.Disk}
2384
  @param disk: the description of the disk to export
2385
  @type dest_node: str
2386
  @param dest_node: the destination node to export to
2387
  @type dest_path: str
2388
  @param dest_path: the destination path on the target node
2389
  @type cluster_name: str
2390
  @param cluster_name: the cluster name, needed for SSH hostalias
2391
  @rtype: None
2392

2393
  """
2394
  real_disk = _OpenRealBD(disk)
2395

    
2396
  # the block size on the read dd is 1MiB to match our units
2397
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2398
                               "dd if=%s bs=1048576 count=%s",
2399
                               real_disk.dev_path, str(disk.size))
2400

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

    
2410
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2411
                                                   constants.SSH_LOGIN_USER,
2412
                                                   destcmd)
2413

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

    
2417
  result = utils.RunCmd(["bash", "-c", command])
2418

    
2419
  if result.failed:
2420
    _Fail("Disk copy command '%s' returned error: %s"
2421
          " output: %s", command, result.fail_reason, result.output)
2422

    
2423

    
2424
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2425
  """Write a file to the filesystem.
2426

2427
  This allows the master to overwrite(!) a file. It will only perform
2428
  the operation if the file belongs to a list of configuration files.
2429

2430
  @type file_name: str
2431
  @param file_name: the target file name
2432
  @type data: str
2433
  @param data: the new contents of the file
2434
  @type mode: int
2435
  @param mode: the mode to give the file (can be None)
2436
  @type uid: string
2437
  @param uid: the owner of the file
2438
  @type gid: string
2439
  @param gid: the group of the file
2440
  @type atime: float
2441
  @param atime: the atime to set on the file (can be None)
2442
  @type mtime: float
2443
  @param mtime: the mtime to set on the file (can be None)
2444
  @rtype: None
2445

2446
  """
2447
  file_name = vcluster.LocalizeVirtualPath(file_name)
2448

    
2449
  if not os.path.isabs(file_name):
2450
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2451

    
2452
  if file_name not in _ALLOWED_UPLOAD_FILES:
2453
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2454
          file_name)
2455

    
2456
  raw_data = _Decompress(data)
2457

    
2458
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2459
    _Fail("Invalid username/groupname type")
2460

    
2461
  getents = runtime.GetEnts()
2462
  uid = getents.LookupUser(uid)
2463
  gid = getents.LookupGroup(gid)
2464

    
2465
  utils.SafeWriteFile(file_name, None,
2466
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2467
                      atime=atime, mtime=mtime)
2468

    
2469

    
2470
def RunOob(oob_program, command, node, timeout):
2471
  """Executes oob_program with given command on given node.
2472

2473
  @param oob_program: The path to the executable oob_program
2474
  @param command: The command to invoke on oob_program
2475
  @param node: The node given as an argument to the program
2476
  @param timeout: Timeout after which we kill the oob program
2477

2478
  @return: stdout
2479
  @raise RPCFail: If execution fails for some reason
2480

2481
  """
2482
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2483

    
2484
  if result.failed:
2485
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2486
          result.fail_reason, result.output)
2487

    
2488
  return result.stdout
2489

    
2490

    
2491
def _OSOndiskAPIVersion(os_dir):
2492
  """Compute and return the API version of a given OS.
2493

2494
  This function will try to read the API version of the OS residing in
2495
  the 'os_dir' directory.
2496

2497
  @type os_dir: str
2498
  @param os_dir: the directory in which we should look for the OS
2499
  @rtype: tuple
2500
  @return: tuple (status, data) with status denoting the validity and
2501
      data holding either the vaid versions or an error message
2502

2503
  """
2504
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2505

    
2506
  try:
2507
    st = os.stat(api_file)
2508
  except EnvironmentError, err:
2509
    return False, ("Required file '%s' not found under path %s: %s" %
2510
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2511

    
2512
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2513
    return False, ("File '%s' in %s is not a regular file" %
2514
                   (constants.OS_API_FILE, os_dir))
2515

    
2516
  try:
2517
    api_versions = utils.ReadFile(api_file).splitlines()
2518
  except EnvironmentError, err:
2519
    return False, ("Error while reading the API version file at %s: %s" %
2520
                   (api_file, utils.ErrnoOrStr(err)))
2521

    
2522
  try:
2523
    api_versions = [int(version.strip()) for version in api_versions]
2524
  except (TypeError, ValueError), err:
2525
    return False, ("API version(s) can't be converted to integer: %s" %
2526
                   str(err))
2527

    
2528
  return True, api_versions
2529

    
2530

    
2531
def DiagnoseOS(top_dirs=None):
2532
  """Compute the validity for all OSes.
2533

2534
  @type top_dirs: list
2535
  @param top_dirs: the list of directories in which to
2536
      search (if not given defaults to
2537
      L{pathutils.OS_SEARCH_PATH})
2538
  @rtype: list of L{objects.OS}
2539
  @return: a list of tuples (name, path, status, diagnose, variants,
2540
      parameters, api_version) for all (potential) OSes under all
2541
      search paths, where:
2542
          - name is the (potential) OS name
2543
          - path is the full path to the OS
2544
          - status True/False is the validity of the OS
2545
          - diagnose is the error message for an invalid OS, otherwise empty
2546
          - variants is a list of supported OS variants, if any
2547
          - parameters is a list of (name, help) parameters, if any
2548
          - api_version is a list of support OS API versions
2549

2550
  """
2551
  if top_dirs is None:
2552
    top_dirs = pathutils.OS_SEARCH_PATH
2553

    
2554
  result = []
2555
  for dir_name in top_dirs:
2556
    if os.path.isdir(dir_name):
2557
      try:
2558
        f_names = utils.ListVisibleFiles(dir_name)
2559
      except EnvironmentError, err:
2560
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2561
        break
2562
      for name in f_names:
2563
        os_path = utils.PathJoin(dir_name, name)
2564
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2565
        if status:
2566
          diagnose = ""
2567
          variants = os_inst.supported_variants
2568
          parameters = os_inst.supported_parameters
2569
          api_versions = os_inst.api_versions
2570
        else:
2571
          diagnose = os_inst
2572
          variants = parameters = api_versions = []
2573
        result.append((name, os_path, status, diagnose, variants,
2574
                       parameters, api_versions))
2575

    
2576
  return result
2577

    
2578

    
2579
def _TryOSFromDisk(name, base_dir=None):
2580
  """Create an OS instance from disk.
2581

2582
  This function will return an OS instance if the given name is a
2583
  valid OS name.
2584

2585
  @type base_dir: string
2586
  @keyword base_dir: Base directory containing OS installations.
2587
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2588
  @rtype: tuple
2589
  @return: success and either the OS instance if we find a valid one,
2590
      or error message
2591

2592
  """
2593
  if base_dir is None:
2594
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2595
  else:
2596
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2597

    
2598
  if os_dir is None:
2599
    return False, "Directory for OS %s not found in search path" % name
2600

    
2601
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2602
  if not status:
2603
    # push the error up
2604
    return status, api_versions
2605

    
2606
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2607
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2608
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2609

    
2610
  # OS Files dictionary, we will populate it with the absolute path
2611
  # names; if the value is True, then it is a required file, otherwise
2612
  # an optional one
2613
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2614

    
2615
  if max(api_versions) >= constants.OS_API_V15:
2616
    os_files[constants.OS_VARIANTS_FILE] = False
2617

    
2618
  if max(api_versions) >= constants.OS_API_V20:
2619
    os_files[constants.OS_PARAMETERS_FILE] = True
2620
  else:
2621
    del os_files[constants.OS_SCRIPT_VERIFY]
2622

    
2623
  for (filename, required) in os_files.items():
2624
    os_files[filename] = utils.PathJoin(os_dir, filename)
2625

    
2626
    try:
2627
      st = os.stat(os_files[filename])
2628
    except EnvironmentError, err:
2629
      if err.errno == errno.ENOENT and not required:
2630
        del os_files[filename]
2631
        continue
2632
      return False, ("File '%s' under path '%s' is missing (%s)" %
2633
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2634

    
2635
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2636
      return False, ("File '%s' under path '%s' is not a regular file" %
2637
                     (filename, os_dir))
2638

    
2639
    if filename in constants.OS_SCRIPTS:
2640
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2641
        return False, ("File '%s' under path '%s' is not executable" %
2642
                       (filename, os_dir))
2643

    
2644
  variants = []
2645
  if constants.OS_VARIANTS_FILE in os_files:
2646
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2647
    try:
2648
      variants = \
2649
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2650
    except EnvironmentError, err:
2651
      # we accept missing files, but not other errors
2652
      if err.errno != errno.ENOENT:
2653
        return False, ("Error while reading the OS variants file at %s: %s" %
2654
                       (variants_file, utils.ErrnoOrStr(err)))
2655

    
2656
  parameters = []
2657
  if constants.OS_PARAMETERS_FILE in os_files:
2658
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2659
    try:
2660
      parameters = utils.ReadFile(parameters_file).splitlines()
2661
    except EnvironmentError, err:
2662
      return False, ("Error while reading the OS parameters file at %s: %s" %
2663
                     (parameters_file, utils.ErrnoOrStr(err)))
2664
    parameters = [v.split(None, 1) for v in parameters]
2665

    
2666
  os_obj = objects.OS(name=name, path=os_dir,
2667
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2668
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2669
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2670
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2671
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2672
                                                 None),
2673
                      supported_variants=variants,
2674
                      supported_parameters=parameters,
2675
                      api_versions=api_versions)
2676
  return True, os_obj
2677

    
2678

    
2679
def OSFromDisk(name, base_dir=None):
2680
  """Create an OS instance from disk.
2681

2682
  This function will return an OS instance if the given name is a
2683
  valid OS name. Otherwise, it will raise an appropriate
2684
  L{RPCFail} exception, detailing why this is not a valid OS.
2685

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

2689
  @type base_dir: string
2690
  @keyword base_dir: Base directory containing OS installations.
2691
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2692
  @rtype: L{objects.OS}
2693
  @return: the OS instance if we find a valid one
2694
  @raise RPCFail: if we don't find a valid OS
2695

2696
  """
2697
  name_only = objects.OS.GetName(name)
2698
  status, payload = _TryOSFromDisk(name_only, base_dir)
2699

    
2700
  if not status:
2701
    _Fail(payload)
2702

    
2703
  return payload
2704

    
2705

    
2706
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2707
  """Calculate the basic environment for an os script.
2708

2709
  @type os_name: str
2710
  @param os_name: full operating system name (including variant)
2711
  @type inst_os: L{objects.OS}
2712
  @param inst_os: operating system for which the environment is being built
2713
  @type os_params: dict
2714
  @param os_params: the OS parameters
2715
  @type debug: integer
2716
  @param debug: debug level (0 or 1, for OS Api 10)
2717
  @rtype: dict
2718
  @return: dict of environment variables
2719
  @raise errors.BlockDeviceError: if the block device
2720
      cannot be found
2721

2722
  """
2723
  result = {}
2724
  api_version = \
2725
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2726
  result["OS_API_VERSION"] = "%d" % api_version
2727
  result["OS_NAME"] = inst_os.name
2728
  result["DEBUG_LEVEL"] = "%d" % debug
2729

    
2730
  # OS variants
2731
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2732
    variant = objects.OS.GetVariant(os_name)
2733
    if not variant:
2734
      variant = inst_os.supported_variants[0]
2735
  else:
2736
    variant = ""
2737
  result["OS_VARIANT"] = variant
2738

    
2739
  # OS params
2740
  for pname, pvalue in os_params.items():
2741
    result["OSP_%s" % pname.upper()] = pvalue
2742

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

    
2748
  return result
2749

    
2750

    
2751
def OSEnvironment(instance, inst_os, debug=0):
2752
  """Calculate the environment for an os script.
2753

2754
  @type instance: L{objects.Instance}
2755
  @param instance: target instance for the os script run
2756
  @type inst_os: L{objects.OS}
2757
  @param inst_os: operating system for which the environment is being built
2758
  @type debug: integer
2759
  @param debug: debug level (0 or 1, for OS Api 10)
2760
  @rtype: dict
2761
  @return: dict of environment variables
2762
  @raise errors.BlockDeviceError: if the block device
2763
      cannot be found
2764

2765
  """
2766
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2767

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

    
2771
  result["HYPERVISOR"] = instance.hypervisor
2772
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2773
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2774
  result["INSTANCE_SECONDARY_NODES"] = \
2775
      ("%s" % " ".join(instance.secondary_nodes))
2776

    
2777
  # Disks
2778
  for idx, disk in enumerate(instance.disks):
2779
    real_disk = _OpenRealBD(disk)
2780
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2781
    result["DISK_%d_ACCESS" % idx] = disk.mode
2782
    result["DISK_%d_UUID" % idx] = disk.uuid
2783
    if disk.name:
2784
      result["DISK_%d_NAME" % idx] = disk.name
2785
    if constants.HV_DISK_TYPE in instance.hvparams:
2786
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2787
        instance.hvparams[constants.HV_DISK_TYPE]
2788
    if disk.dev_type in constants.LDS_BLOCK:
2789
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2790
    elif disk.dev_type == constants.LD_FILE:
2791
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2792
        "file:%s" % disk.physical_id[0]
2793

    
2794
  # NICs
2795
  for idx, nic in enumerate(instance.nics):
2796
    result["NIC_%d_MAC" % idx] = nic.mac
2797
    result["NIC_%d_UUID" % idx] = nic.uuid
2798
    if nic.name:
2799
      result["NIC_%d_NAME" % idx] = nic.name
2800
    if nic.ip:
2801
      result["NIC_%d_IP" % idx] = nic.ip
2802
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2803
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2804
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2805
    if nic.nicparams[constants.NIC_LINK]:
2806
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2807
    if nic.netinfo:
2808
      nobj = objects.Network.FromDict(nic.netinfo)
2809
      result.update(nobj.HooksDict("NIC_%d_" % idx))
2810
    if constants.HV_NIC_TYPE in instance.hvparams:
2811
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2812
        instance.hvparams[constants.HV_NIC_TYPE]
2813

    
2814
  # HV/BE params
2815
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2816
    for key, value in source.items():
2817
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2818

    
2819
  return result
2820

    
2821

    
2822
def DiagnoseExtStorage(top_dirs=None):
2823
  """Compute the validity for all ExtStorage Providers.
2824

2825
  @type top_dirs: list
2826
  @param top_dirs: the list of directories in which to
2827
      search (if not given defaults to
2828
      L{pathutils.ES_SEARCH_PATH})
2829
  @rtype: list of L{objects.ExtStorage}
2830
  @return: a list of tuples (name, path, status, diagnose, parameters)
2831
      for all (potential) ExtStorage Providers under all
2832
      search paths, where:
2833
          - name is the (potential) ExtStorage Provider
2834
          - path is the full path to the ExtStorage Provider
2835
          - status True/False is the validity of the ExtStorage Provider
2836
          - diagnose is the error message for an invalid ExtStorage Provider,
2837
            otherwise empty
2838
          - parameters is a list of (name, help) parameters, if any
2839

2840
  """
2841
  if top_dirs is None:
2842
    top_dirs = pathutils.ES_SEARCH_PATH
2843

    
2844
  result = []
2845
  for dir_name in top_dirs:
2846
    if os.path.isdir(dir_name):
2847
      try:
2848
        f_names = utils.ListVisibleFiles(dir_name)
2849
      except EnvironmentError, err:
2850
        logging.exception("Can't list the ExtStorage directory %s: %s",
2851
                          dir_name, err)
2852
        break
2853
      for name in f_names:
2854
        es_path = utils.PathJoin(dir_name, name)
2855
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2856
        if status:
2857
          diagnose = ""
2858
          parameters = es_inst.supported_parameters
2859
        else:
2860
          diagnose = es_inst
2861
          parameters = []
2862
        result.append((name, es_path, status, diagnose, parameters))
2863

    
2864
  return result
2865

    
2866

    
2867
def BlockdevGrow(disk, amount, dryrun, backingstore, excl_stor):
2868
  """Grow a stack of block devices.
2869

2870
  This function is called recursively, with the childrens being the
2871
  first ones to resize.
2872

2873
  @type disk: L{objects.Disk}
2874
  @param disk: the disk to be grown
2875
  @type amount: integer
2876
  @param amount: the amount (in mebibytes) to grow with
2877
  @type dryrun: boolean
2878
  @param dryrun: whether to execute the operation in simulation mode
2879
      only, without actually increasing the size
2880
  @param backingstore: whether to execute the operation on backing storage
2881
      only, or on "logical" storage only; e.g. DRBD is logical storage,
2882
      whereas LVM, file, RBD are backing storage
2883
  @rtype: (status, result)
2884
  @type excl_stor: boolean
2885
  @param excl_stor: Whether exclusive_storage is active
2886
  @return: a tuple with the status of the operation (True/False), and
2887
      the errors message if status is False
2888

2889
  """
2890
  r_dev = _RecursiveFindBD(disk)
2891
  if r_dev is None:
2892
    _Fail("Cannot find block device %s", disk)
2893

    
2894
  try:
2895
    r_dev.Grow(amount, dryrun, backingstore, excl_stor)
2896
  except errors.BlockDeviceError, err:
2897
    _Fail("Failed to grow block device: %s", err, exc=True)
2898

    
2899

    
2900
def BlockdevSnapshot(disk):
2901
  """Create a snapshot copy of a block device.
2902

2903
  This function is called recursively, and the snapshot is actually created
2904
  just for the leaf lvm backend device.
2905

2906
  @type disk: L{objects.Disk}
2907
  @param disk: the disk to be snapshotted
2908
  @rtype: string
2909
  @return: snapshot disk ID as (vg, lv)
2910

2911
  """
2912
  if disk.dev_type == constants.LD_DRBD8:
2913
    if not disk.children:
2914
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2915
            disk.unique_id)
2916
    return BlockdevSnapshot(disk.children[0])
2917
  elif disk.dev_type == constants.LD_LV:
2918
    r_dev = _RecursiveFindBD(disk)
2919
    if r_dev is not None:
2920
      # FIXME: choose a saner value for the snapshot size
2921
      # let's stay on the safe side and ask for the full size, for now
2922
      return r_dev.Snapshot(disk.size)
2923
    else:
2924
      _Fail("Cannot find block device %s", disk)
2925
  else:
2926
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2927
          disk.unique_id, disk.dev_type)
2928

    
2929

    
2930
def BlockdevSetInfo(disk, info):
2931
  """Sets 'metadata' information on block devices.
2932

2933
  This function sets 'info' metadata on block devices. Initial
2934
  information is set at device creation; this function should be used
2935
  for example after renames.
2936

2937
  @type disk: L{objects.Disk}
2938
  @param disk: the disk to be grown
2939
  @type info: string
2940
  @param info: new 'info' metadata
2941
  @rtype: (status, result)
2942
  @return: a tuple with the status of the operation (True/False), and
2943
      the errors message if status is False
2944

2945
  """
2946
  r_dev = _RecursiveFindBD(disk)
2947
  if r_dev is None:
2948
    _Fail("Cannot find block device %s", disk)
2949

    
2950
  try:
2951
    r_dev.SetInfo(info)
2952
  except errors.BlockDeviceError, err:
2953
    _Fail("Failed to set information on block device: %s", err, exc=True)
2954

    
2955

    
2956
def FinalizeExport(instance, snap_disks):
2957
  """Write out the export configuration information.
2958

2959
  @type instance: L{objects.Instance}
2960
  @param instance: the instance which we export, used for
2961
      saving configuration
2962
  @type snap_disks: list of L{objects.Disk}
2963
  @param snap_disks: list of snapshot block devices, which
2964
      will be used to get the actual name of the dump file
2965

2966
  @rtype: None
2967

2968
  """
2969
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
2970
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
2971

    
2972
  config = objects.SerializableConfigParser()
2973

    
2974
  config.add_section(constants.INISECT_EXP)
2975
  config.set(constants.INISECT_EXP, "version", "0")
2976
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2977
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2978
  config.set(constants.INISECT_EXP, "os", instance.os)
2979
  config.set(constants.INISECT_EXP, "compression", "none")
2980

    
2981
  config.add_section(constants.INISECT_INS)
2982
  config.set(constants.INISECT_INS, "name", instance.name)
2983
  config.set(constants.INISECT_INS, "maxmem", "%d" %
2984
             instance.beparams[constants.BE_MAXMEM])
2985
  config.set(constants.INISECT_INS, "minmem", "%d" %
2986
             instance.beparams[constants.BE_MINMEM])
2987
  # "memory" is deprecated, but useful for exporting to old ganeti versions
2988
  config.set(constants.INISECT_INS, "memory", "%d" %
2989
             instance.beparams[constants.BE_MAXMEM])
2990
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2991
             instance.beparams[constants.BE_VCPUS])
2992
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2993
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2994
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2995

    
2996
  nic_total = 0
2997
  for nic_count, nic in enumerate(instance.nics):
2998
    nic_total += 1
2999
    config.set(constants.INISECT_INS, "nic%d_mac" %
3000
               nic_count, "%s" % nic.mac)
3001
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
3002
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
3003
               "%s" % nic.network)
3004
    for param in constants.NICS_PARAMETER_TYPES:
3005
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
3006
                 "%s" % nic.nicparams.get(param, None))
3007
  # TODO: redundant: on load can read nics until it doesn't exist
3008
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
3009

    
3010
  disk_total = 0
3011
  for disk_count, disk in enumerate(snap_disks):
3012
    if disk:
3013
      disk_total += 1
3014
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
3015
                 ("%s" % disk.iv_name))
3016
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
3017
                 ("%s" % disk.physical_id[1]))
3018
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
3019
                 ("%d" % disk.size))
3020

    
3021
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
3022

    
3023
  # New-style hypervisor/backend parameters
3024

    
3025
  config.add_section(constants.INISECT_HYP)
3026
  for name, value in instance.hvparams.items():
3027
    if name not in constants.HVC_GLOBALS:
3028
      config.set(constants.INISECT_HYP, name, str(value))
3029

    
3030
  config.add_section(constants.INISECT_BEP)
3031
  for name, value in instance.beparams.items():
3032
    config.set(constants.INISECT_BEP, name, str(value))
3033

    
3034
  config.add_section(constants.INISECT_OSP)
3035
  for name, value in instance.osparams.items():
3036
    config.set(constants.INISECT_OSP, name, str(value))
3037

    
3038
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
3039
                  data=config.Dumps())
3040
  shutil.rmtree(finaldestdir, ignore_errors=True)
3041
  shutil.move(destdir, finaldestdir)
3042

    
3043

    
3044
def ExportInfo(dest):
3045
  """Get export configuration information.
3046

3047
  @type dest: str
3048
  @param dest: directory containing the export
3049

3050
  @rtype: L{objects.SerializableConfigParser}
3051
  @return: a serializable config file containing the
3052
      export info
3053

3054
  """
3055
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
3056

    
3057
  config = objects.SerializableConfigParser()
3058
  config.read(cff)
3059

    
3060
  if (not config.has_section(constants.INISECT_EXP) or
3061
      not config.has_section(constants.INISECT_INS)):
3062
    _Fail("Export info file doesn't have the required fields")
3063

    
3064
  return config.Dumps()
3065

    
3066

    
3067
def ListExports():
3068
  """Return a list of exports currently available on this machine.
3069

3070
  @rtype: list
3071
  @return: list of the exports
3072

3073
  """
3074
  if os.path.isdir(pathutils.EXPORT_DIR):
3075
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
3076
  else:
3077
    _Fail("No exports directory")
3078

    
3079

    
3080
def RemoveExport(export):
3081
  """Remove an existing export from the node.
3082

3083
  @type export: str
3084
  @param export: the name of the export to remove
3085
  @rtype: None
3086

3087
  """
3088
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
3089

    
3090
  try:
3091
    shutil.rmtree(target)
3092
  except EnvironmentError, err:
3093
    _Fail("Error while removing the export: %s", err, exc=True)
3094

    
3095

    
3096
def BlockdevRename(devlist):
3097
  """Rename a list of block devices.
3098

3099
  @type devlist: list of tuples
3100
  @param devlist: list of tuples of the form  (disk,
3101
      new_logical_id, new_physical_id); disk is an
3102
      L{objects.Disk} object describing the current disk,
3103
      and new logical_id/physical_id is the name we
3104
      rename it to
3105
  @rtype: boolean
3106
  @return: True if all renames succeeded, False otherwise
3107

3108
  """
3109
  msgs = []
3110
  result = True
3111
  for disk, unique_id in devlist:
3112
    dev = _RecursiveFindBD(disk)
3113
    if dev is None:
3114
      msgs.append("Can't find device %s in rename" % str(disk))
3115
      result = False
3116
      continue
3117
    try:
3118
      old_rpath = dev.dev_path
3119
      dev.Rename(unique_id)
3120
      new_rpath = dev.dev_path
3121
      if old_rpath != new_rpath:
3122
        DevCacheManager.RemoveCache(old_rpath)
3123
        # FIXME: we should add the new cache information here, like:
3124
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
3125
        # but we don't have the owner here - maybe parse from existing
3126
        # cache? for now, we only lose lvm data when we rename, which
3127
        # is less critical than DRBD or MD
3128
    except errors.BlockDeviceError, err:
3129
      msgs.append("Can't rename device '%s' to '%s': %s" %
3130
                  (dev, unique_id, err))
3131
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
3132
      result = False
3133
  if not result:
3134
    _Fail("; ".join(msgs))
3135

    
3136

    
3137
def _TransformFileStorageDir(fs_dir):
3138
  """Checks whether given file_storage_dir is valid.
3139

3140
  Checks wheter the given fs_dir is within the cluster-wide default
3141
  file_storage_dir or the shared_file_storage_dir, which are stored in
3142
  SimpleStore. Only paths under those directories are allowed.
3143

3144
  @type fs_dir: str
3145
  @param fs_dir: the path to check
3146

3147
  @return: the normalized path if valid, None otherwise
3148

3149
  """
3150
  if not (constants.ENABLE_FILE_STORAGE or
3151
          constants.ENABLE_SHARED_FILE_STORAGE):
3152
    _Fail("File storage disabled at configure time")
3153

    
3154
  bdev.CheckFileStoragePath(fs_dir)
3155

    
3156
  return os.path.normpath(fs_dir)
3157

    
3158

    
3159
def CreateFileStorageDir(file_storage_dir):
3160
  """Create file storage directory.
3161

3162
  @type file_storage_dir: str
3163
  @param file_storage_dir: directory to create
3164

3165
  @rtype: tuple
3166
  @return: tuple with first element a boolean indicating wheter dir
3167
      creation was successful or not
3168

3169
  """
3170
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3171
  if os.path.exists(file_storage_dir):
3172
    if not os.path.isdir(file_storage_dir):
3173
      _Fail("Specified storage dir '%s' is not a directory",
3174
            file_storage_dir)
3175
  else:
3176
    try:
3177
      os.makedirs(file_storage_dir, 0750)
3178
    except OSError, err:
3179
      _Fail("Cannot create file storage directory '%s': %s",
3180
            file_storage_dir, err, exc=True)
3181

    
3182

    
3183
def RemoveFileStorageDir(file_storage_dir):
3184
  """Remove file storage directory.
3185

3186
  Remove it only if it's empty. If not log an error and return.
3187

3188
  @type file_storage_dir: str
3189
  @param file_storage_dir: the directory we should cleanup
3190
  @rtype: tuple (success,)
3191
  @return: tuple of one element, C{success}, denoting
3192
      whether the operation was successful
3193

3194
  """
3195
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3196
  if os.path.exists(file_storage_dir):
3197
    if not os.path.isdir(file_storage_dir):
3198
      _Fail("Specified Storage directory '%s' is not a directory",
3199
            file_storage_dir)
3200
    # deletes dir only if empty, otherwise we want to fail the rpc call
3201
    try:
3202
      os.rmdir(file_storage_dir)
3203
    except OSError, err:
3204
      _Fail("Cannot remove file storage directory '%s': %s",
3205
            file_storage_dir, err)
3206

    
3207

    
3208
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
3209
  """Rename the file storage directory.
3210

3211
  @type old_file_storage_dir: str
3212
  @param old_file_storage_dir: the current path
3213
  @type new_file_storage_dir: str
3214
  @param new_file_storage_dir: the name we should rename to
3215
  @rtype: tuple (success,)
3216
  @return: tuple of one element, C{success}, denoting
3217
      whether the operation was successful
3218

3219
  """
3220
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
3221
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
3222
  if not os.path.exists(new_file_storage_dir):
3223
    if os.path.isdir(old_file_storage_dir):
3224
      try:
3225
        os.rename(old_file_storage_dir, new_file_storage_dir)
3226
      except OSError, err:
3227
        _Fail("Cannot rename '%s' to '%s': %s",
3228
              old_file_storage_dir, new_file_storage_dir, err)
3229
    else:
3230
      _Fail("Specified storage dir '%s' is not a directory",
3231
            old_file_storage_dir)
3232
  else:
3233
    if os.path.exists(old_file_storage_dir):
3234
      _Fail("Cannot rename '%s' to '%s': both locations exist",
3235
            old_file_storage_dir, new_file_storage_dir)
3236

    
3237

    
3238
def _EnsureJobQueueFile(file_name):
3239
  """Checks whether the given filename is in the queue directory.
3240

3241
  @type file_name: str
3242
  @param file_name: the file name we should check
3243
  @rtype: None
3244
  @raises RPCFail: if the file is not valid
3245

3246
  """
3247
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
3248
    _Fail("Passed job queue file '%s' does not belong to"
3249
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
3250

    
3251

    
3252
def JobQueueUpdate(file_name, content):
3253
  """Updates a file in the queue directory.
3254

3255
  This is just a wrapper over L{utils.io.WriteFile}, with proper
3256
  checking.
3257

3258
  @type file_name: str
3259
  @param file_name: the job file name
3260
  @type content: str
3261
  @param content: the new job contents
3262
  @rtype: boolean
3263
  @return: the success of the operation
3264

3265
  """
3266
  file_name = vcluster.LocalizeVirtualPath(file_name)
3267

    
3268
  _EnsureJobQueueFile(file_name)
3269
  getents = runtime.GetEnts()
3270

    
3271
  # Write and replace the file atomically
3272
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3273
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3274

    
3275

    
3276
def JobQueueRename(old, new):
3277
  """Renames a job queue file.
3278

3279
  This is just a wrapper over os.rename with proper checking.
3280

3281
  @type old: str
3282
  @param old: the old (actual) file name
3283
  @type new: str
3284
  @param new: the desired file name
3285
  @rtype: tuple
3286
  @return: the success of the operation and payload
3287

3288
  """
3289
  old = vcluster.LocalizeVirtualPath(old)
3290
  new = vcluster.LocalizeVirtualPath(new)
3291

    
3292
  _EnsureJobQueueFile(old)
3293
  _EnsureJobQueueFile(new)
3294

    
3295
  getents = runtime.GetEnts()
3296

    
3297
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3298
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3299

    
3300

    
3301
def BlockdevClose(instance_name, disks):
3302
  """Closes the given block devices.
3303

3304
  This means they will be switched to secondary mode (in case of
3305
  DRBD).
3306

3307
  @param instance_name: if the argument is not empty, the symlinks
3308
      of this instance will be removed
3309
  @type disks: list of L{objects.Disk}
3310
  @param disks: the list of disks to be closed
3311
  @rtype: tuple (success, message)
3312
  @return: a tuple of success and message, where success
3313
      indicates the succes of the operation, and message
3314
      which will contain the error details in case we
3315
      failed
3316

3317
  """
3318
  bdevs = []
3319
  for cf in disks:
3320
    rd = _RecursiveFindBD(cf)
3321
    if rd is None:
3322
      _Fail("Can't find device %s", cf)
3323
    bdevs.append(rd)
3324

    
3325
  msg = []
3326
  for rd in bdevs:
3327
    try:
3328
      rd.Close()
3329
    except errors.BlockDeviceError, err:
3330
      msg.append(str(err))
3331
  if msg:
3332
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3333
  else:
3334
    if instance_name:
3335
      _RemoveBlockDevLinks(instance_name, disks)
3336

    
3337

    
3338
def ValidateHVParams(hvname, hvparams):
3339
  """Validates the given hypervisor parameters.
3340

3341
  @type hvname: string
3342
  @param hvname: the hypervisor name
3343
  @type hvparams: dict
3344
  @param hvparams: the hypervisor parameters to be validated
3345
  @rtype: None
3346

3347
  """
3348
  try:
3349
    hv_type = hypervisor.GetHypervisor(hvname)
3350
    hv_type.ValidateParameters(hvparams)
3351
  except errors.HypervisorError, err:
3352
    _Fail(str(err), log=False)
3353

    
3354

    
3355
def _CheckOSPList(os_obj, parameters):
3356
  """Check whether a list of parameters is supported by the OS.
3357

3358
  @type os_obj: L{objects.OS}
3359
  @param os_obj: OS object to check
3360
  @type parameters: list
3361
  @param parameters: the list of parameters to check
3362

3363
  """
3364
  supported = [v[0] for v in os_obj.supported_parameters]
3365
  delta = frozenset(parameters).difference(supported)
3366
  if delta:
3367
    _Fail("The following parameters are not supported"
3368
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3369

    
3370

    
3371
def ValidateOS(required, osname, checks, osparams):
3372
  """Validate the given OS' parameters.
3373

3374
  @type required: boolean
3375
  @param required: whether absence of the OS should translate into
3376
      failure or not
3377
  @type osname: string
3378
  @param osname: the OS to be validated
3379
  @type checks: list
3380
  @param checks: list of the checks to run (currently only 'parameters')
3381
  @type osparams: dict
3382
  @param osparams: dictionary with OS parameters
3383
  @rtype: boolean
3384
  @return: True if the validation passed, or False if the OS was not
3385
      found and L{required} was false
3386

3387
  """
3388
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3389
    _Fail("Unknown checks required for OS %s: %s", osname,
3390
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3391

    
3392
  name_only = objects.OS.GetName(osname)
3393
  status, tbv = _TryOSFromDisk(name_only, None)
3394

    
3395
  if not status:
3396
    if required:
3397
      _Fail(tbv)
3398
    else:
3399
      return False
3400

    
3401
  if max(tbv.api_versions) < constants.OS_API_V20:
3402
    return True
3403

    
3404
  if constants.OS_VALIDATE_PARAMETERS in checks:
3405
    _CheckOSPList(tbv, osparams.keys())
3406

    
3407
  validate_env = OSCoreEnv(osname, tbv, osparams)
3408
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3409
                        cwd=tbv.path, reset_env=True)
3410
  if result.failed:
3411
    logging.error("os validate command '%s' returned error: %s output: %s",
3412
                  result.cmd, result.fail_reason, result.output)
3413
    _Fail("OS validation script failed (%s), output: %s",
3414
          result.fail_reason, result.output, log=False)
3415

    
3416
  return True
3417

    
3418

    
3419
def DemoteFromMC():
3420
  """Demotes the current node from master candidate role.
3421

3422
  """
3423
  # try to ensure we're not the master by mistake
3424
  master, myself = ssconf.GetMasterAndMyself()
3425
  if master == myself:
3426
    _Fail("ssconf status shows I'm the master node, will not demote")
3427

    
3428
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3429
  if not result.failed:
3430
    _Fail("The master daemon is running, will not demote")
3431

    
3432
  try:
3433
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3434
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3435
  except EnvironmentError, err:
3436
    if err.errno != errno.ENOENT:
3437
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3438

    
3439
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3440

    
3441

    
3442
def _GetX509Filenames(cryptodir, name):
3443
  """Returns the full paths for the private key and certificate.
3444

3445
  """
3446
  return (utils.PathJoin(cryptodir, name),
3447
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3448
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3449

    
3450

    
3451
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3452
  """Creates a new X509 certificate for SSL/TLS.
3453

3454
  @type validity: int
3455
  @param validity: Validity in seconds
3456
  @rtype: tuple; (string, string)
3457
  @return: Certificate name and public part
3458

3459
  """
3460
  (key_pem, cert_pem) = \
3461
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3462
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3463

    
3464
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3465
                              prefix="x509-%s-" % utils.TimestampForFilename())
3466
  try:
3467
    name = os.path.basename(cert_dir)
3468
    assert len(name) > 5
3469

    
3470
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3471

    
3472
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3473
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3474

    
3475
    # Never return private key as it shouldn't leave the node
3476
    return (name, cert_pem)
3477
  except Exception:
3478
    shutil.rmtree(cert_dir, ignore_errors=True)
3479
    raise
3480

    
3481

    
3482
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3483
  """Removes a X509 certificate.
3484

3485
  @type name: string
3486
  @param name: Certificate name
3487

3488
  """
3489
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3490

    
3491
  utils.RemoveFile(key_file)
3492
  utils.RemoveFile(cert_file)
3493

    
3494
  try:
3495
    os.rmdir(cert_dir)
3496
  except EnvironmentError, err:
3497
    _Fail("Cannot remove certificate directory '%s': %s",
3498
          cert_dir, err)
3499

    
3500

    
3501
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3502
  """Returns the command for the requested input/output.
3503

3504
  @type instance: L{objects.Instance}
3505
  @param instance: The instance object
3506
  @param mode: Import/export mode
3507
  @param ieio: Input/output type
3508
  @param ieargs: Input/output arguments
3509

3510
  """
3511
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3512

    
3513
  env = None
3514
  prefix = None
3515
  suffix = None
3516
  exp_size = None
3517

    
3518
  if ieio == constants.IEIO_FILE:
3519
    (filename, ) = ieargs
3520

    
3521
    if not utils.IsNormAbsPath(filename):
3522
      _Fail("Path '%s' is not normalized or absolute", filename)
3523

    
3524
    real_filename = os.path.realpath(filename)
3525
    directory = os.path.dirname(real_filename)
3526

    
3527
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3528
      _Fail("File '%s' is not under exports directory '%s': %s",
3529
            filename, pathutils.EXPORT_DIR, real_filename)
3530

    
3531
    # Create directory
3532
    utils.Makedirs(directory, mode=0750)
3533

    
3534
    quoted_filename = utils.ShellQuote(filename)
3535

    
3536
    if mode == constants.IEM_IMPORT:
3537
      suffix = "> %s" % quoted_filename
3538
    elif mode == constants.IEM_EXPORT:
3539
      suffix = "< %s" % quoted_filename
3540

    
3541
      # Retrieve file size
3542
      try:
3543
        st = os.stat(filename)
3544
      except EnvironmentError, err:
3545
        logging.error("Can't stat(2) %s: %s", filename, err)
3546
      else:
3547
        exp_size = utils.BytesToMebibyte(st.st_size)
3548

    
3549
  elif ieio == constants.IEIO_RAW_DISK:
3550
    (disk, ) = ieargs
3551

    
3552
    real_disk = _OpenRealBD(disk)
3553

    
3554
    if mode == constants.IEM_IMPORT:
3555
      # we set here a smaller block size as, due to transport buffering, more
3556
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3557
      # is not already there or we pass a wrong path; we use notrunc to no
3558
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3559
      # much memory; this means that at best, we flush every 64k, which will
3560
      # not be very fast
3561
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3562
                                    " bs=%s oflag=dsync"),
3563
                                    real_disk.dev_path,
3564
                                    str(64 * 1024))
3565

    
3566
    elif mode == constants.IEM_EXPORT:
3567
      # the block size on the read dd is 1MiB to match our units
3568
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3569
                                   real_disk.dev_path,
3570
                                   str(1024 * 1024), # 1 MB
3571
                                   str(disk.size))
3572
      exp_size = disk.size
3573

    
3574
  elif ieio == constants.IEIO_SCRIPT:
3575
    (disk, disk_index, ) = ieargs
3576

    
3577
    assert isinstance(disk_index, (int, long))
3578

    
3579
    real_disk = _OpenRealBD(disk)
3580

    
3581
    inst_os = OSFromDisk(instance.os)
3582
    env = OSEnvironment(instance, inst_os)
3583

    
3584
    if mode == constants.IEM_IMPORT:
3585
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3586
      env["IMPORT_INDEX"] = str(disk_index)
3587
      script = inst_os.import_script
3588

    
3589
    elif mode == constants.IEM_EXPORT:
3590
      env["EXPORT_DEVICE"] = real_disk.dev_path
3591
      env["EXPORT_INDEX"] = str(disk_index)
3592
      script = inst_os.export_script
3593

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

    
3597
    if mode == constants.IEM_IMPORT:
3598
      suffix = "| %s" % script_cmd
3599

    
3600
    elif mode == constants.IEM_EXPORT:
3601
      prefix = "%s |" % script_cmd
3602

    
3603
    # Let script predict size
3604
    exp_size = constants.IE_CUSTOM_SIZE
3605

    
3606
  else:
3607
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3608

    
3609
  return (env, prefix, suffix, exp_size)
3610

    
3611

    
3612
def _CreateImportExportStatusDir(prefix):
3613
  """Creates status directory for import/export.
3614

3615
  """
3616
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3617
                          prefix=("%s-%s-" %
3618
                                  (prefix, utils.TimestampForFilename())))
3619

    
3620

    
3621
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3622
                            ieio, ieioargs):
3623
  """Starts an import or export daemon.
3624

3625
  @param mode: Import/output mode
3626
  @type opts: L{objects.ImportExportOptions}
3627
  @param opts: Daemon options
3628
  @type host: string
3629
  @param host: Remote host for export (None for import)
3630
  @type port: int
3631
  @param port: Remote port for export (None for import)
3632
  @type instance: L{objects.Instance}
3633
  @param instance: Instance object
3634
  @type component: string
3635
  @param component: which part of the instance is transferred now,
3636
      e.g. 'disk/0'
3637
  @param ieio: Input/output type
3638
  @param ieioargs: Input/output arguments
3639

3640
  """
3641
  if mode == constants.IEM_IMPORT:
3642
    prefix = "import"
3643

    
3644
    if not (host is None and port is None):
3645
      _Fail("Can not specify host or port on import")
3646

    
3647
  elif mode == constants.IEM_EXPORT:
3648
    prefix = "export"
3649

    
3650
    if host is None or port is None:
3651
      _Fail("Host and port must be specified for an export")
3652

    
3653
  else:
3654
    _Fail("Invalid mode %r", mode)
3655

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

    
3659
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3660
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3661

    
3662
  if opts.key_name is None:
3663
    # Use server.pem
3664
    key_path = pathutils.NODED_CERT_FILE
3665
    cert_path = pathutils.NODED_CERT_FILE
3666
    assert opts.ca_pem is None
3667
  else:
3668
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3669
                                                 opts.key_name)
3670
    assert opts.ca_pem is not None
3671

    
3672
  for i in [key_path, cert_path]:
3673
    if not os.path.exists(i):
3674
      _Fail("File '%s' does not exist" % i)
3675

    
3676
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3677
  try:
3678
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3679
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3680
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3681

    
3682
    if opts.ca_pem is None:
3683
      # Use server.pem
3684
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3685
    else:
3686
      ca = opts.ca_pem
3687

    
3688
    # Write CA file
3689
    utils.WriteFile(ca_file, data=ca, mode=0400)
3690

    
3691
    cmd = [
3692
      pathutils.IMPORT_EXPORT_DAEMON,
3693
      status_file, mode,
3694
      "--key=%s" % key_path,
3695
      "--cert=%s" % cert_path,
3696
      "--ca=%s" % ca_file,
3697
      ]
3698

    
3699
    if host:
3700
      cmd.append("--host=%s" % host)
3701

    
3702
    if port:
3703
      cmd.append("--port=%s" % port)
3704

    
3705
    if opts.ipv6:
3706
      cmd.append("--ipv6")
3707
    else:
3708
      cmd.append("--ipv4")
3709

    
3710
    if opts.compress:
3711
      cmd.append("--compress=%s" % opts.compress)
3712

    
3713
    if opts.magic:
3714
      cmd.append("--magic=%s" % opts.magic)
3715

    
3716
    if exp_size is not None:
3717
      cmd.append("--expected-size=%s" % exp_size)
3718

    
3719
    if cmd_prefix:
3720
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3721

    
3722
    if cmd_suffix:
3723
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3724

    
3725
    if mode == constants.IEM_EXPORT:
3726
      # Retry connection a few times when connecting to remote peer
3727
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3728
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3729
    elif opts.connect_timeout is not None:
3730
      assert mode == constants.IEM_IMPORT
3731
      # Overall timeout for establishing connection while listening
3732
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3733

    
3734
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3735

    
3736
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3737
    # support for receiving a file descriptor for output
3738
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3739
                      output=logfile)
3740

    
3741
    # The import/export name is simply the status directory name
3742
    return os.path.basename(status_dir)
3743

    
3744
  except Exception:
3745
    shutil.rmtree(status_dir, ignore_errors=True)
3746
    raise
3747

    
3748

    
3749
def GetImportExportStatus(names):
3750
  """Returns import/export daemon status.
3751

3752
  @type names: sequence
3753
  @param names: List of names
3754
  @rtype: List of dicts
3755
  @return: Returns a list of the state of each named import/export or None if a
3756
           status couldn't be read
3757

3758
  """
3759
  result = []
3760

    
3761
  for name in names:
3762
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3763
                                 _IES_STATUS_FILE)
3764

    
3765
    try:
3766
      data = utils.ReadFile(status_file)
3767
    except EnvironmentError, err:
3768
      if err.errno != errno.ENOENT:
3769
        raise
3770
      data = None
3771

    
3772
    if not data:
3773
      result.append(None)
3774
      continue
3775

    
3776
    result.append(serializer.LoadJson(data))
3777

    
3778
  return result
3779

    
3780

    
3781
def AbortImportExport(name):
3782
  """Sends SIGTERM to a running import/export daemon.
3783

3784
  """
3785
  logging.info("Abort import/export %s", name)
3786

    
3787
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3788
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3789

    
3790
  if pid:
3791
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3792
                 name, pid)
3793
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3794

    
3795

    
3796
def CleanupImportExport(name):
3797
  """Cleanup after an import or export.
3798

3799
  If the import/export daemon is still running it's killed. Afterwards the
3800
  whole status directory is removed.
3801

3802
  """
3803
  logging.info("Finalizing import/export %s", name)
3804

    
3805
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3806

    
3807
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3808

    
3809
  if pid:
3810
    logging.info("Import/export %s is still running with PID %s",
3811
                 name, pid)
3812
    utils.KillProcess(pid, waitpid=False)
3813

    
3814
  shutil.rmtree(status_dir, ignore_errors=True)
3815

    
3816

    
3817
def _FindDisks(target_node_uuid, nodes_ip, disks):
3818
  """Sets the physical ID on disks and returns the block devices.
3819

3820
  """
3821
  # set the correct physical ID
3822
  for cf in disks:
3823
    cf.SetPhysicalID(target_node_uuid, nodes_ip)
3824

    
3825
  bdevs = []
3826

    
3827
  for cf in disks:
3828
    rd = _RecursiveFindBD(cf)
3829
    if rd is None:
3830
      _Fail("Can't find device %s", cf)
3831
    bdevs.append(rd)
3832
  return bdevs
3833

    
3834

    
3835
def DrbdDisconnectNet(target_node_uuid, nodes_ip, disks):
3836
  """Disconnects the network on a list of drbd devices.
3837

3838
  """
3839
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3840

    
3841
  # disconnect disks
3842
  for rd in bdevs:
3843
    try:
3844
      rd.DisconnectNet()
3845
    except errors.BlockDeviceError, err:
3846
      _Fail("Can't change network configuration to standalone mode: %s",
3847
            err, exc=True)
3848

    
3849

    
3850
def DrbdAttachNet(target_node_uuid, nodes_ip, disks, instance_name,
3851
                  multimaster):
3852
  """Attaches the network on a list of drbd devices.
3853

3854
  """
3855
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3856

    
3857
  if multimaster:
3858
    for idx, rd in enumerate(bdevs):
3859
      try:
3860
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3861
      except EnvironmentError, err:
3862
        _Fail("Can't create symlink: %s", err)
3863
  # reconnect disks, switch to new master configuration and if
3864
  # needed primary mode
3865
  for rd in bdevs:
3866
    try:
3867
      rd.AttachNet(multimaster)
3868
    except errors.BlockDeviceError, err:
3869
      _Fail("Can't change network configuration: %s", err)
3870

    
3871
  # wait until the disks are connected; we need to retry the re-attach
3872
  # if the device becomes standalone, as this might happen if the one
3873
  # node disconnects and reconnects in a different mode before the
3874
  # other node reconnects; in this case, one or both of the nodes will
3875
  # decide it has wrong configuration and switch to standalone
3876

    
3877
  def _Attach():
3878
    all_connected = True
3879

    
3880
    for rd in bdevs:
3881
      stats = rd.GetProcStatus()
3882

    
3883
      all_connected = (all_connected and
3884
                       (stats.is_connected or stats.is_in_resync))
3885

    
3886
      if stats.is_standalone:
3887
        # peer had different config info and this node became
3888
        # standalone, even though this should not happen with the
3889
        # new staged way of changing disk configs
3890
        try:
3891
          rd.AttachNet(multimaster)
3892
        except errors.BlockDeviceError, err:
3893
          _Fail("Can't change network configuration: %s", err)
3894

    
3895
    if not all_connected:
3896
      raise utils.RetryAgain()
3897

    
3898
  try:
3899
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3900
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3901
  except utils.RetryTimeout:
3902
    _Fail("Timeout in disk reconnecting")
3903

    
3904
  if multimaster:
3905
    # change to primary mode
3906
    for rd in bdevs:
3907
      try:
3908
        rd.Open()
3909
      except errors.BlockDeviceError, err:
3910
        _Fail("Can't change to primary mode: %s", err)
3911

    
3912

    
3913
def DrbdWaitSync(target_node_uuid, nodes_ip, disks):
3914
  """Wait until DRBDs have synchronized.
3915

3916
  """
3917
  def _helper(rd):
3918
    stats = rd.GetProcStatus()
3919
    if not (stats.is_connected or stats.is_in_resync):
3920
      raise utils.RetryAgain()
3921
    return stats
3922

    
3923
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3924

    
3925
  min_resync = 100
3926
  alldone = True
3927
  for rd in bdevs:
3928
    try:
3929
      # poll each second for 15 seconds
3930
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3931
    except utils.RetryTimeout:
3932
      stats = rd.GetProcStatus()
3933
      # last check
3934
      if not (stats.is_connected or stats.is_in_resync):
3935
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3936
    alldone = alldone and (not stats.is_in_resync)
3937
    if stats.sync_percent is not None:
3938
      min_resync = min(min_resync, stats.sync_percent)
3939

    
3940
  return (alldone, min_resync)
3941

    
3942

    
3943
def GetDrbdUsermodeHelper():
3944
  """Returns DRBD usermode helper currently configured.
3945

3946
  """
3947
  try:
3948
    return drbd.DRBD8.GetUsermodeHelper()
3949
  except errors.BlockDeviceError, err:
3950
    _Fail(str(err))
3951

    
3952

    
3953
def PowercycleNode(hypervisor_type, hvparams=None):
3954
  """Hard-powercycle the node.
3955

3956
  Because we need to return first, and schedule the powercycle in the
3957
  background, we won't be able to report failures nicely.
3958

3959
  """
3960
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3961
  try:
3962
    pid = os.fork()
3963
  except OSError:
3964
    # if we can't fork, we'll pretend that we're in the child process
3965
    pid = 0
3966
  if pid > 0:
3967
    return "Reboot scheduled in 5 seconds"
3968
  # ensure the child is running on ram
3969
  try:
3970
    utils.Mlockall()
3971
  except Exception: # pylint: disable=W0703
3972
    pass
3973
  time.sleep(5)
3974
  hyper.PowercycleNode(hvparams=hvparams)
3975

    
3976

    
3977
def _VerifyRestrictedCmdName(cmd):
3978
  """Verifies a restricted command name.
3979

3980
  @type cmd: string
3981
  @param cmd: Command name
3982
  @rtype: tuple; (boolean, string or None)
3983
  @return: The tuple's first element is the status; if C{False}, the second
3984
    element is an error message string, otherwise it's C{None}
3985

3986
  """
3987
  if not cmd.strip():
3988
    return (False, "Missing command name")
3989

    
3990
  if os.path.basename(cmd) != cmd:
3991
    return (False, "Invalid command name")
3992

    
3993
  if not constants.EXT_PLUGIN_MASK.match(cmd):
3994
    return (False, "Command name contains forbidden characters")
3995

    
3996
  return (True, None)
3997

    
3998

    
3999
def _CommonRestrictedCmdCheck(path, owner):
4000
  """Common checks for restricted command file system directories and files.
4001

4002
  @type path: string
4003
  @param path: Path to check
4004
  @param owner: C{None} or tuple containing UID and GID
4005
  @rtype: tuple; (boolean, string or C{os.stat} result)
4006
  @return: The tuple's first element is the status; if C{False}, the second
4007
    element is an error message string, otherwise it's the result of C{os.stat}
4008

4009
  """
4010
  if owner is None:
4011
    # Default to root as owner
4012
    owner = (0, 0)
4013

    
4014
  try:
4015
    st = os.stat(path)
4016
  except EnvironmentError, err:
4017
    return (False, "Can't stat(2) '%s': %s" % (path, err))
4018

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

    
4022
  if (st.st_uid, st.st_gid) != owner:
4023
    (owner_uid, owner_gid) = owner
4024
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
4025

    
4026
  return (True, st)
4027

    
4028

    
4029
def _VerifyRestrictedCmdDirectory(path, _owner=None):
4030
  """Verifies restricted command directory.
4031

4032
  @type path: string
4033
  @param path: Path to check
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
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
4040

    
4041
  if not status:
4042
    return (False, value)
4043

    
4044
  if not stat.S_ISDIR(value.st_mode):
4045
    return (False, "Path '%s' is not a directory" % path)
4046

    
4047
  return (True, None)
4048

    
4049

    
4050
def _VerifyRestrictedCmd(path, cmd, _owner=None):
4051
  """Verifies a whole restricted command and returns its executable filename.
4052

4053
  @type path: string
4054
  @param path: Directory containing restricted commands
4055
  @type cmd: string
4056
  @param cmd: Command name
4057
  @rtype: tuple; (boolean, string)
4058
  @return: The tuple's first element is the status; if C{False}, the second
4059
    element is an error message string, otherwise the second element is the
4060
    absolute path to the executable
4061

4062
  """
4063
  executable = utils.PathJoin(path, cmd)
4064

    
4065
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
4066

    
4067
  if not status:
4068
    return (False, msg)
4069

    
4070
  if not utils.IsExecutable(executable):
4071
    return (False, "access(2) thinks '%s' can't be executed" % executable)
4072

    
4073
  return (True, executable)
4074

    
4075

    
4076
def _PrepareRestrictedCmd(path, cmd,
4077
                          _verify_dir=_VerifyRestrictedCmdDirectory,
4078
                          _verify_name=_VerifyRestrictedCmdName,
4079
                          _verify_cmd=_VerifyRestrictedCmd):
4080
  """Performs a number of tests on a restricted command.
4081

4082
  @type path: string
4083
  @param path: Directory containing restricted commands
4084
  @type cmd: string
4085
  @param cmd: Command name
4086
  @return: Same as L{_VerifyRestrictedCmd}
4087

4088
  """
4089
  # Verify the directory first
4090
  (status, msg) = _verify_dir(path)
4091
  if status:
4092
    # Check command if everything was alright
4093
    (status, msg) = _verify_name(cmd)
4094

    
4095
  if not status:
4096
    return (False, msg)
4097

    
4098
  # Check actual executable
4099
  return _verify_cmd(path, cmd)
4100

    
4101

    
4102
def RunRestrictedCmd(cmd,
4103
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
4104
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
4105
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
4106
                     _sleep_fn=time.sleep,
4107
                     _prepare_fn=_PrepareRestrictedCmd,
4108
                     _runcmd_fn=utils.RunCmd,
4109
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
4110
  """Executes a restricted command after performing strict tests.
4111

4112
  @type cmd: string
4113
  @param cmd: Command name
4114
  @rtype: string
4115
  @return: Command output
4116
  @raise RPCFail: In case of an error
4117

4118
  """
4119
  logging.info("Preparing to run restricted command '%s'", cmd)
4120

    
4121
  if not _enabled:
4122
    _Fail("Restricted commands disabled at configure time")
4123

    
4124
  lock = None
4125
  try:
4126
    cmdresult = None
4127
    try:
4128
      lock = utils.FileLock.Open(_lock_file)
4129
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
4130

    
4131
      (status, value) = _prepare_fn(_path, cmd)
4132

    
4133
      if status:
4134
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
4135
                               postfork_fn=lambda _: lock.Unlock())
4136
      else:
4137
        logging.error(value)
4138
    except Exception: # pylint: disable=W0703
4139
      # Keep original error in log
4140
      logging.exception("Caught exception")
4141

    
4142
    if cmdresult is None:
4143
      logging.info("Sleeping for %0.1f seconds before returning",
4144
                   _RCMD_INVALID_DELAY)
4145
      _sleep_fn(_RCMD_INVALID_DELAY)
4146

    
4147
      # Do not include original error message in returned error
4148
      _Fail("Executing command '%s' failed" % cmd)
4149
    elif cmdresult.failed or cmdresult.fail_reason:
4150
      _Fail("Restricted command '%s' failed: %s; output: %s",
4151
            cmd, cmdresult.fail_reason, cmdresult.output)
4152
    else:
4153
      return cmdresult.output
4154
  finally:
4155
    if lock is not None:
4156
      # Release lock at last
4157
      lock.Close()
4158
      lock = None
4159

    
4160

    
4161
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
4162
  """Creates or removes the watcher pause file.
4163

4164
  @type until: None or number
4165
  @param until: Unix timestamp saying until when the watcher shouldn't run
4166

4167
  """
4168
  if until is None:
4169
    logging.info("Received request to no longer pause watcher")
4170
    utils.RemoveFile(_filename)
4171
  else:
4172
    logging.info("Received request to pause watcher until %s", until)
4173

    
4174
    if not ht.TNumber(until):
4175
      _Fail("Duration must be numeric")
4176

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

    
4179

    
4180
class HooksRunner(object):
4181
  """Hook runner.
4182

4183
  This class is instantiated on the node side (ganeti-noded) and not
4184
  on the master side.
4185

4186
  """
4187
  def __init__(self, hooks_base_dir=None):
4188
    """Constructor for hooks runner.
4189

4190
    @type hooks_base_dir: str or None
4191
    @param hooks_base_dir: if not None, this overrides the
4192
        L{pathutils.HOOKS_BASE_DIR} (useful for unittests)
4193

4194
    """
4195
    if hooks_base_dir is None:
4196
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
4197
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
4198
    # constant
4199
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
4200

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

4204
    """
4205
    assert len(node_list) == 1
4206
    node = node_list[0]
4207
    _, myself = ssconf.GetMasterAndMyself()
4208
    assert node == myself
4209

    
4210
    results = self.RunHooks(hpath, phase, env)
4211

    
4212
    # Return values in the form expected by HooksMaster
4213
    return {node: (None, False, results)}
4214

    
4215
  def RunHooks(self, hpath, phase, env):
4216
    """Run the scripts in the hooks directory.
4217

4218
    @type hpath: str
4219
    @param hpath: the path to the hooks directory which
4220
        holds the scripts
4221
    @type phase: str
4222
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
4223
        L{constants.HOOKS_PHASE_POST}
4224
    @type env: dict
4225
    @param env: dictionary with the environment for the hook
4226
    @rtype: list
4227
    @return: list of 3-element tuples:
4228
      - script path
4229
      - script result, either L{constants.HKR_SUCCESS} or
4230
        L{constants.HKR_FAIL}
4231
      - output of the script
4232

4233
    @raise errors.ProgrammerError: for invalid input
4234
        parameters
4235

4236
    """
4237
    if phase == constants.HOOKS_PHASE_PRE:
4238
      suffix = "pre"
4239
    elif phase == constants.HOOKS_PHASE_POST:
4240
      suffix = "post"
4241
    else:
4242
      _Fail("Unknown hooks phase '%s'", phase)
4243

    
4244
    subdir = "%s-%s.d" % (hpath, suffix)
4245
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
4246

    
4247
    results = []
4248

    
4249
    if not os.path.isdir(dir_name):
4250
      # for non-existing/non-dirs, we simply exit instead of logging a
4251
      # warning at every operation
4252
      return results
4253

    
4254
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
4255

    
4256
    for (relname, relstatus, runresult) in runparts_results:
4257
      if relstatus == constants.RUNPARTS_SKIP:
4258
        rrval = constants.HKR_SKIP
4259
        output = ""
4260
      elif relstatus == constants.RUNPARTS_ERR:
4261
        rrval = constants.HKR_FAIL
4262
        output = "Hook script execution error: %s" % runresult
4263
      elif relstatus == constants.RUNPARTS_RUN:
4264
        if runresult.failed:
4265
          rrval = constants.HKR_FAIL
4266
        else:
4267
          rrval = constants.HKR_SUCCESS
4268
        output = utils.SafeEncode(runresult.output.strip())
4269
      results.append(("%s/%s" % (subdir, relname), rrval, output))
4270

    
4271
    return results
4272

    
4273

    
4274
class IAllocatorRunner(object):
4275
  """IAllocator runner.
4276

4277
  This class is instantiated on the node side (ganeti-noded) and not on
4278
  the master side.
4279

4280
  """
4281
  @staticmethod
4282
  def Run(name, idata):
4283
    """Run an iallocator script.
4284

4285
    @type name: str
4286
    @param name: the iallocator script name
4287
    @type idata: str
4288
    @param idata: the allocator input data
4289

4290
    @rtype: tuple
4291
    @return: two element tuple of:
4292
       - status
4293
       - either error message or stdout of allocator (for success)
4294

4295
    """
4296
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
4297
                                  os.path.isfile)
4298
    if alloc_script is None:
4299
      _Fail("iallocator module '%s' not found in the search path", name)
4300

    
4301
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
4302
    try:
4303
      os.write(fd, idata)
4304
      os.close(fd)
4305
      result = utils.RunCmd([alloc_script, fin_name])
4306
      if result.failed:
4307
        _Fail("iallocator module '%s' failed: %s, output '%s'",
4308
              name, result.fail_reason, result.output)
4309
    finally:
4310
      os.unlink(fin_name)
4311

    
4312
    return result.stdout
4313

    
4314

    
4315
class DevCacheManager(object):
4316
  """Simple class for managing a cache of block device information.
4317

4318
  """
4319
  _DEV_PREFIX = "/dev/"
4320
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4321

    
4322
  @classmethod
4323
  def _ConvertPath(cls, dev_path):
4324
    """Converts a /dev/name path to the cache file name.
4325

4326
    This replaces slashes with underscores and strips the /dev
4327
    prefix. It then returns the full path to the cache file.
4328

4329
    @type dev_path: str
4330
    @param dev_path: the C{/dev/} path name
4331
    @rtype: str
4332
    @return: the converted path name
4333

4334
    """
4335
    if dev_path.startswith(cls._DEV_PREFIX):
4336
      dev_path = dev_path[len(cls._DEV_PREFIX):]
4337
    dev_path = dev_path.replace("/", "_")
4338
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4339
    return fpath
4340

    
4341
  @classmethod
4342
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4343
    """Updates the cache information for a given device.
4344

4345
    @type dev_path: str
4346
    @param dev_path: the pathname of the device
4347
    @type owner: str
4348
    @param owner: the owner (instance name) of the device
4349
    @type on_primary: bool
4350
    @param on_primary: whether this is the primary
4351
        node nor not
4352
    @type iv_name: str
4353
    @param iv_name: the instance-visible name of the
4354
        device, as in objects.Disk.iv_name
4355

4356
    @rtype: None
4357

4358
    """
4359
    if dev_path is None:
4360
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
4361
      return
4362
    fpath = cls._ConvertPath(dev_path)
4363
    if on_primary:
4364
      state = "primary"
4365
    else:
4366
      state = "secondary"
4367
    if iv_name is None:
4368
      iv_name = "not_visible"
4369
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4370
    try:
4371
      utils.WriteFile(fpath, data=fdata)
4372
    except EnvironmentError, err:
4373
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4374

    
4375
  @classmethod
4376
  def RemoveCache(cls, dev_path):
4377
    """Remove data for a dev_path.
4378

4379
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
4380
    path name and logging.
4381

4382
    @type dev_path: str
4383
    @param dev_path: the pathname of the device
4384

4385
    @rtype: None
4386

4387
    """
4388
    if dev_path is None:
4389
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
4390
      return
4391
    fpath = cls._ConvertPath(dev_path)
4392
    try:
4393
      utils.RemoveFile(fpath)
4394
    except EnvironmentError, err:
4395
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)