Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 2bff1928

History | View | Annotate | Download (129.4 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Google Inc.
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful, but
12
# WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
# General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19
# 02110-1301, USA.
20

    
21

    
22
"""Functions used by the node daemon
23

24
@var _ALLOWED_UPLOAD_FILES: denotes which files are accepted in
25
     the L{UploadFile} function
26
@var _ALLOWED_CLEAN_DIRS: denotes which directories are accepted
27
     in the L{_CleanDirectory} function
28

29
"""
30

    
31
# pylint: disable=E1103
32

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

    
37

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

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

    
72

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

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

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

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

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

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

    
107

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

111
  Its argument is the error message.
112

113
  """
114

    
115

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

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

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

    
127

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

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

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

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

    
143

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

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

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

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

    
166

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

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

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

    
176

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

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

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

    
189

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

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

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

    
209

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

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

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

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

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

    
239

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

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

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

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

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

    
266
  return frozenset(allowed_files)
267

    
268

    
269
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
270

    
271

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

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

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

    
282

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

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

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

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

    
307

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

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

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

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

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

    
339
      return result
340
    return wrapper
341
  return decorator
342

    
343

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

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

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

    
364
  return env
365

    
366

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

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

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

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

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

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

    
395

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

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

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

    
412

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

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

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

423
  """
424

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

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

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

    
440

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

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

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

    
457

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

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

463
  @rtype: None
464

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

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

    
475

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

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

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

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

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

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

    
506

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

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

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

    
528

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

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

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

539
  @param modify_ssh_setup: boolean
540

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

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

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

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

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

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

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

    
574

    
575
def _GetVgInfo(name, excl_stor):
576
  """Retrieves information about a LVM volume group.
577

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

    
588
  return {
589
    "name": name,
590
    "vg_free": vg_free,
591
    "vg_size": vg_size,
592
    }
593

    
594

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

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

606
  """
607
  if excl_stor:
608
    (vg_free, vg_size) = bdev.LogicalVolume.GetVgSpindlesInfo(name)
609
  else:
610
    vg_free = 0
611
    vg_size = 0
612
  return {
613
    "name": name,
614
    "vg_free": vg_free,
615
    "vg_size": vg_size,
616
    }
617

    
618

    
619
def _GetHvInfo(name):
620
  """Retrieves node information from a hypervisor.
621

622
  The information returned depends on the hypervisor. Common items:
623

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

631
  """
632
  return hypervisor.GetHypervisor(name).GetNodeInfo()
633

    
634

    
635
def _GetNamedNodeInfo(names, fn):
636
  """Calls C{fn} for all names in C{names} and returns a dictionary.
637

638
  @rtype: None or dict
639

640
  """
641
  if names is None:
642
    return None
643
  else:
644
    return map(fn, names)
645

    
646

    
647
def GetNodeInfo(storage_units, hv_names, excl_stor):
648
  """Gives back a hash with different information about the node.
649

650
  @type storage_units: list of pairs (string, string)
651
  @param storage_units: List of pairs (storage unit, identifier) to ask for disk
652
                        space information. In case of lvm-vg, the identifier is
653
                        the VG name.
654
  @type hv_names: list of string
655
  @param hv_names: Names of the hypervisors to ask for node information
656
  @type excl_stor: boolean
657
  @param excl_stor: Whether exclusive_storage is active
658
  @rtype: tuple; (string, None/dict, None/dict)
659
  @return: Tuple containing boot ID, volume group information and hypervisor
660
    information
661

662
  """
663
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
664
  storage_info = _GetNamedNodeInfo(
665
    storage_units,
666
    (lambda storage_unit: _ApplyStorageInfoFunction(storage_unit[0],
667
                                                    storage_unit[1],
668
                                                    excl_stor)))
669
  hv_info = _GetNamedNodeInfo(hv_names, _GetHvInfo)
670

    
671
  return (bootid, storage_info, hv_info)
672

    
673

    
674
# FIXME: implement storage reporting for all missing storage types.
675
_STORAGE_TYPE_INFO_FN = {
676
  constants.ST_BLOCK: None,
677
  constants.ST_DISKLESS: None,
678
  constants.ST_EXT: None,
679
  constants.ST_FILE: None,
680
  constants.ST_LVM_PV: _GetVgSpindlesInfo,
681
  constants.ST_LVM_VG: _GetVgInfo,
682
  constants.ST_RADOS: None,
683
}
684

    
685

    
686
def _ApplyStorageInfoFunction(storage_type, storage_key, *args):
687
  """Looks up and applies the correct function to calculate free and total
688
  storage for the given storage type.
689

690
  @type storage_type: string
691
  @param storage_type: the storage type for which the storage shall be reported.
692
  @type storage_key: string
693
  @param storage_key: identifier of a storage unit, e.g. the volume group name
694
    of an LVM storage unit
695
  @type args: any
696
  @param args: various parameters that can be used for storage reporting. These
697
    parameters and their semantics vary from storage type to storage type and
698
    are just propagated in this function.
699
  @return: the results of the application of the storage space function (see
700
    _STORAGE_TYPE_INFO_FN) if storage space reporting is implemented for that
701
    storage type
702
  @raises NotImplementedError: for storage types who don't support space
703
    reporting yet
704
  """
705
  fn = _STORAGE_TYPE_INFO_FN[storage_type]
706
  if fn is not None:
707
    return fn(storage_key, *args)
708
  else:
709
    raise NotImplementedError
710

    
711

    
712
def _CheckExclusivePvs(pvi_list):
713
  """Check that PVs are not shared among LVs
714

715
  @type pvi_list: list of L{objects.LvmPvInfo} objects
716
  @param pvi_list: information about the PVs
717

718
  @rtype: list of tuples (string, list of strings)
719
  @return: offending volumes, as tuples: (pv_name, [lv1_name, lv2_name...])
720

721
  """
722
  res = []
723
  for pvi in pvi_list:
724
    if len(pvi.lv_list) > 1:
725
      res.append((pvi.name, pvi.lv_list))
726
  return res
727

    
728

    
729
def VerifyNode(what, cluster_name):
730
  """Verify the status of the local node.
731

732
  Based on the input L{what} parameter, various checks are done on the
733
  local node.
734

735
  If the I{filelist} key is present, this list of
736
  files is checksummed and the file/checksum pairs are returned.
737

738
  If the I{nodelist} key is present, we check that we have
739
  connectivity via ssh with the target nodes (and check the hostname
740
  report).
741

742
  If the I{node-net-test} key is present, we check that we have
743
  connectivity to the given nodes via both primary IP and, if
744
  applicable, secondary IPs.
745

746
  @type what: C{dict}
747
  @param what: a dictionary of things to check:
748
      - filelist: list of files for which to compute checksums
749
      - nodelist: list of nodes we should check ssh communication with
750
      - node-net-test: list of nodes we should check node daemon port
751
        connectivity with
752
      - hypervisor: list with hypervisors to run the verify for
753
  @rtype: dict
754
  @return: a dictionary with the same keys as the input dict, and
755
      values representing the result of the checks
756

757
  """
758
  result = {}
759
  my_name = netutils.Hostname.GetSysName()
760
  port = netutils.GetDaemonPort(constants.NODED)
761
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
762

    
763
  if constants.NV_HYPERVISOR in what and vm_capable:
764
    result[constants.NV_HYPERVISOR] = tmp = {}
765
    for hv_name in what[constants.NV_HYPERVISOR]:
766
      try:
767
        val = hypervisor.GetHypervisor(hv_name).Verify()
768
      except errors.HypervisorError, err:
769
        val = "Error while checking hypervisor: %s" % str(err)
770
      tmp[hv_name] = val
771

    
772
  if constants.NV_HVPARAMS in what and vm_capable:
773
    result[constants.NV_HVPARAMS] = tmp = []
774
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
775
      try:
776
        logging.info("Validating hv %s, %s", hv_name, hvparms)
777
        hypervisor.GetHypervisor(hv_name).ValidateParameters(hvparms)
778
      except errors.HypervisorError, err:
779
        tmp.append((source, hv_name, str(err)))
780

    
781
  if constants.NV_FILELIST in what:
782
    fingerprints = utils.FingerprintFiles(map(vcluster.LocalizeVirtualPath,
783
                                              what[constants.NV_FILELIST]))
784
    result[constants.NV_FILELIST] = \
785
      dict((vcluster.MakeVirtualPath(key), value)
786
           for (key, value) in fingerprints.items())
787

    
788
  if constants.NV_NODELIST in what:
789
    (nodes, bynode) = what[constants.NV_NODELIST]
790

    
791
    # Add nodes from other groups (different for each node)
792
    try:
793
      nodes.extend(bynode[my_name])
794
    except KeyError:
795
      pass
796

    
797
    # Use a random order
798
    random.shuffle(nodes)
799

    
800
    # Try to contact all nodes
801
    val = {}
802
    for node in nodes:
803
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
804
      if not success:
805
        val[node] = message
806

    
807
    result[constants.NV_NODELIST] = val
808

    
809
  if constants.NV_NODENETTEST in what:
810
    result[constants.NV_NODENETTEST] = tmp = {}
811
    my_pip = my_sip = None
812
    for name, pip, sip in what[constants.NV_NODENETTEST]:
813
      if name == my_name:
814
        my_pip = pip
815
        my_sip = sip
816
        break
817
    if not my_pip:
818
      tmp[my_name] = ("Can't find my own primary/secondary IP"
819
                      " in the node list")
820
    else:
821
      for name, pip, sip in what[constants.NV_NODENETTEST]:
822
        fail = []
823
        if not netutils.TcpPing(pip, port, source=my_pip):
824
          fail.append("primary")
825
        if sip != pip:
826
          if not netutils.TcpPing(sip, port, source=my_sip):
827
            fail.append("secondary")
828
        if fail:
829
          tmp[name] = ("failure using the %s interface(s)" %
830
                       " and ".join(fail))
831

    
832
  if constants.NV_MASTERIP in what:
833
    # FIXME: add checks on incoming data structures (here and in the
834
    # rest of the function)
835
    master_name, master_ip = what[constants.NV_MASTERIP]
836
    if master_name == my_name:
837
      source = constants.IP4_ADDRESS_LOCALHOST
838
    else:
839
      source = None
840
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
841
                                                     source=source)
842

    
843
  if constants.NV_USERSCRIPTS in what:
844
    result[constants.NV_USERSCRIPTS] = \
845
      [script for script in what[constants.NV_USERSCRIPTS]
846
       if not utils.IsExecutable(script)]
847

    
848
  if constants.NV_OOB_PATHS in what:
849
    result[constants.NV_OOB_PATHS] = tmp = []
850
    for path in what[constants.NV_OOB_PATHS]:
851
      try:
852
        st = os.stat(path)
853
      except OSError, err:
854
        tmp.append("error stating out of band helper: %s" % err)
855
      else:
856
        if stat.S_ISREG(st.st_mode):
857
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
858
            tmp.append(None)
859
          else:
860
            tmp.append("out of band helper %s is not executable" % path)
861
        else:
862
          tmp.append("out of band helper %s is not a file" % path)
863

    
864
  if constants.NV_LVLIST in what and vm_capable:
865
    try:
866
      val = GetVolumeList(utils.ListVolumeGroups().keys())
867
    except RPCFail, err:
868
      val = str(err)
869
    result[constants.NV_LVLIST] = val
870

    
871
  if constants.NV_INSTANCELIST in what and vm_capable:
872
    # GetInstanceList can fail
873
    try:
874
      val = GetInstanceList(what[constants.NV_INSTANCELIST])
875
    except RPCFail, err:
876
      val = str(err)
877
    result[constants.NV_INSTANCELIST] = val
878

    
879
  if constants.NV_VGLIST in what and vm_capable:
880
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
881

    
882
  if constants.NV_PVLIST in what and vm_capable:
883
    check_exclusive_pvs = constants.NV_EXCLUSIVEPVS in what
884
    val = bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
885
                                       filter_allocatable=False,
886
                                       include_lvs=check_exclusive_pvs)
887
    if check_exclusive_pvs:
888
      result[constants.NV_EXCLUSIVEPVS] = _CheckExclusivePvs(val)
889
      for pvi in val:
890
        # Avoid sending useless data on the wire
891
        pvi.lv_list = []
892
    result[constants.NV_PVLIST] = map(objects.LvmPvInfo.ToDict, val)
893

    
894
  if constants.NV_VERSION in what:
895
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
896
                                    constants.RELEASE_VERSION)
897

    
898
  if constants.NV_HVINFO in what and vm_capable:
899
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
900
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
901

    
902
  if constants.NV_DRBDVERSION in what and vm_capable:
903
    try:
904
      drbd_version = DRBD8.GetProcInfo().GetVersionString()
905
    except errors.BlockDeviceError, err:
906
      logging.warning("Can't get DRBD version", exc_info=True)
907
      drbd_version = str(err)
908
    result[constants.NV_DRBDVERSION] = drbd_version
909

    
910
  if constants.NV_DRBDLIST in what and vm_capable:
911
    try:
912
      used_minors = drbd.DRBD8.GetUsedDevs()
913
    except errors.BlockDeviceError, err:
914
      logging.warning("Can't get used minors list", exc_info=True)
915
      used_minors = str(err)
916
    result[constants.NV_DRBDLIST] = used_minors
917

    
918
  if constants.NV_DRBDHELPER in what and vm_capable:
919
    status = True
920
    try:
921
      payload = drbd.DRBD8.GetUsermodeHelper()
922
    except errors.BlockDeviceError, err:
923
      logging.error("Can't get DRBD usermode helper: %s", str(err))
924
      status = False
925
      payload = str(err)
926
    result[constants.NV_DRBDHELPER] = (status, payload)
927

    
928
  if constants.NV_NODESETUP in what:
929
    result[constants.NV_NODESETUP] = tmpr = []
930
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
931
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
932
                  " under /sys, missing required directories /sys/block"
933
                  " and /sys/class/net")
934
    if (not os.path.isdir("/proc/sys") or
935
        not os.path.isfile("/proc/sysrq-trigger")):
936
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
937
                  " under /proc, missing required directory /proc/sys and"
938
                  " the file /proc/sysrq-trigger")
939

    
940
  if constants.NV_TIME in what:
941
    result[constants.NV_TIME] = utils.SplitTime(time.time())
942

    
943
  if constants.NV_OSLIST in what and vm_capable:
944
    result[constants.NV_OSLIST] = DiagnoseOS()
945

    
946
  if constants.NV_BRIDGES in what and vm_capable:
947
    result[constants.NV_BRIDGES] = [bridge
948
                                    for bridge in what[constants.NV_BRIDGES]
949
                                    if not utils.BridgeExists(bridge)]
950

    
951
  if what.get(constants.NV_FILE_STORAGE_PATHS) == my_name:
952
    result[constants.NV_FILE_STORAGE_PATHS] = \
953
      bdev.ComputeWrongFileStoragePaths()
954

    
955
  return result
956

    
957

    
958
def GetBlockDevSizes(devices):
959
  """Return the size of the given block devices
960

961
  @type devices: list
962
  @param devices: list of block device nodes to query
963
  @rtype: dict
964
  @return:
965
    dictionary of all block devices under /dev (key). The value is their
966
    size in MiB.
967

968
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
969

970
  """
971
  DEV_PREFIX = "/dev/"
972
  blockdevs = {}
973

    
974
  for devpath in devices:
975
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
976
      continue
977

    
978
    try:
979
      st = os.stat(devpath)
980
    except EnvironmentError, err:
981
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
982
      continue
983

    
984
    if stat.S_ISBLK(st.st_mode):
985
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
986
      if result.failed:
987
        # We don't want to fail, just do not list this device as available
988
        logging.warning("Cannot get size for block device %s", devpath)
989
        continue
990

    
991
      size = int(result.stdout) / (1024 * 1024)
992
      blockdevs[devpath] = size
993
  return blockdevs
994

    
995

    
996
def GetVolumeList(vg_names):
997
  """Compute list of logical volumes and their size.
998

999
  @type vg_names: list
1000
  @param vg_names: the volume groups whose LVs we should list, or
1001
      empty for all volume groups
1002
  @rtype: dict
1003
  @return:
1004
      dictionary of all partions (key) with value being a tuple of
1005
      their size (in MiB), inactive and online status::
1006

1007
        {'xenvg/test1': ('20.06', True, True)}
1008

1009
      in case of errors, a string is returned with the error
1010
      details.
1011

1012
  """
1013
  lvs = {}
1014
  sep = "|"
1015
  if not vg_names:
1016
    vg_names = []
1017
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1018
                         "--separator=%s" % sep,
1019
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
1020
  if result.failed:
1021
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
1022

    
1023
  for line in result.stdout.splitlines():
1024
    line = line.strip()
1025
    match = _LVSLINE_REGEX.match(line)
1026
    if not match:
1027
      logging.error("Invalid line returned from lvs output: '%s'", line)
1028
      continue
1029
    vg_name, name, size, attr = match.groups()
1030
    inactive = attr[4] == "-"
1031
    online = attr[5] == "o"
1032
    virtual = attr[0] == "v"
1033
    if virtual:
1034
      # we don't want to report such volumes as existing, since they
1035
      # don't really hold data
1036
      continue
1037
    lvs[vg_name + "/" + name] = (size, inactive, online)
1038

    
1039
  return lvs
1040

    
1041

    
1042
def ListVolumeGroups():
1043
  """List the volume groups and their size.
1044

1045
  @rtype: dict
1046
  @return: dictionary with keys volume name and values the
1047
      size of the volume
1048

1049
  """
1050
  return utils.ListVolumeGroups()
1051

    
1052

    
1053
def NodeVolumes():
1054
  """List all volumes on this node.
1055

1056
  @rtype: list
1057
  @return:
1058
    A list of dictionaries, each having four keys:
1059
      - name: the logical volume name,
1060
      - size: the size of the logical volume
1061
      - dev: the physical device on which the LV lives
1062
      - vg: the volume group to which it belongs
1063

1064
    In case of errors, we return an empty list and log the
1065
    error.
1066

1067
    Note that since a logical volume can live on multiple physical
1068
    volumes, the resulting list might include a logical volume
1069
    multiple times.
1070

1071
  """
1072
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1073
                         "--separator=|",
1074
                         "--options=lv_name,lv_size,devices,vg_name"])
1075
  if result.failed:
1076
    _Fail("Failed to list logical volumes, lvs output: %s",
1077
          result.output)
1078

    
1079
  def parse_dev(dev):
1080
    return dev.split("(")[0]
1081

    
1082
  def handle_dev(dev):
1083
    return [parse_dev(x) for x in dev.split(",")]
1084

    
1085
  def map_line(line):
1086
    line = [v.strip() for v in line]
1087
    return [{"name": line[0], "size": line[1],
1088
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
1089

    
1090
  all_devs = []
1091
  for line in result.stdout.splitlines():
1092
    if line.count("|") >= 3:
1093
      all_devs.extend(map_line(line.split("|")))
1094
    else:
1095
      logging.warning("Strange line in the output from lvs: '%s'", line)
1096
  return all_devs
1097

    
1098

    
1099
def BridgesExist(bridges_list):
1100
  """Check if a list of bridges exist on the current node.
1101

1102
  @rtype: boolean
1103
  @return: C{True} if all of them exist, C{False} otherwise
1104

1105
  """
1106
  missing = []
1107
  for bridge in bridges_list:
1108
    if not utils.BridgeExists(bridge):
1109
      missing.append(bridge)
1110

    
1111
  if missing:
1112
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
1113

    
1114

    
1115
def GetInstanceListForHypervisor(hname, hvparams=None,
1116
                                 get_hv_fn=hypervisor.GetHypervisor):
1117
  """Provides a list of instances of the given hypervisor.
1118

1119
  @type hname: string
1120
  @param hname: name of the hypervisor
1121
  @type hvparams: dict of strings
1122
  @param hvparams: hypervisor parameters for the given hypervisor
1123
  @type get_hv_fn: function
1124
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1125
    name; optional parameter to increase testability
1126

1127
  @rtype: list
1128
  @return: a list of all running instances on the current node
1129
    - instance1.example.com
1130
    - instance2.example.com
1131

1132
  """
1133
  results = []
1134
  try:
1135
    hv = get_hv_fn(hname)
1136
    names = hv.ListInstances(hvparams)
1137
    results.extend(names)
1138
  except errors.HypervisorError, err:
1139
    _Fail("Error enumerating instances (hypervisor %s): %s",
1140
          hname, err, exc=True)
1141
  return results
1142

    
1143

    
1144
def GetInstanceList(hypervisor_list, all_hvparams=None,
1145
                    get_hv_fn=hypervisor.GetHypervisor):
1146
  """Provides a list of instances.
1147

1148
  @type hypervisor_list: list
1149
  @param hypervisor_list: the list of hypervisors to query information
1150
  @type all_hvparams: dict of dict of strings
1151
  @param all_hvparams: a dictionary mapping hypervisor types to respective
1152
    cluster-wide hypervisor parameters
1153
  @type get_hv_fn: function
1154
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1155
    name; optional parameter to increase testability
1156

1157
  @rtype: list
1158
  @return: a list of all running instances on the current node
1159
    - instance1.example.com
1160
    - instance2.example.com
1161

1162
  """
1163
  results = []
1164
  for hname in hypervisor_list:
1165
    hvparams = None
1166
    if all_hvparams is not None:
1167
      hvparams = all_hvparams[hname]
1168
    results.extend(GetInstanceListForHypervisor(hname, hvparams,
1169
                                                get_hv_fn=get_hv_fn))
1170
  return results
1171

    
1172

    
1173
def GetInstanceInfo(instance, hname):
1174
  """Gives back the information about an instance as a dictionary.
1175

1176
  @type instance: string
1177
  @param instance: the instance name
1178
  @type hname: string
1179
  @param hname: the hypervisor type of the instance
1180

1181
  @rtype: dict
1182
  @return: dictionary with the following keys:
1183
      - memory: memory size of instance (int)
1184
      - state: xen state of instance (string)
1185
      - time: cpu time of instance (float)
1186
      - vcpus: the number of vcpus (int)
1187

1188
  """
1189
  output = {}
1190

    
1191
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
1192
  if iinfo is not None:
1193
    output["memory"] = iinfo[2]
1194
    output["vcpus"] = iinfo[3]
1195
    output["state"] = iinfo[4]
1196
    output["time"] = iinfo[5]
1197

    
1198
  return output
1199

    
1200

    
1201
def GetInstanceMigratable(instance):
1202
  """Gives whether an instance can be migrated.
1203

1204
  @type instance: L{objects.Instance}
1205
  @param instance: object representing the instance to be checked.
1206

1207
  @rtype: tuple
1208
  @return: tuple of (result, description) where:
1209
      - result: whether the instance can be migrated or not
1210
      - description: a description of the issue, if relevant
1211

1212
  """
1213
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1214
  iname = instance.name
1215
  if iname not in hyper.ListInstances():
1216
    _Fail("Instance %s is not running", iname)
1217

    
1218
  for idx in range(len(instance.disks)):
1219
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1220
    if not os.path.islink(link_name):
1221
      logging.warning("Instance %s is missing symlink %s for disk %d",
1222
                      iname, link_name, idx)
1223

    
1224

    
1225
def GetAllInstancesInfo(hypervisor_list):
1226
  """Gather data about all instances.
1227

1228
  This is the equivalent of L{GetInstanceInfo}, except that it
1229
  computes data for all instances at once, thus being faster if one
1230
  needs data about more than one instance.
1231

1232
  @type hypervisor_list: list
1233
  @param hypervisor_list: list of hypervisors to query for instance data
1234

1235
  @rtype: dict
1236
  @return: dictionary of instance: data, with data having the following keys:
1237
      - memory: memory size of instance (int)
1238
      - state: xen state of instance (string)
1239
      - time: cpu time of instance (float)
1240
      - vcpus: the number of vcpus
1241

1242
  """
1243
  output = {}
1244

    
1245
  for hname in hypervisor_list:
1246
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
1247
    if iinfo:
1248
      for name, _, memory, vcpus, state, times in iinfo:
1249
        value = {
1250
          "memory": memory,
1251
          "vcpus": vcpus,
1252
          "state": state,
1253
          "time": times,
1254
          }
1255
        if name in output:
1256
          # we only check static parameters, like memory and vcpus,
1257
          # and not state and time which can change between the
1258
          # invocations of the different hypervisors
1259
          for key in "memory", "vcpus":
1260
            if value[key] != output[name][key]:
1261
              _Fail("Instance %s is running twice"
1262
                    " with different parameters", name)
1263
        output[name] = value
1264

    
1265
  return output
1266

    
1267

    
1268
def _InstanceLogName(kind, os_name, instance, component):
1269
  """Compute the OS log filename for a given instance and operation.
1270

1271
  The instance name and os name are passed in as strings since not all
1272
  operations have these as part of an instance object.
1273

1274
  @type kind: string
1275
  @param kind: the operation type (e.g. add, import, etc.)
1276
  @type os_name: string
1277
  @param os_name: the os name
1278
  @type instance: string
1279
  @param instance: the name of the instance being imported/added/etc.
1280
  @type component: string or None
1281
  @param component: the name of the component of the instance being
1282
      transferred
1283

1284
  """
1285
  # TODO: Use tempfile.mkstemp to create unique filename
1286
  if component:
1287
    assert "/" not in component
1288
    c_msg = "-%s" % component
1289
  else:
1290
    c_msg = ""
1291
  base = ("%s-%s-%s%s-%s.log" %
1292
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1293
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1294

    
1295

    
1296
def InstanceOsAdd(instance, reinstall, debug):
1297
  """Add an OS to an instance.
1298

1299
  @type instance: L{objects.Instance}
1300
  @param instance: Instance whose OS is to be installed
1301
  @type reinstall: boolean
1302
  @param reinstall: whether this is an instance reinstall
1303
  @type debug: integer
1304
  @param debug: debug level, passed to the OS scripts
1305
  @rtype: None
1306

1307
  """
1308
  inst_os = OSFromDisk(instance.os)
1309

    
1310
  create_env = OSEnvironment(instance, inst_os, debug)
1311
  if reinstall:
1312
    create_env["INSTANCE_REINSTALL"] = "1"
1313

    
1314
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1315

    
1316
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1317
                        cwd=inst_os.path, output=logfile, reset_env=True)
1318
  if result.failed:
1319
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1320
                  " output: %s", result.cmd, result.fail_reason, logfile,
1321
                  result.output)
1322
    lines = [utils.SafeEncode(val)
1323
             for val in utils.TailFile(logfile, lines=20)]
1324
    _Fail("OS create script failed (%s), last lines in the"
1325
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1326

    
1327

    
1328
def RunRenameInstance(instance, old_name, debug):
1329
  """Run the OS rename script for an instance.
1330

1331
  @type instance: L{objects.Instance}
1332
  @param instance: Instance whose OS is to be installed
1333
  @type old_name: string
1334
  @param old_name: previous instance name
1335
  @type debug: integer
1336
  @param debug: debug level, passed to the OS scripts
1337
  @rtype: boolean
1338
  @return: the success of the operation
1339

1340
  """
1341
  inst_os = OSFromDisk(instance.os)
1342

    
1343
  rename_env = OSEnvironment(instance, inst_os, debug)
1344
  rename_env["OLD_INSTANCE_NAME"] = old_name
1345

    
1346
  logfile = _InstanceLogName("rename", instance.os,
1347
                             "%s-%s" % (old_name, instance.name), None)
1348

    
1349
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1350
                        cwd=inst_os.path, output=logfile, reset_env=True)
1351

    
1352
  if result.failed:
1353
    logging.error("os create command '%s' returned error: %s output: %s",
1354
                  result.cmd, result.fail_reason, result.output)
1355
    lines = [utils.SafeEncode(val)
1356
             for val in utils.TailFile(logfile, lines=20)]
1357
    _Fail("OS rename script failed (%s), last lines in the"
1358
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1359

    
1360

    
1361
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1362
  """Returns symlink path for block device.
1363

1364
  """
1365
  if _dir is None:
1366
    _dir = pathutils.DISK_LINKS_DIR
1367

    
1368
  return utils.PathJoin(_dir,
1369
                        ("%s%s%s" %
1370
                         (instance_name, constants.DISK_SEPARATOR, idx)))
1371

    
1372

    
1373
def _SymlinkBlockDev(instance_name, device_path, idx):
1374
  """Set up symlinks to a instance's block device.
1375

1376
  This is an auxiliary function run when an instance is start (on the primary
1377
  node) or when an instance is migrated (on the target node).
1378

1379

1380
  @param instance_name: the name of the target instance
1381
  @param device_path: path of the physical block device, on the node
1382
  @param idx: the disk index
1383
  @return: absolute path to the disk's symlink
1384

1385
  """
1386
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1387
  try:
1388
    os.symlink(device_path, link_name)
1389
  except OSError, err:
1390
    if err.errno == errno.EEXIST:
1391
      if (not os.path.islink(link_name) or
1392
          os.readlink(link_name) != device_path):
1393
        os.remove(link_name)
1394
        os.symlink(device_path, link_name)
1395
    else:
1396
      raise
1397

    
1398
  return link_name
1399

    
1400

    
1401
def _RemoveBlockDevLinks(instance_name, disks):
1402
  """Remove the block device symlinks belonging to the given instance.
1403

1404
  """
1405
  for idx, _ in enumerate(disks):
1406
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1407
    if os.path.islink(link_name):
1408
      try:
1409
        os.remove(link_name)
1410
      except OSError:
1411
        logging.exception("Can't remove symlink '%s'", link_name)
1412

    
1413

    
1414
def _GatherAndLinkBlockDevs(instance):
1415
  """Set up an instance's block device(s).
1416

1417
  This is run on the primary node at instance startup. The block
1418
  devices must be already assembled.
1419

1420
  @type instance: L{objects.Instance}
1421
  @param instance: the instance whose disks we shoul assemble
1422
  @rtype: list
1423
  @return: list of (disk_object, device_path)
1424

1425
  """
1426
  block_devices = []
1427
  for idx, disk in enumerate(instance.disks):
1428
    device = _RecursiveFindBD(disk)
1429
    if device is None:
1430
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1431
                                    str(disk))
1432
    device.Open()
1433
    try:
1434
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1435
    except OSError, e:
1436
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1437
                                    e.strerror)
1438

    
1439
    block_devices.append((disk, link_name))
1440

    
1441
  return block_devices
1442

    
1443

    
1444
def StartInstance(instance, startup_paused, reason, store_reason=True):
1445
  """Start an instance.
1446

1447
  @type instance: L{objects.Instance}
1448
  @param instance: the instance object
1449
  @type startup_paused: bool
1450
  @param instance: pause instance at startup?
1451
  @type reason: list of reasons
1452
  @param reason: the reason trail for this startup
1453
  @type store_reason: boolean
1454
  @param store_reason: whether to store the shutdown reason trail on file
1455
  @rtype: None
1456

1457
  """
1458
  running_instances = GetInstanceList([instance.hypervisor])
1459

    
1460
  if instance.name in running_instances:
1461
    logging.info("Instance %s already running, not starting", instance.name)
1462
    return
1463

    
1464
  try:
1465
    block_devices = _GatherAndLinkBlockDevs(instance)
1466
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1467
    hyper.StartInstance(instance, block_devices, startup_paused)
1468
    if store_reason:
1469
      _StoreInstReasonTrail(instance.name, reason)
1470
  except errors.BlockDeviceError, err:
1471
    _Fail("Block device error: %s", err, exc=True)
1472
  except errors.HypervisorError, err:
1473
    _RemoveBlockDevLinks(instance.name, instance.disks)
1474
    _Fail("Hypervisor error: %s", err, exc=True)
1475

    
1476

    
1477
def InstanceShutdown(instance, timeout, reason, store_reason=True):
1478
  """Shut an instance down.
1479

1480
  @note: this functions uses polling with a hardcoded timeout.
1481

1482
  @type instance: L{objects.Instance}
1483
  @param instance: the instance object
1484
  @type timeout: integer
1485
  @param timeout: maximum timeout for soft shutdown
1486
  @type reason: list of reasons
1487
  @param reason: the reason trail for this shutdown
1488
  @type store_reason: boolean
1489
  @param store_reason: whether to store the shutdown reason trail on file
1490
  @rtype: None
1491

1492
  """
1493
  hv_name = instance.hypervisor
1494
  hyper = hypervisor.GetHypervisor(hv_name)
1495
  iname = instance.name
1496

    
1497
  if instance.name not in hyper.ListInstances():
1498
    logging.info("Instance %s not running, doing nothing", iname)
1499
    return
1500

    
1501
  class _TryShutdown:
1502
    def __init__(self):
1503
      self.tried_once = False
1504

    
1505
    def __call__(self):
1506
      if iname not in hyper.ListInstances():
1507
        return
1508

    
1509
      try:
1510
        hyper.StopInstance(instance, retry=self.tried_once)
1511
        if store_reason:
1512
          _StoreInstReasonTrail(instance.name, reason)
1513
      except errors.HypervisorError, err:
1514
        if iname not in hyper.ListInstances():
1515
          # if the instance is no longer existing, consider this a
1516
          # success and go to cleanup
1517
          return
1518

    
1519
        _Fail("Failed to stop instance %s: %s", iname, err)
1520

    
1521
      self.tried_once = True
1522

    
1523
      raise utils.RetryAgain()
1524

    
1525
  try:
1526
    utils.Retry(_TryShutdown(), 5, timeout)
1527
  except utils.RetryTimeout:
1528
    # the shutdown did not succeed
1529
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1530

    
1531
    try:
1532
      hyper.StopInstance(instance, force=True)
1533
    except errors.HypervisorError, err:
1534
      if iname in hyper.ListInstances():
1535
        # only raise an error if the instance still exists, otherwise
1536
        # the error could simply be "instance ... unknown"!
1537
        _Fail("Failed to force stop instance %s: %s", iname, err)
1538

    
1539
    time.sleep(1)
1540

    
1541
    if iname in hyper.ListInstances():
1542
      _Fail("Could not shutdown instance %s even by destroy", iname)
1543

    
1544
  try:
1545
    hyper.CleanupInstance(instance.name)
1546
  except errors.HypervisorError, err:
1547
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1548

    
1549
  _RemoveBlockDevLinks(iname, instance.disks)
1550

    
1551

    
1552
def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1553
  """Reboot an instance.
1554

1555
  @type instance: L{objects.Instance}
1556
  @param instance: the instance object to reboot
1557
  @type reboot_type: str
1558
  @param reboot_type: the type of reboot, one the following
1559
    constants:
1560
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1561
        instance OS, do not recreate the VM
1562
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1563
        restart the VM (at the hypervisor level)
1564
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1565
        not accepted here, since that mode is handled differently, in
1566
        cmdlib, and translates into full stop and start of the
1567
        instance (instead of a call_instance_reboot RPC)
1568
  @type shutdown_timeout: integer
1569
  @param shutdown_timeout: maximum timeout for soft shutdown
1570
  @type reason: list of reasons
1571
  @param reason: the reason trail for this reboot
1572
  @rtype: None
1573

1574
  """
1575
  running_instances = GetInstanceList([instance.hypervisor])
1576

    
1577
  if instance.name not in running_instances:
1578
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1579

    
1580
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1581
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1582
    try:
1583
      hyper.RebootInstance(instance)
1584
    except errors.HypervisorError, err:
1585
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1586
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1587
    try:
1588
      InstanceShutdown(instance, shutdown_timeout, reason, store_reason=False)
1589
      result = StartInstance(instance, False, reason, store_reason=False)
1590
      _StoreInstReasonTrail(instance.name, reason)
1591
      return result
1592
    except errors.HypervisorError, err:
1593
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1594
  else:
1595
    _Fail("Invalid reboot_type received: %s", reboot_type)
1596

    
1597

    
1598
def InstanceBalloonMemory(instance, memory):
1599
  """Resize an instance's memory.
1600

1601
  @type instance: L{objects.Instance}
1602
  @param instance: the instance object
1603
  @type memory: int
1604
  @param memory: new memory amount in MB
1605
  @rtype: None
1606

1607
  """
1608
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1609
  running = hyper.ListInstances()
1610
  if instance.name not in running:
1611
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1612
    return
1613
  try:
1614
    hyper.BalloonInstanceMemory(instance, memory)
1615
  except errors.HypervisorError, err:
1616
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1617

    
1618

    
1619
def MigrationInfo(instance):
1620
  """Gather information about an instance to be migrated.
1621

1622
  @type instance: L{objects.Instance}
1623
  @param instance: the instance definition
1624

1625
  """
1626
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1627
  try:
1628
    info = hyper.MigrationInfo(instance)
1629
  except errors.HypervisorError, err:
1630
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1631
  return info
1632

    
1633

    
1634
def AcceptInstance(instance, info, target):
1635
  """Prepare the node to accept an instance.
1636

1637
  @type instance: L{objects.Instance}
1638
  @param instance: the instance definition
1639
  @type info: string/data (opaque)
1640
  @param info: migration information, from the source node
1641
  @type target: string
1642
  @param target: target host (usually ip), on this node
1643

1644
  """
1645
  # TODO: why is this required only for DTS_EXT_MIRROR?
1646
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1647
    # Create the symlinks, as the disks are not active
1648
    # in any way
1649
    try:
1650
      _GatherAndLinkBlockDevs(instance)
1651
    except errors.BlockDeviceError, err:
1652
      _Fail("Block device error: %s", err, exc=True)
1653

    
1654
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1655
  try:
1656
    hyper.AcceptInstance(instance, info, target)
1657
  except errors.HypervisorError, err:
1658
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1659
      _RemoveBlockDevLinks(instance.name, instance.disks)
1660
    _Fail("Failed to accept instance: %s", err, exc=True)
1661

    
1662

    
1663
def FinalizeMigrationDst(instance, info, success):
1664
  """Finalize any preparation to accept an instance.
1665

1666
  @type instance: L{objects.Instance}
1667
  @param instance: the instance definition
1668
  @type info: string/data (opaque)
1669
  @param info: migration information, from the source node
1670
  @type success: boolean
1671
  @param success: whether the migration was a success or a failure
1672

1673
  """
1674
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1675
  try:
1676
    hyper.FinalizeMigrationDst(instance, info, success)
1677
  except errors.HypervisorError, err:
1678
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1679

    
1680

    
1681
def MigrateInstance(instance, target, live):
1682
  """Migrates an instance to another node.
1683

1684
  @type instance: L{objects.Instance}
1685
  @param instance: the instance definition
1686
  @type target: string
1687
  @param target: the target node name
1688
  @type live: boolean
1689
  @param live: whether the migration should be done live or not (the
1690
      interpretation of this parameter is left to the hypervisor)
1691
  @raise RPCFail: if migration fails for some reason
1692

1693
  """
1694
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1695

    
1696
  try:
1697
    hyper.MigrateInstance(instance, target, live)
1698
  except errors.HypervisorError, err:
1699
    _Fail("Failed to migrate instance: %s", err, exc=True)
1700

    
1701

    
1702
def FinalizeMigrationSource(instance, success, live):
1703
  """Finalize the instance migration on the source node.
1704

1705
  @type instance: L{objects.Instance}
1706
  @param instance: the instance definition of the migrated instance
1707
  @type success: bool
1708
  @param success: whether the migration succeeded or not
1709
  @type live: bool
1710
  @param live: whether the user requested a live migration or not
1711
  @raise RPCFail: If the execution fails for some reason
1712

1713
  """
1714
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1715

    
1716
  try:
1717
    hyper.FinalizeMigrationSource(instance, success, live)
1718
  except Exception, err:  # pylint: disable=W0703
1719
    _Fail("Failed to finalize the migration on the source node: %s", err,
1720
          exc=True)
1721

    
1722

    
1723
def GetMigrationStatus(instance):
1724
  """Get the migration status
1725

1726
  @type instance: L{objects.Instance}
1727
  @param instance: the instance that is being migrated
1728
  @rtype: L{objects.MigrationStatus}
1729
  @return: the status of the current migration (one of
1730
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1731
           progress info that can be retrieved from the hypervisor
1732
  @raise RPCFail: If the migration status cannot be retrieved
1733

1734
  """
1735
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1736
  try:
1737
    return hyper.GetMigrationStatus(instance)
1738
  except Exception, err:  # pylint: disable=W0703
1739
    _Fail("Failed to get migration status: %s", err, exc=True)
1740

    
1741

    
1742
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
1743
  """Creates a block device for an instance.
1744

1745
  @type disk: L{objects.Disk}
1746
  @param disk: the object describing the disk we should create
1747
  @type size: int
1748
  @param size: the size of the physical underlying device, in MiB
1749
  @type owner: str
1750
  @param owner: the name of the instance for which disk is created,
1751
      used for device cache data
1752
  @type on_primary: boolean
1753
  @param on_primary:  indicates if it is the primary node or not
1754
  @type info: string
1755
  @param info: string that will be sent to the physical device
1756
      creation, used for example to set (LVM) tags on LVs
1757
  @type excl_stor: boolean
1758
  @param excl_stor: Whether exclusive_storage is active
1759

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

1764
  """
1765
  # TODO: remove the obsolete "size" argument
1766
  # pylint: disable=W0613
1767
  clist = []
1768
  if disk.children:
1769
    for child in disk.children:
1770
      try:
1771
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1772
      except errors.BlockDeviceError, err:
1773
        _Fail("Can't assemble device %s: %s", child, err)
1774
      if on_primary or disk.AssembleOnSecondary():
1775
        # we need the children open in case the device itself has to
1776
        # be assembled
1777
        try:
1778
          # pylint: disable=E1103
1779
          crdev.Open()
1780
        except errors.BlockDeviceError, err:
1781
          _Fail("Can't make child '%s' read-write: %s", child, err)
1782
      clist.append(crdev)
1783

    
1784
  try:
1785
    device = bdev.Create(disk, clist, excl_stor)
1786
  except errors.BlockDeviceError, err:
1787
    _Fail("Can't create block device: %s", err)
1788

    
1789
  if on_primary or disk.AssembleOnSecondary():
1790
    try:
1791
      device.Assemble()
1792
    except errors.BlockDeviceError, err:
1793
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1794
    if on_primary or disk.OpenOnSecondary():
1795
      try:
1796
        device.Open(force=True)
1797
      except errors.BlockDeviceError, err:
1798
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1799
    DevCacheManager.UpdateCache(device.dev_path, owner,
1800
                                on_primary, disk.iv_name)
1801

    
1802
  device.SetInfo(info)
1803

    
1804
  return device.unique_id
1805

    
1806

    
1807
def _WipeDevice(path, offset, size):
1808
  """This function actually wipes the device.
1809

1810
  @param path: The path to the device to wipe
1811
  @param offset: The offset in MiB in the file
1812
  @param size: The size in MiB to write
1813

1814
  """
1815
  # Internal sizes are always in Mebibytes; if the following "dd" command
1816
  # should use a different block size the offset and size given to this
1817
  # function must be adjusted accordingly before being passed to "dd".
1818
  block_size = 1024 * 1024
1819

    
1820
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1821
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
1822
         "count=%d" % size]
1823
  result = utils.RunCmd(cmd)
1824

    
1825
  if result.failed:
1826
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1827
          result.fail_reason, result.output)
1828

    
1829

    
1830
def BlockdevWipe(disk, offset, size):
1831
  """Wipes a block device.
1832

1833
  @type disk: L{objects.Disk}
1834
  @param disk: the disk object we want to wipe
1835
  @type offset: int
1836
  @param offset: The offset in MiB in the file
1837
  @type size: int
1838
  @param size: The size in MiB to write
1839

1840
  """
1841
  try:
1842
    rdev = _RecursiveFindBD(disk)
1843
  except errors.BlockDeviceError:
1844
    rdev = None
1845

    
1846
  if not rdev:
1847
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1848

    
1849
  # Do cross verify some of the parameters
1850
  if offset < 0:
1851
    _Fail("Negative offset")
1852
  if size < 0:
1853
    _Fail("Negative size")
1854
  if offset > rdev.size:
1855
    _Fail("Offset is bigger than device size")
1856
  if (offset + size) > rdev.size:
1857
    _Fail("The provided offset and size to wipe is bigger than device size")
1858

    
1859
  _WipeDevice(rdev.dev_path, offset, size)
1860

    
1861

    
1862
def BlockdevPauseResumeSync(disks, pause):
1863
  """Pause or resume the sync of the block device.
1864

1865
  @type disks: list of L{objects.Disk}
1866
  @param disks: the disks object we want to pause/resume
1867
  @type pause: bool
1868
  @param pause: Wheater to pause or resume
1869

1870
  """
1871
  success = []
1872
  for disk in disks:
1873
    try:
1874
      rdev = _RecursiveFindBD(disk)
1875
    except errors.BlockDeviceError:
1876
      rdev = None
1877

    
1878
    if not rdev:
1879
      success.append((False, ("Cannot change sync for device %s:"
1880
                              " device not found" % disk.iv_name)))
1881
      continue
1882

    
1883
    result = rdev.PauseResumeSync(pause)
1884

    
1885
    if result:
1886
      success.append((result, None))
1887
    else:
1888
      if pause:
1889
        msg = "Pause"
1890
      else:
1891
        msg = "Resume"
1892
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1893

    
1894
  return success
1895

    
1896

    
1897
def BlockdevRemove(disk):
1898
  """Remove a block device.
1899

1900
  @note: This is intended to be called recursively.
1901

1902
  @type disk: L{objects.Disk}
1903
  @param disk: the disk object we should remove
1904
  @rtype: boolean
1905
  @return: the success of the operation
1906

1907
  """
1908
  msgs = []
1909
  try:
1910
    rdev = _RecursiveFindBD(disk)
1911
  except errors.BlockDeviceError, err:
1912
    # probably can't attach
1913
    logging.info("Can't attach to device %s in remove", disk)
1914
    rdev = None
1915
  if rdev is not None:
1916
    r_path = rdev.dev_path
1917
    try:
1918
      rdev.Remove()
1919
    except errors.BlockDeviceError, err:
1920
      msgs.append(str(err))
1921
    if not msgs:
1922
      DevCacheManager.RemoveCache(r_path)
1923

    
1924
  if disk.children:
1925
    for child in disk.children:
1926
      try:
1927
        BlockdevRemove(child)
1928
      except RPCFail, err:
1929
        msgs.append(str(err))
1930

    
1931
  if msgs:
1932
    _Fail("; ".join(msgs))
1933

    
1934

    
1935
def _RecursiveAssembleBD(disk, owner, as_primary):
1936
  """Activate a block device for an instance.
1937

1938
  This is run on the primary and secondary nodes for an instance.
1939

1940
  @note: this function is called recursively.
1941

1942
  @type disk: L{objects.Disk}
1943
  @param disk: the disk we try to assemble
1944
  @type owner: str
1945
  @param owner: the name of the instance which owns the disk
1946
  @type as_primary: boolean
1947
  @param as_primary: if we should make the block device
1948
      read/write
1949

1950
  @return: the assembled device or None (in case no device
1951
      was assembled)
1952
  @raise errors.BlockDeviceError: in case there is an error
1953
      during the activation of the children or the device
1954
      itself
1955

1956
  """
1957
  children = []
1958
  if disk.children:
1959
    mcn = disk.ChildrenNeeded()
1960
    if mcn == -1:
1961
      mcn = 0 # max number of Nones allowed
1962
    else:
1963
      mcn = len(disk.children) - mcn # max number of Nones
1964
    for chld_disk in disk.children:
1965
      try:
1966
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1967
      except errors.BlockDeviceError, err:
1968
        if children.count(None) >= mcn:
1969
          raise
1970
        cdev = None
1971
        logging.error("Error in child activation (but continuing): %s",
1972
                      str(err))
1973
      children.append(cdev)
1974

    
1975
  if as_primary or disk.AssembleOnSecondary():
1976
    r_dev = bdev.Assemble(disk, children)
1977
    result = r_dev
1978
    if as_primary or disk.OpenOnSecondary():
1979
      r_dev.Open()
1980
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1981
                                as_primary, disk.iv_name)
1982

    
1983
  else:
1984
    result = True
1985
  return result
1986

    
1987

    
1988
def BlockdevAssemble(disk, owner, as_primary, idx):
1989
  """Activate a block device for an instance.
1990

1991
  This is a wrapper over _RecursiveAssembleBD.
1992

1993
  @rtype: str or boolean
1994
  @return: a C{/dev/...} path for primary nodes, and
1995
      C{True} for secondary nodes
1996

1997
  """
1998
  try:
1999
    result = _RecursiveAssembleBD(disk, owner, as_primary)
2000
    if isinstance(result, BlockDev):
2001
      # pylint: disable=E1103
2002
      result = result.dev_path
2003
      if as_primary:
2004
        _SymlinkBlockDev(owner, result, idx)
2005
  except errors.BlockDeviceError, err:
2006
    _Fail("Error while assembling disk: %s", err, exc=True)
2007
  except OSError, err:
2008
    _Fail("Error while symlinking disk: %s", err, exc=True)
2009

    
2010
  return result
2011

    
2012

    
2013
def BlockdevShutdown(disk):
2014
  """Shut down a block device.
2015

2016
  First, if the device is assembled (Attach() is successful), then
2017
  the device is shutdown. Then the children of the device are
2018
  shutdown.
2019

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

2024
  @type disk: L{objects.Disk}
2025
  @param disk: the description of the disk we should
2026
      shutdown
2027
  @rtype: None
2028

2029
  """
2030
  msgs = []
2031
  r_dev = _RecursiveFindBD(disk)
2032
  if r_dev is not None:
2033
    r_path = r_dev.dev_path
2034
    try:
2035
      r_dev.Shutdown()
2036
      DevCacheManager.RemoveCache(r_path)
2037
    except errors.BlockDeviceError, err:
2038
      msgs.append(str(err))
2039

    
2040
  if disk.children:
2041
    for child in disk.children:
2042
      try:
2043
        BlockdevShutdown(child)
2044
      except RPCFail, err:
2045
        msgs.append(str(err))
2046

    
2047
  if msgs:
2048
    _Fail("; ".join(msgs))
2049

    
2050

    
2051
def BlockdevAddchildren(parent_cdev, new_cdevs):
2052
  """Extend a mirrored block device.
2053

2054
  @type parent_cdev: L{objects.Disk}
2055
  @param parent_cdev: the disk to which we should add children
2056
  @type new_cdevs: list of L{objects.Disk}
2057
  @param new_cdevs: the list of children which we should add
2058
  @rtype: None
2059

2060
  """
2061
  parent_bdev = _RecursiveFindBD(parent_cdev)
2062
  if parent_bdev is None:
2063
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
2064
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
2065
  if new_bdevs.count(None) > 0:
2066
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
2067
  parent_bdev.AddChildren(new_bdevs)
2068

    
2069

    
2070
def BlockdevRemovechildren(parent_cdev, new_cdevs):
2071
  """Shrink a mirrored block device.
2072

2073
  @type parent_cdev: L{objects.Disk}
2074
  @param parent_cdev: the disk from which we should remove children
2075
  @type new_cdevs: list of L{objects.Disk}
2076
  @param new_cdevs: the list of children which we should remove
2077
  @rtype: None
2078

2079
  """
2080
  parent_bdev = _RecursiveFindBD(parent_cdev)
2081
  if parent_bdev is None:
2082
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
2083
  devs = []
2084
  for disk in new_cdevs:
2085
    rpath = disk.StaticDevPath()
2086
    if rpath is None:
2087
      bd = _RecursiveFindBD(disk)
2088
      if bd is None:
2089
        _Fail("Can't find device %s while removing children", disk)
2090
      else:
2091
        devs.append(bd.dev_path)
2092
    else:
2093
      if not utils.IsNormAbsPath(rpath):
2094
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
2095
      devs.append(rpath)
2096
  parent_bdev.RemoveChildren(devs)
2097

    
2098

    
2099
def BlockdevGetmirrorstatus(disks):
2100
  """Get the mirroring status of a list of devices.
2101

2102
  @type disks: list of L{objects.Disk}
2103
  @param disks: the list of disks which we should query
2104
  @rtype: disk
2105
  @return: List of L{objects.BlockDevStatus}, one for each disk
2106
  @raise errors.BlockDeviceError: if any of the disks cannot be
2107
      found
2108

2109
  """
2110
  stats = []
2111
  for dsk in disks:
2112
    rbd = _RecursiveFindBD(dsk)
2113
    if rbd is None:
2114
      _Fail("Can't find device %s", dsk)
2115

    
2116
    stats.append(rbd.CombinedSyncStatus())
2117

    
2118
  return stats
2119

    
2120

    
2121
def BlockdevGetmirrorstatusMulti(disks):
2122
  """Get the mirroring status of a list of devices.
2123

2124
  @type disks: list of L{objects.Disk}
2125
  @param disks: the list of disks which we should query
2126
  @rtype: disk
2127
  @return: List of tuples, (bool, status), one for each disk; bool denotes
2128
    success/failure, status is L{objects.BlockDevStatus} on success, string
2129
    otherwise
2130

2131
  """
2132
  result = []
2133
  for disk in disks:
2134
    try:
2135
      rbd = _RecursiveFindBD(disk)
2136
      if rbd is None:
2137
        result.append((False, "Can't find device %s" % disk))
2138
        continue
2139

    
2140
      status = rbd.CombinedSyncStatus()
2141
    except errors.BlockDeviceError, err:
2142
      logging.exception("Error while getting disk status")
2143
      result.append((False, str(err)))
2144
    else:
2145
      result.append((True, status))
2146

    
2147
  assert len(disks) == len(result)
2148

    
2149
  return result
2150

    
2151

    
2152
def _RecursiveFindBD(disk):
2153
  """Check if a device is activated.
2154

2155
  If so, return information about the real device.
2156

2157
  @type disk: L{objects.Disk}
2158
  @param disk: the disk object we need to find
2159

2160
  @return: None if the device can't be found,
2161
      otherwise the device instance
2162

2163
  """
2164
  children = []
2165
  if disk.children:
2166
    for chdisk in disk.children:
2167
      children.append(_RecursiveFindBD(chdisk))
2168

    
2169
  return bdev.FindDevice(disk, children)
2170

    
2171

    
2172
def _OpenRealBD(disk):
2173
  """Opens the underlying block device of a disk.
2174

2175
  @type disk: L{objects.Disk}
2176
  @param disk: the disk object we want to open
2177

2178
  """
2179
  real_disk = _RecursiveFindBD(disk)
2180
  if real_disk is None:
2181
    _Fail("Block device '%s' is not set up", disk)
2182

    
2183
  real_disk.Open()
2184

    
2185
  return real_disk
2186

    
2187

    
2188
def BlockdevFind(disk):
2189
  """Check if a device is activated.
2190

2191
  If it is, return information about the real device.
2192

2193
  @type disk: L{objects.Disk}
2194
  @param disk: the disk to find
2195
  @rtype: None or objects.BlockDevStatus
2196
  @return: None if the disk cannot be found, otherwise a the current
2197
           information
2198

2199
  """
2200
  try:
2201
    rbd = _RecursiveFindBD(disk)
2202
  except errors.BlockDeviceError, err:
2203
    _Fail("Failed to find device: %s", err, exc=True)
2204

    
2205
  if rbd is None:
2206
    return None
2207

    
2208
  return rbd.GetSyncStatus()
2209

    
2210

    
2211
def BlockdevGetdimensions(disks):
2212
  """Computes the size of the given disks.
2213

2214
  If a disk is not found, returns None instead.
2215

2216
  @type disks: list of L{objects.Disk}
2217
  @param disks: the list of disk to compute the size for
2218
  @rtype: list
2219
  @return: list with elements None if the disk cannot be found,
2220
      otherwise the pair (size, spindles), where spindles is None if the
2221
      device doesn't support that
2222

2223
  """
2224
  result = []
2225
  for cf in disks:
2226
    try:
2227
      rbd = _RecursiveFindBD(cf)
2228
    except errors.BlockDeviceError:
2229
      result.append(None)
2230
      continue
2231
    if rbd is None:
2232
      result.append(None)
2233
    else:
2234
      result.append(rbd.GetActualDimensions())
2235
  return result
2236

    
2237

    
2238
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2239
  """Export a block device to a remote node.
2240

2241
  @type disk: L{objects.Disk}
2242
  @param disk: the description of the disk to export
2243
  @type dest_node: str
2244
  @param dest_node: the destination node to export to
2245
  @type dest_path: str
2246
  @param dest_path: the destination path on the target node
2247
  @type cluster_name: str
2248
  @param cluster_name: the cluster name, needed for SSH hostalias
2249
  @rtype: None
2250

2251
  """
2252
  real_disk = _OpenRealBD(disk)
2253

    
2254
  # the block size on the read dd is 1MiB to match our units
2255
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2256
                               "dd if=%s bs=1048576 count=%s",
2257
                               real_disk.dev_path, str(disk.size))
2258

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

    
2268
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2269
                                                   constants.SSH_LOGIN_USER,
2270
                                                   destcmd)
2271

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

    
2275
  result = utils.RunCmd(["bash", "-c", command])
2276

    
2277
  if result.failed:
2278
    _Fail("Disk copy command '%s' returned error: %s"
2279
          " output: %s", command, result.fail_reason, result.output)
2280

    
2281

    
2282
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2283
  """Write a file to the filesystem.
2284

2285
  This allows the master to overwrite(!) a file. It will only perform
2286
  the operation if the file belongs to a list of configuration files.
2287

2288
  @type file_name: str
2289
  @param file_name: the target file name
2290
  @type data: str
2291
  @param data: the new contents of the file
2292
  @type mode: int
2293
  @param mode: the mode to give the file (can be None)
2294
  @type uid: string
2295
  @param uid: the owner of the file
2296
  @type gid: string
2297
  @param gid: the group of the file
2298
  @type atime: float
2299
  @param atime: the atime to set on the file (can be None)
2300
  @type mtime: float
2301
  @param mtime: the mtime to set on the file (can be None)
2302
  @rtype: None
2303

2304
  """
2305
  file_name = vcluster.LocalizeVirtualPath(file_name)
2306

    
2307
  if not os.path.isabs(file_name):
2308
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2309

    
2310
  if file_name not in _ALLOWED_UPLOAD_FILES:
2311
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2312
          file_name)
2313

    
2314
  raw_data = _Decompress(data)
2315

    
2316
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2317
    _Fail("Invalid username/groupname type")
2318

    
2319
  getents = runtime.GetEnts()
2320
  uid = getents.LookupUser(uid)
2321
  gid = getents.LookupGroup(gid)
2322

    
2323
  utils.SafeWriteFile(file_name, None,
2324
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2325
                      atime=atime, mtime=mtime)
2326

    
2327

    
2328
def RunOob(oob_program, command, node, timeout):
2329
  """Executes oob_program with given command on given node.
2330

2331
  @param oob_program: The path to the executable oob_program
2332
  @param command: The command to invoke on oob_program
2333
  @param node: The node given as an argument to the program
2334
  @param timeout: Timeout after which we kill the oob program
2335

2336
  @return: stdout
2337
  @raise RPCFail: If execution fails for some reason
2338

2339
  """
2340
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2341

    
2342
  if result.failed:
2343
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2344
          result.fail_reason, result.output)
2345

    
2346
  return result.stdout
2347

    
2348

    
2349
def _OSOndiskAPIVersion(os_dir):
2350
  """Compute and return the API version of a given OS.
2351

2352
  This function will try to read the API version of the OS residing in
2353
  the 'os_dir' directory.
2354

2355
  @type os_dir: str
2356
  @param os_dir: the directory in which we should look for the OS
2357
  @rtype: tuple
2358
  @return: tuple (status, data) with status denoting the validity and
2359
      data holding either the vaid versions or an error message
2360

2361
  """
2362
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2363

    
2364
  try:
2365
    st = os.stat(api_file)
2366
  except EnvironmentError, err:
2367
    return False, ("Required file '%s' not found under path %s: %s" %
2368
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2369

    
2370
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2371
    return False, ("File '%s' in %s is not a regular file" %
2372
                   (constants.OS_API_FILE, os_dir))
2373

    
2374
  try:
2375
    api_versions = utils.ReadFile(api_file).splitlines()
2376
  except EnvironmentError, err:
2377
    return False, ("Error while reading the API version file at %s: %s" %
2378
                   (api_file, utils.ErrnoOrStr(err)))
2379

    
2380
  try:
2381
    api_versions = [int(version.strip()) for version in api_versions]
2382
  except (TypeError, ValueError), err:
2383
    return False, ("API version(s) can't be converted to integer: %s" %
2384
                   str(err))
2385

    
2386
  return True, api_versions
2387

    
2388

    
2389
def DiagnoseOS(top_dirs=None):
2390
  """Compute the validity for all OSes.
2391

2392
  @type top_dirs: list
2393
  @param top_dirs: the list of directories in which to
2394
      search (if not given defaults to
2395
      L{pathutils.OS_SEARCH_PATH})
2396
  @rtype: list of L{objects.OS}
2397
  @return: a list of tuples (name, path, status, diagnose, variants,
2398
      parameters, api_version) for all (potential) OSes under all
2399
      search paths, where:
2400
          - name is the (potential) OS name
2401
          - path is the full path to the OS
2402
          - status True/False is the validity of the OS
2403
          - diagnose is the error message for an invalid OS, otherwise empty
2404
          - variants is a list of supported OS variants, if any
2405
          - parameters is a list of (name, help) parameters, if any
2406
          - api_version is a list of support OS API versions
2407

2408
  """
2409
  if top_dirs is None:
2410
    top_dirs = pathutils.OS_SEARCH_PATH
2411

    
2412
  result = []
2413
  for dir_name in top_dirs:
2414
    if os.path.isdir(dir_name):
2415
      try:
2416
        f_names = utils.ListVisibleFiles(dir_name)
2417
      except EnvironmentError, err:
2418
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2419
        break
2420
      for name in f_names:
2421
        os_path = utils.PathJoin(dir_name, name)
2422
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2423
        if status:
2424
          diagnose = ""
2425
          variants = os_inst.supported_variants
2426
          parameters = os_inst.supported_parameters
2427
          api_versions = os_inst.api_versions
2428
        else:
2429
          diagnose = os_inst
2430
          variants = parameters = api_versions = []
2431
        result.append((name, os_path, status, diagnose, variants,
2432
                       parameters, api_versions))
2433

    
2434
  return result
2435

    
2436

    
2437
def _TryOSFromDisk(name, base_dir=None):
2438
  """Create an OS instance from disk.
2439

2440
  This function will return an OS instance if the given name is a
2441
  valid OS name.
2442

2443
  @type base_dir: string
2444
  @keyword base_dir: Base directory containing OS installations.
2445
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2446
  @rtype: tuple
2447
  @return: success and either the OS instance if we find a valid one,
2448
      or error message
2449

2450
  """
2451
  if base_dir is None:
2452
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2453
  else:
2454
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2455

    
2456
  if os_dir is None:
2457
    return False, "Directory for OS %s not found in search path" % name
2458

    
2459
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2460
  if not status:
2461
    # push the error up
2462
    return status, api_versions
2463

    
2464
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2465
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2466
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2467

    
2468
  # OS Files dictionary, we will populate it with the absolute path
2469
  # names; if the value is True, then it is a required file, otherwise
2470
  # an optional one
2471
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2472

    
2473
  if max(api_versions) >= constants.OS_API_V15:
2474
    os_files[constants.OS_VARIANTS_FILE] = False
2475

    
2476
  if max(api_versions) >= constants.OS_API_V20:
2477
    os_files[constants.OS_PARAMETERS_FILE] = True
2478
  else:
2479
    del os_files[constants.OS_SCRIPT_VERIFY]
2480

    
2481
  for (filename, required) in os_files.items():
2482
    os_files[filename] = utils.PathJoin(os_dir, filename)
2483

    
2484
    try:
2485
      st = os.stat(os_files[filename])
2486
    except EnvironmentError, err:
2487
      if err.errno == errno.ENOENT and not required:
2488
        del os_files[filename]
2489
        continue
2490
      return False, ("File '%s' under path '%s' is missing (%s)" %
2491
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2492

    
2493
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2494
      return False, ("File '%s' under path '%s' is not a regular file" %
2495
                     (filename, os_dir))
2496

    
2497
    if filename in constants.OS_SCRIPTS:
2498
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2499
        return False, ("File '%s' under path '%s' is not executable" %
2500
                       (filename, os_dir))
2501

    
2502
  variants = []
2503
  if constants.OS_VARIANTS_FILE in os_files:
2504
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2505
    try:
2506
      variants = \
2507
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2508
    except EnvironmentError, err:
2509
      # we accept missing files, but not other errors
2510
      if err.errno != errno.ENOENT:
2511
        return False, ("Error while reading the OS variants file at %s: %s" %
2512
                       (variants_file, utils.ErrnoOrStr(err)))
2513

    
2514
  parameters = []
2515
  if constants.OS_PARAMETERS_FILE in os_files:
2516
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2517
    try:
2518
      parameters = utils.ReadFile(parameters_file).splitlines()
2519
    except EnvironmentError, err:
2520
      return False, ("Error while reading the OS parameters file at %s: %s" %
2521
                     (parameters_file, utils.ErrnoOrStr(err)))
2522
    parameters = [v.split(None, 1) for v in parameters]
2523

    
2524
  os_obj = objects.OS(name=name, path=os_dir,
2525
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2526
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2527
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2528
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2529
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2530
                                                 None),
2531
                      supported_variants=variants,
2532
                      supported_parameters=parameters,
2533
                      api_versions=api_versions)
2534
  return True, os_obj
2535

    
2536

    
2537
def OSFromDisk(name, base_dir=None):
2538
  """Create an OS instance from disk.
2539

2540
  This function will return an OS instance if the given name is a
2541
  valid OS name. Otherwise, it will raise an appropriate
2542
  L{RPCFail} exception, detailing why this is not a valid OS.
2543

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

2547
  @type base_dir: string
2548
  @keyword base_dir: Base directory containing OS installations.
2549
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2550
  @rtype: L{objects.OS}
2551
  @return: the OS instance if we find a valid one
2552
  @raise RPCFail: if we don't find a valid OS
2553

2554
  """
2555
  name_only = objects.OS.GetName(name)
2556
  status, payload = _TryOSFromDisk(name_only, base_dir)
2557

    
2558
  if not status:
2559
    _Fail(payload)
2560

    
2561
  return payload
2562

    
2563

    
2564
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2565
  """Calculate the basic environment for an os script.
2566

2567
  @type os_name: str
2568
  @param os_name: full operating system name (including variant)
2569
  @type inst_os: L{objects.OS}
2570
  @param inst_os: operating system for which the environment is being built
2571
  @type os_params: dict
2572
  @param os_params: the OS parameters
2573
  @type debug: integer
2574
  @param debug: debug level (0 or 1, for OS Api 10)
2575
  @rtype: dict
2576
  @return: dict of environment variables
2577
  @raise errors.BlockDeviceError: if the block device
2578
      cannot be found
2579

2580
  """
2581
  result = {}
2582
  api_version = \
2583
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2584
  result["OS_API_VERSION"] = "%d" % api_version
2585
  result["OS_NAME"] = inst_os.name
2586
  result["DEBUG_LEVEL"] = "%d" % debug
2587

    
2588
  # OS variants
2589
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2590
    variant = objects.OS.GetVariant(os_name)
2591
    if not variant:
2592
      variant = inst_os.supported_variants[0]
2593
  else:
2594
    variant = ""
2595
  result["OS_VARIANT"] = variant
2596

    
2597
  # OS params
2598
  for pname, pvalue in os_params.items():
2599
    result["OSP_%s" % pname.upper()] = pvalue
2600

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

    
2606
  return result
2607

    
2608

    
2609
def OSEnvironment(instance, inst_os, debug=0):
2610
  """Calculate the environment for an os script.
2611

2612
  @type instance: L{objects.Instance}
2613
  @param instance: target instance for the os script run
2614
  @type inst_os: L{objects.OS}
2615
  @param inst_os: operating system for which the environment is being built
2616
  @type debug: integer
2617
  @param debug: debug level (0 or 1, for OS Api 10)
2618
  @rtype: dict
2619
  @return: dict of environment variables
2620
  @raise errors.BlockDeviceError: if the block device
2621
      cannot be found
2622

2623
  """
2624
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2625

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

    
2629
  result["HYPERVISOR"] = instance.hypervisor
2630
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2631
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2632
  result["INSTANCE_SECONDARY_NODES"] = \
2633
      ("%s" % " ".join(instance.secondary_nodes))
2634

    
2635
  # Disks
2636
  for idx, disk in enumerate(instance.disks):
2637
    real_disk = _OpenRealBD(disk)
2638
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2639
    result["DISK_%d_ACCESS" % idx] = disk.mode
2640
    if constants.HV_DISK_TYPE in instance.hvparams:
2641
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2642
        instance.hvparams[constants.HV_DISK_TYPE]
2643
    if disk.dev_type in constants.LDS_BLOCK:
2644
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2645
    elif disk.dev_type == constants.LD_FILE:
2646
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2647
        "file:%s" % disk.physical_id[0]
2648

    
2649
  # NICs
2650
  for idx, nic in enumerate(instance.nics):
2651
    result["NIC_%d_MAC" % idx] = nic.mac
2652
    if nic.ip:
2653
      result["NIC_%d_IP" % idx] = nic.ip
2654
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2655
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2656
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2657
    if nic.nicparams[constants.NIC_LINK]:
2658
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2659
    if nic.netinfo:
2660
      nobj = objects.Network.FromDict(nic.netinfo)
2661
      result.update(nobj.HooksDict("NIC_%d_" % idx))
2662
    if constants.HV_NIC_TYPE in instance.hvparams:
2663
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2664
        instance.hvparams[constants.HV_NIC_TYPE]
2665

    
2666
  # HV/BE params
2667
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2668
    for key, value in source.items():
2669
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2670

    
2671
  return result
2672

    
2673

    
2674
def DiagnoseExtStorage(top_dirs=None):
2675
  """Compute the validity for all ExtStorage Providers.
2676

2677
  @type top_dirs: list
2678
  @param top_dirs: the list of directories in which to
2679
      search (if not given defaults to
2680
      L{pathutils.ES_SEARCH_PATH})
2681
  @rtype: list of L{objects.ExtStorage}
2682
  @return: a list of tuples (name, path, status, diagnose, parameters)
2683
      for all (potential) ExtStorage Providers under all
2684
      search paths, where:
2685
          - name is the (potential) ExtStorage Provider
2686
          - path is the full path to the ExtStorage Provider
2687
          - status True/False is the validity of the ExtStorage Provider
2688
          - diagnose is the error message for an invalid ExtStorage Provider,
2689
            otherwise empty
2690
          - parameters is a list of (name, help) parameters, if any
2691

2692
  """
2693
  if top_dirs is None:
2694
    top_dirs = pathutils.ES_SEARCH_PATH
2695

    
2696
  result = []
2697
  for dir_name in top_dirs:
2698
    if os.path.isdir(dir_name):
2699
      try:
2700
        f_names = utils.ListVisibleFiles(dir_name)
2701
      except EnvironmentError, err:
2702
        logging.exception("Can't list the ExtStorage directory %s: %s",
2703
                          dir_name, err)
2704
        break
2705
      for name in f_names:
2706
        es_path = utils.PathJoin(dir_name, name)
2707
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2708
        if status:
2709
          diagnose = ""
2710
          parameters = es_inst.supported_parameters
2711
        else:
2712
          diagnose = es_inst
2713
          parameters = []
2714
        result.append((name, es_path, status, diagnose, parameters))
2715

    
2716
  return result
2717

    
2718

    
2719
def BlockdevGrow(disk, amount, dryrun, backingstore):
2720
  """Grow a stack of block devices.
2721

2722
  This function is called recursively, with the childrens being the
2723
  first ones to resize.
2724

2725
  @type disk: L{objects.Disk}
2726
  @param disk: the disk to be grown
2727
  @type amount: integer
2728
  @param amount: the amount (in mebibytes) to grow with
2729
  @type dryrun: boolean
2730
  @param dryrun: whether to execute the operation in simulation mode
2731
      only, without actually increasing the size
2732
  @param backingstore: whether to execute the operation on backing storage
2733
      only, or on "logical" storage only; e.g. DRBD is logical storage,
2734
      whereas LVM, file, RBD are backing storage
2735
  @rtype: (status, result)
2736
  @return: a tuple with the status of the operation (True/False), and
2737
      the errors message if status is False
2738

2739
  """
2740
  r_dev = _RecursiveFindBD(disk)
2741
  if r_dev is None:
2742
    _Fail("Cannot find block device %s", disk)
2743

    
2744
  try:
2745
    r_dev.Grow(amount, dryrun, backingstore)
2746
  except errors.BlockDeviceError, err:
2747
    _Fail("Failed to grow block device: %s", err, exc=True)
2748

    
2749

    
2750
def BlockdevSnapshot(disk):
2751
  """Create a snapshot copy of a block device.
2752

2753
  This function is called recursively, and the snapshot is actually created
2754
  just for the leaf lvm backend device.
2755

2756
  @type disk: L{objects.Disk}
2757
  @param disk: the disk to be snapshotted
2758
  @rtype: string
2759
  @return: snapshot disk ID as (vg, lv)
2760

2761
  """
2762
  if disk.dev_type == constants.LD_DRBD8:
2763
    if not disk.children:
2764
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2765
            disk.unique_id)
2766
    return BlockdevSnapshot(disk.children[0])
2767
  elif disk.dev_type == constants.LD_LV:
2768
    r_dev = _RecursiveFindBD(disk)
2769
    if r_dev is not None:
2770
      # FIXME: choose a saner value for the snapshot size
2771
      # let's stay on the safe side and ask for the full size, for now
2772
      return r_dev.Snapshot(disk.size)
2773
    else:
2774
      _Fail("Cannot find block device %s", disk)
2775
  else:
2776
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2777
          disk.unique_id, disk.dev_type)
2778

    
2779

    
2780
def BlockdevSetInfo(disk, info):
2781
  """Sets 'metadata' information on block devices.
2782

2783
  This function sets 'info' metadata on block devices. Initial
2784
  information is set at device creation; this function should be used
2785
  for example after renames.
2786

2787
  @type disk: L{objects.Disk}
2788
  @param disk: the disk to be grown
2789
  @type info: string
2790
  @param info: new 'info' metadata
2791
  @rtype: (status, result)
2792
  @return: a tuple with the status of the operation (True/False), and
2793
      the errors message if status is False
2794

2795
  """
2796
  r_dev = _RecursiveFindBD(disk)
2797
  if r_dev is None:
2798
    _Fail("Cannot find block device %s", disk)
2799

    
2800
  try:
2801
    r_dev.SetInfo(info)
2802
  except errors.BlockDeviceError, err:
2803
    _Fail("Failed to set information on block device: %s", err, exc=True)
2804

    
2805

    
2806
def FinalizeExport(instance, snap_disks):
2807
  """Write out the export configuration information.
2808

2809
  @type instance: L{objects.Instance}
2810
  @param instance: the instance which we export, used for
2811
      saving configuration
2812
  @type snap_disks: list of L{objects.Disk}
2813
  @param snap_disks: list of snapshot block devices, which
2814
      will be used to get the actual name of the dump file
2815

2816
  @rtype: None
2817

2818
  """
2819
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
2820
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
2821

    
2822
  config = objects.SerializableConfigParser()
2823

    
2824
  config.add_section(constants.INISECT_EXP)
2825
  config.set(constants.INISECT_EXP, "version", "0")
2826
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2827
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2828
  config.set(constants.INISECT_EXP, "os", instance.os)
2829
  config.set(constants.INISECT_EXP, "compression", "none")
2830

    
2831
  config.add_section(constants.INISECT_INS)
2832
  config.set(constants.INISECT_INS, "name", instance.name)
2833
  config.set(constants.INISECT_INS, "maxmem", "%d" %
2834
             instance.beparams[constants.BE_MAXMEM])
2835
  config.set(constants.INISECT_INS, "minmem", "%d" %
2836
             instance.beparams[constants.BE_MINMEM])
2837
  # "memory" is deprecated, but useful for exporting to old ganeti versions
2838
  config.set(constants.INISECT_INS, "memory", "%d" %
2839
             instance.beparams[constants.BE_MAXMEM])
2840
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2841
             instance.beparams[constants.BE_VCPUS])
2842
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2843
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2844
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2845

    
2846
  nic_total = 0
2847
  for nic_count, nic in enumerate(instance.nics):
2848
    nic_total += 1
2849
    config.set(constants.INISECT_INS, "nic%d_mac" %
2850
               nic_count, "%s" % nic.mac)
2851
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2852
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
2853
               "%s" % nic.network)
2854
    for param in constants.NICS_PARAMETER_TYPES:
2855
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2856
                 "%s" % nic.nicparams.get(param, None))
2857
  # TODO: redundant: on load can read nics until it doesn't exist
2858
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2859

    
2860
  disk_total = 0
2861
  for disk_count, disk in enumerate(snap_disks):
2862
    if disk:
2863
      disk_total += 1
2864
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2865
                 ("%s" % disk.iv_name))
2866
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2867
                 ("%s" % disk.physical_id[1]))
2868
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2869
                 ("%d" % disk.size))
2870

    
2871
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2872

    
2873
  # New-style hypervisor/backend parameters
2874

    
2875
  config.add_section(constants.INISECT_HYP)
2876
  for name, value in instance.hvparams.items():
2877
    if name not in constants.HVC_GLOBALS:
2878
      config.set(constants.INISECT_HYP, name, str(value))
2879

    
2880
  config.add_section(constants.INISECT_BEP)
2881
  for name, value in instance.beparams.items():
2882
    config.set(constants.INISECT_BEP, name, str(value))
2883

    
2884
  config.add_section(constants.INISECT_OSP)
2885
  for name, value in instance.osparams.items():
2886
    config.set(constants.INISECT_OSP, name, str(value))
2887

    
2888
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2889
                  data=config.Dumps())
2890
  shutil.rmtree(finaldestdir, ignore_errors=True)
2891
  shutil.move(destdir, finaldestdir)
2892

    
2893

    
2894
def ExportInfo(dest):
2895
  """Get export configuration information.
2896

2897
  @type dest: str
2898
  @param dest: directory containing the export
2899

2900
  @rtype: L{objects.SerializableConfigParser}
2901
  @return: a serializable config file containing the
2902
      export info
2903

2904
  """
2905
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2906

    
2907
  config = objects.SerializableConfigParser()
2908
  config.read(cff)
2909

    
2910
  if (not config.has_section(constants.INISECT_EXP) or
2911
      not config.has_section(constants.INISECT_INS)):
2912
    _Fail("Export info file doesn't have the required fields")
2913

    
2914
  return config.Dumps()
2915

    
2916

    
2917
def ListExports():
2918
  """Return a list of exports currently available on this machine.
2919

2920
  @rtype: list
2921
  @return: list of the exports
2922

2923
  """
2924
  if os.path.isdir(pathutils.EXPORT_DIR):
2925
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
2926
  else:
2927
    _Fail("No exports directory")
2928

    
2929

    
2930
def RemoveExport(export):
2931
  """Remove an existing export from the node.
2932

2933
  @type export: str
2934
  @param export: the name of the export to remove
2935
  @rtype: None
2936

2937
  """
2938
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
2939

    
2940
  try:
2941
    shutil.rmtree(target)
2942
  except EnvironmentError, err:
2943
    _Fail("Error while removing the export: %s", err, exc=True)
2944

    
2945

    
2946
def BlockdevRename(devlist):
2947
  """Rename a list of block devices.
2948

2949
  @type devlist: list of tuples
2950
  @param devlist: list of tuples of the form  (disk,
2951
      new_logical_id, new_physical_id); disk is an
2952
      L{objects.Disk} object describing the current disk,
2953
      and new logical_id/physical_id is the name we
2954
      rename it to
2955
  @rtype: boolean
2956
  @return: True if all renames succeeded, False otherwise
2957

2958
  """
2959
  msgs = []
2960
  result = True
2961
  for disk, unique_id in devlist:
2962
    dev = _RecursiveFindBD(disk)
2963
    if dev is None:
2964
      msgs.append("Can't find device %s in rename" % str(disk))
2965
      result = False
2966
      continue
2967
    try:
2968
      old_rpath = dev.dev_path
2969
      dev.Rename(unique_id)
2970
      new_rpath = dev.dev_path
2971
      if old_rpath != new_rpath:
2972
        DevCacheManager.RemoveCache(old_rpath)
2973
        # FIXME: we should add the new cache information here, like:
2974
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2975
        # but we don't have the owner here - maybe parse from existing
2976
        # cache? for now, we only lose lvm data when we rename, which
2977
        # is less critical than DRBD or MD
2978
    except errors.BlockDeviceError, err:
2979
      msgs.append("Can't rename device '%s' to '%s': %s" %
2980
                  (dev, unique_id, err))
2981
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2982
      result = False
2983
  if not result:
2984
    _Fail("; ".join(msgs))
2985

    
2986

    
2987
def _TransformFileStorageDir(fs_dir):
2988
  """Checks whether given file_storage_dir is valid.
2989

2990
  Checks wheter the given fs_dir is within the cluster-wide default
2991
  file_storage_dir or the shared_file_storage_dir, which are stored in
2992
  SimpleStore. Only paths under those directories are allowed.
2993

2994
  @type fs_dir: str
2995
  @param fs_dir: the path to check
2996

2997
  @return: the normalized path if valid, None otherwise
2998

2999
  """
3000
  if not (constants.ENABLE_FILE_STORAGE or
3001
          constants.ENABLE_SHARED_FILE_STORAGE):
3002
    _Fail("File storage disabled at configure time")
3003

    
3004
  bdev.CheckFileStoragePath(fs_dir)
3005

    
3006
  return os.path.normpath(fs_dir)
3007

    
3008

    
3009
def CreateFileStorageDir(file_storage_dir):
3010
  """Create file storage directory.
3011

3012
  @type file_storage_dir: str
3013
  @param file_storage_dir: directory to create
3014

3015
  @rtype: tuple
3016
  @return: tuple with first element a boolean indicating wheter dir
3017
      creation was successful or not
3018

3019
  """
3020
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3021
  if os.path.exists(file_storage_dir):
3022
    if not os.path.isdir(file_storage_dir):
3023
      _Fail("Specified storage dir '%s' is not a directory",
3024
            file_storage_dir)
3025
  else:
3026
    try:
3027
      os.makedirs(file_storage_dir, 0750)
3028
    except OSError, err:
3029
      _Fail("Cannot create file storage directory '%s': %s",
3030
            file_storage_dir, err, exc=True)
3031

    
3032

    
3033
def RemoveFileStorageDir(file_storage_dir):
3034
  """Remove file storage directory.
3035

3036
  Remove it only if it's empty. If not log an error and return.
3037

3038
  @type file_storage_dir: str
3039
  @param file_storage_dir: the directory we should cleanup
3040
  @rtype: tuple (success,)
3041
  @return: tuple of one element, C{success}, denoting
3042
      whether the operation was successful
3043

3044
  """
3045
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3046
  if os.path.exists(file_storage_dir):
3047
    if not os.path.isdir(file_storage_dir):
3048
      _Fail("Specified Storage directory '%s' is not a directory",
3049
            file_storage_dir)
3050
    # deletes dir only if empty, otherwise we want to fail the rpc call
3051
    try:
3052
      os.rmdir(file_storage_dir)
3053
    except OSError, err:
3054
      _Fail("Cannot remove file storage directory '%s': %s",
3055
            file_storage_dir, err)
3056

    
3057

    
3058
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
3059
  """Rename the file storage directory.
3060

3061
  @type old_file_storage_dir: str
3062
  @param old_file_storage_dir: the current path
3063
  @type new_file_storage_dir: str
3064
  @param new_file_storage_dir: the name we should rename to
3065
  @rtype: tuple (success,)
3066
  @return: tuple of one element, C{success}, denoting
3067
      whether the operation was successful
3068

3069
  """
3070
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
3071
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
3072
  if not os.path.exists(new_file_storage_dir):
3073
    if os.path.isdir(old_file_storage_dir):
3074
      try:
3075
        os.rename(old_file_storage_dir, new_file_storage_dir)
3076
      except OSError, err:
3077
        _Fail("Cannot rename '%s' to '%s': %s",
3078
              old_file_storage_dir, new_file_storage_dir, err)
3079
    else:
3080
      _Fail("Specified storage dir '%s' is not a directory",
3081
            old_file_storage_dir)
3082
  else:
3083
    if os.path.exists(old_file_storage_dir):
3084
      _Fail("Cannot rename '%s' to '%s': both locations exist",
3085
            old_file_storage_dir, new_file_storage_dir)
3086

    
3087

    
3088
def _EnsureJobQueueFile(file_name):
3089
  """Checks whether the given filename is in the queue directory.
3090

3091
  @type file_name: str
3092
  @param file_name: the file name we should check
3093
  @rtype: None
3094
  @raises RPCFail: if the file is not valid
3095

3096
  """
3097
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
3098
    _Fail("Passed job queue file '%s' does not belong to"
3099
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
3100

    
3101

    
3102
def JobQueueUpdate(file_name, content):
3103
  """Updates a file in the queue directory.
3104

3105
  This is just a wrapper over L{utils.io.WriteFile}, with proper
3106
  checking.
3107

3108
  @type file_name: str
3109
  @param file_name: the job file name
3110
  @type content: str
3111
  @param content: the new job contents
3112
  @rtype: boolean
3113
  @return: the success of the operation
3114

3115
  """
3116
  file_name = vcluster.LocalizeVirtualPath(file_name)
3117

    
3118
  _EnsureJobQueueFile(file_name)
3119
  getents = runtime.GetEnts()
3120

    
3121
  # Write and replace the file atomically
3122
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3123
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3124

    
3125

    
3126
def JobQueueRename(old, new):
3127
  """Renames a job queue file.
3128

3129
  This is just a wrapper over os.rename with proper checking.
3130

3131
  @type old: str
3132
  @param old: the old (actual) file name
3133
  @type new: str
3134
  @param new: the desired file name
3135
  @rtype: tuple
3136
  @return: the success of the operation and payload
3137

3138
  """
3139
  old = vcluster.LocalizeVirtualPath(old)
3140
  new = vcluster.LocalizeVirtualPath(new)
3141

    
3142
  _EnsureJobQueueFile(old)
3143
  _EnsureJobQueueFile(new)
3144

    
3145
  getents = runtime.GetEnts()
3146

    
3147
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3148
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3149

    
3150

    
3151
def BlockdevClose(instance_name, disks):
3152
  """Closes the given block devices.
3153

3154
  This means they will be switched to secondary mode (in case of
3155
  DRBD).
3156

3157
  @param instance_name: if the argument is not empty, the symlinks
3158
      of this instance will be removed
3159
  @type disks: list of L{objects.Disk}
3160
  @param disks: the list of disks to be closed
3161
  @rtype: tuple (success, message)
3162
  @return: a tuple of success and message, where success
3163
      indicates the succes of the operation, and message
3164
      which will contain the error details in case we
3165
      failed
3166

3167
  """
3168
  bdevs = []
3169
  for cf in disks:
3170
    rd = _RecursiveFindBD(cf)
3171
    if rd is None:
3172
      _Fail("Can't find device %s", cf)
3173
    bdevs.append(rd)
3174

    
3175
  msg = []
3176
  for rd in bdevs:
3177
    try:
3178
      rd.Close()
3179
    except errors.BlockDeviceError, err:
3180
      msg.append(str(err))
3181
  if msg:
3182
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3183
  else:
3184
    if instance_name:
3185
      _RemoveBlockDevLinks(instance_name, disks)
3186

    
3187

    
3188
def ValidateHVParams(hvname, hvparams):
3189
  """Validates the given hypervisor parameters.
3190

3191
  @type hvname: string
3192
  @param hvname: the hypervisor name
3193
  @type hvparams: dict
3194
  @param hvparams: the hypervisor parameters to be validated
3195
  @rtype: None
3196

3197
  """
3198
  try:
3199
    hv_type = hypervisor.GetHypervisor(hvname)
3200
    hv_type.ValidateParameters(hvparams)
3201
  except errors.HypervisorError, err:
3202
    _Fail(str(err), log=False)
3203

    
3204

    
3205
def _CheckOSPList(os_obj, parameters):
3206
  """Check whether a list of parameters is supported by the OS.
3207

3208
  @type os_obj: L{objects.OS}
3209
  @param os_obj: OS object to check
3210
  @type parameters: list
3211
  @param parameters: the list of parameters to check
3212

3213
  """
3214
  supported = [v[0] for v in os_obj.supported_parameters]
3215
  delta = frozenset(parameters).difference(supported)
3216
  if delta:
3217
    _Fail("The following parameters are not supported"
3218
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3219

    
3220

    
3221
def ValidateOS(required, osname, checks, osparams):
3222
  """Validate the given OS' parameters.
3223

3224
  @type required: boolean
3225
  @param required: whether absence of the OS should translate into
3226
      failure or not
3227
  @type osname: string
3228
  @param osname: the OS to be validated
3229
  @type checks: list
3230
  @param checks: list of the checks to run (currently only 'parameters')
3231
  @type osparams: dict
3232
  @param osparams: dictionary with OS parameters
3233
  @rtype: boolean
3234
  @return: True if the validation passed, or False if the OS was not
3235
      found and L{required} was false
3236

3237
  """
3238
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3239
    _Fail("Unknown checks required for OS %s: %s", osname,
3240
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3241

    
3242
  name_only = objects.OS.GetName(osname)
3243
  status, tbv = _TryOSFromDisk(name_only, None)
3244

    
3245
  if not status:
3246
    if required:
3247
      _Fail(tbv)
3248
    else:
3249
      return False
3250

    
3251
  if max(tbv.api_versions) < constants.OS_API_V20:
3252
    return True
3253

    
3254
  if constants.OS_VALIDATE_PARAMETERS in checks:
3255
    _CheckOSPList(tbv, osparams.keys())
3256

    
3257
  validate_env = OSCoreEnv(osname, tbv, osparams)
3258
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3259
                        cwd=tbv.path, reset_env=True)
3260
  if result.failed:
3261
    logging.error("os validate command '%s' returned error: %s output: %s",
3262
                  result.cmd, result.fail_reason, result.output)
3263
    _Fail("OS validation script failed (%s), output: %s",
3264
          result.fail_reason, result.output, log=False)
3265

    
3266
  return True
3267

    
3268

    
3269
def DemoteFromMC():
3270
  """Demotes the current node from master candidate role.
3271

3272
  """
3273
  # try to ensure we're not the master by mistake
3274
  master, myself = ssconf.GetMasterAndMyself()
3275
  if master == myself:
3276
    _Fail("ssconf status shows I'm the master node, will not demote")
3277

    
3278
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3279
  if not result.failed:
3280
    _Fail("The master daemon is running, will not demote")
3281

    
3282
  try:
3283
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3284
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3285
  except EnvironmentError, err:
3286
    if err.errno != errno.ENOENT:
3287
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3288

    
3289
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3290

    
3291

    
3292
def _GetX509Filenames(cryptodir, name):
3293
  """Returns the full paths for the private key and certificate.
3294

3295
  """
3296
  return (utils.PathJoin(cryptodir, name),
3297
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3298
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3299

    
3300

    
3301
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3302
  """Creates a new X509 certificate for SSL/TLS.
3303

3304
  @type validity: int
3305
  @param validity: Validity in seconds
3306
  @rtype: tuple; (string, string)
3307
  @return: Certificate name and public part
3308

3309
  """
3310
  (key_pem, cert_pem) = \
3311
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3312
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3313

    
3314
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3315
                              prefix="x509-%s-" % utils.TimestampForFilename())
3316
  try:
3317
    name = os.path.basename(cert_dir)
3318
    assert len(name) > 5
3319

    
3320
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3321

    
3322
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3323
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3324

    
3325
    # Never return private key as it shouldn't leave the node
3326
    return (name, cert_pem)
3327
  except Exception:
3328
    shutil.rmtree(cert_dir, ignore_errors=True)
3329
    raise
3330

    
3331

    
3332
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3333
  """Removes a X509 certificate.
3334

3335
  @type name: string
3336
  @param name: Certificate name
3337

3338
  """
3339
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3340

    
3341
  utils.RemoveFile(key_file)
3342
  utils.RemoveFile(cert_file)
3343

    
3344
  try:
3345
    os.rmdir(cert_dir)
3346
  except EnvironmentError, err:
3347
    _Fail("Cannot remove certificate directory '%s': %s",
3348
          cert_dir, err)
3349

    
3350

    
3351
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3352
  """Returns the command for the requested input/output.
3353

3354
  @type instance: L{objects.Instance}
3355
  @param instance: The instance object
3356
  @param mode: Import/export mode
3357
  @param ieio: Input/output type
3358
  @param ieargs: Input/output arguments
3359

3360
  """
3361
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3362

    
3363
  env = None
3364
  prefix = None
3365
  suffix = None
3366
  exp_size = None
3367

    
3368
  if ieio == constants.IEIO_FILE:
3369
    (filename, ) = ieargs
3370

    
3371
    if not utils.IsNormAbsPath(filename):
3372
      _Fail("Path '%s' is not normalized or absolute", filename)
3373

    
3374
    real_filename = os.path.realpath(filename)
3375
    directory = os.path.dirname(real_filename)
3376

    
3377
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3378
      _Fail("File '%s' is not under exports directory '%s': %s",
3379
            filename, pathutils.EXPORT_DIR, real_filename)
3380

    
3381
    # Create directory
3382
    utils.Makedirs(directory, mode=0750)
3383

    
3384
    quoted_filename = utils.ShellQuote(filename)
3385

    
3386
    if mode == constants.IEM_IMPORT:
3387
      suffix = "> %s" % quoted_filename
3388
    elif mode == constants.IEM_EXPORT:
3389
      suffix = "< %s" % quoted_filename
3390

    
3391
      # Retrieve file size
3392
      try:
3393
        st = os.stat(filename)
3394
      except EnvironmentError, err:
3395
        logging.error("Can't stat(2) %s: %s", filename, err)
3396
      else:
3397
        exp_size = utils.BytesToMebibyte(st.st_size)
3398

    
3399
  elif ieio == constants.IEIO_RAW_DISK:
3400
    (disk, ) = ieargs
3401

    
3402
    real_disk = _OpenRealBD(disk)
3403

    
3404
    if mode == constants.IEM_IMPORT:
3405
      # we set here a smaller block size as, due to transport buffering, more
3406
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3407
      # is not already there or we pass a wrong path; we use notrunc to no
3408
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3409
      # much memory; this means that at best, we flush every 64k, which will
3410
      # not be very fast
3411
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3412
                                    " bs=%s oflag=dsync"),
3413
                                    real_disk.dev_path,
3414
                                    str(64 * 1024))
3415

    
3416
    elif mode == constants.IEM_EXPORT:
3417
      # the block size on the read dd is 1MiB to match our units
3418
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3419
                                   real_disk.dev_path,
3420
                                   str(1024 * 1024), # 1 MB
3421
                                   str(disk.size))
3422
      exp_size = disk.size
3423

    
3424
  elif ieio == constants.IEIO_SCRIPT:
3425
    (disk, disk_index, ) = ieargs
3426

    
3427
    assert isinstance(disk_index, (int, long))
3428

    
3429
    real_disk = _OpenRealBD(disk)
3430

    
3431
    inst_os = OSFromDisk(instance.os)
3432
    env = OSEnvironment(instance, inst_os)
3433

    
3434
    if mode == constants.IEM_IMPORT:
3435
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3436
      env["IMPORT_INDEX"] = str(disk_index)
3437
      script = inst_os.import_script
3438

    
3439
    elif mode == constants.IEM_EXPORT:
3440
      env["EXPORT_DEVICE"] = real_disk.dev_path
3441
      env["EXPORT_INDEX"] = str(disk_index)
3442
      script = inst_os.export_script
3443

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

    
3447
    if mode == constants.IEM_IMPORT:
3448
      suffix = "| %s" % script_cmd
3449

    
3450
    elif mode == constants.IEM_EXPORT:
3451
      prefix = "%s |" % script_cmd
3452

    
3453
    # Let script predict size
3454
    exp_size = constants.IE_CUSTOM_SIZE
3455

    
3456
  else:
3457
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3458

    
3459
  return (env, prefix, suffix, exp_size)
3460

    
3461

    
3462
def _CreateImportExportStatusDir(prefix):
3463
  """Creates status directory for import/export.
3464

3465
  """
3466
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3467
                          prefix=("%s-%s-" %
3468
                                  (prefix, utils.TimestampForFilename())))
3469

    
3470

    
3471
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3472
                            ieio, ieioargs):
3473
  """Starts an import or export daemon.
3474

3475
  @param mode: Import/output mode
3476
  @type opts: L{objects.ImportExportOptions}
3477
  @param opts: Daemon options
3478
  @type host: string
3479
  @param host: Remote host for export (None for import)
3480
  @type port: int
3481
  @param port: Remote port for export (None for import)
3482
  @type instance: L{objects.Instance}
3483
  @param instance: Instance object
3484
  @type component: string
3485
  @param component: which part of the instance is transferred now,
3486
      e.g. 'disk/0'
3487
  @param ieio: Input/output type
3488
  @param ieioargs: Input/output arguments
3489

3490
  """
3491
  if mode == constants.IEM_IMPORT:
3492
    prefix = "import"
3493

    
3494
    if not (host is None and port is None):
3495
      _Fail("Can not specify host or port on import")
3496

    
3497
  elif mode == constants.IEM_EXPORT:
3498
    prefix = "export"
3499

    
3500
    if host is None or port is None:
3501
      _Fail("Host and port must be specified for an export")
3502

    
3503
  else:
3504
    _Fail("Invalid mode %r", mode)
3505

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

    
3509
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3510
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3511

    
3512
  if opts.key_name is None:
3513
    # Use server.pem
3514
    key_path = pathutils.NODED_CERT_FILE
3515
    cert_path = pathutils.NODED_CERT_FILE
3516
    assert opts.ca_pem is None
3517
  else:
3518
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3519
                                                 opts.key_name)
3520
    assert opts.ca_pem is not None
3521

    
3522
  for i in [key_path, cert_path]:
3523
    if not os.path.exists(i):
3524
      _Fail("File '%s' does not exist" % i)
3525

    
3526
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3527
  try:
3528
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3529
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3530
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3531

    
3532
    if opts.ca_pem is None:
3533
      # Use server.pem
3534
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3535
    else:
3536
      ca = opts.ca_pem
3537

    
3538
    # Write CA file
3539
    utils.WriteFile(ca_file, data=ca, mode=0400)
3540

    
3541
    cmd = [
3542
      pathutils.IMPORT_EXPORT_DAEMON,
3543
      status_file, mode,
3544
      "--key=%s" % key_path,
3545
      "--cert=%s" % cert_path,
3546
      "--ca=%s" % ca_file,
3547
      ]
3548

    
3549
    if host:
3550
      cmd.append("--host=%s" % host)
3551

    
3552
    if port:
3553
      cmd.append("--port=%s" % port)
3554

    
3555
    if opts.ipv6:
3556
      cmd.append("--ipv6")
3557
    else:
3558
      cmd.append("--ipv4")
3559

    
3560
    if opts.compress:
3561
      cmd.append("--compress=%s" % opts.compress)
3562

    
3563
    if opts.magic:
3564
      cmd.append("--magic=%s" % opts.magic)
3565

    
3566
    if exp_size is not None:
3567
      cmd.append("--expected-size=%s" % exp_size)
3568

    
3569
    if cmd_prefix:
3570
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3571

    
3572
    if cmd_suffix:
3573
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3574

    
3575
    if mode == constants.IEM_EXPORT:
3576
      # Retry connection a few times when connecting to remote peer
3577
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3578
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3579
    elif opts.connect_timeout is not None:
3580
      assert mode == constants.IEM_IMPORT
3581
      # Overall timeout for establishing connection while listening
3582
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3583

    
3584
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3585

    
3586
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3587
    # support for receiving a file descriptor for output
3588
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3589
                      output=logfile)
3590

    
3591
    # The import/export name is simply the status directory name
3592
    return os.path.basename(status_dir)
3593

    
3594
  except Exception:
3595
    shutil.rmtree(status_dir, ignore_errors=True)
3596
    raise
3597

    
3598

    
3599
def GetImportExportStatus(names):
3600
  """Returns import/export daemon status.
3601

3602
  @type names: sequence
3603
  @param names: List of names
3604
  @rtype: List of dicts
3605
  @return: Returns a list of the state of each named import/export or None if a
3606
           status couldn't be read
3607

3608
  """
3609
  result = []
3610

    
3611
  for name in names:
3612
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3613
                                 _IES_STATUS_FILE)
3614

    
3615
    try:
3616
      data = utils.ReadFile(status_file)
3617
    except EnvironmentError, err:
3618
      if err.errno != errno.ENOENT:
3619
        raise
3620
      data = None
3621

    
3622
    if not data:
3623
      result.append(None)
3624
      continue
3625

    
3626
    result.append(serializer.LoadJson(data))
3627

    
3628
  return result
3629

    
3630

    
3631
def AbortImportExport(name):
3632
  """Sends SIGTERM to a running import/export daemon.
3633

3634
  """
3635
  logging.info("Abort import/export %s", name)
3636

    
3637
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3638
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3639

    
3640
  if pid:
3641
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3642
                 name, pid)
3643
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3644

    
3645

    
3646
def CleanupImportExport(name):
3647
  """Cleanup after an import or export.
3648

3649
  If the import/export daemon is still running it's killed. Afterwards the
3650
  whole status directory is removed.
3651

3652
  """
3653
  logging.info("Finalizing import/export %s", name)
3654

    
3655
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3656

    
3657
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3658

    
3659
  if pid:
3660
    logging.info("Import/export %s is still running with PID %s",
3661
                 name, pid)
3662
    utils.KillProcess(pid, waitpid=False)
3663

    
3664
  shutil.rmtree(status_dir, ignore_errors=True)
3665

    
3666

    
3667
def _FindDisks(nodes_ip, disks):
3668
  """Sets the physical ID on disks and returns the block devices.
3669

3670
  """
3671
  # set the correct physical ID
3672
  my_name = netutils.Hostname.GetSysName()
3673
  for cf in disks:
3674
    cf.SetPhysicalID(my_name, nodes_ip)
3675

    
3676
  bdevs = []
3677

    
3678
  for cf in disks:
3679
    rd = _RecursiveFindBD(cf)
3680
    if rd is None:
3681
      _Fail("Can't find device %s", cf)
3682
    bdevs.append(rd)
3683
  return bdevs
3684

    
3685

    
3686
def DrbdDisconnectNet(nodes_ip, disks):
3687
  """Disconnects the network on a list of drbd devices.
3688

3689
  """
3690
  bdevs = _FindDisks(nodes_ip, disks)
3691

    
3692
  # disconnect disks
3693
  for rd in bdevs:
3694
    try:
3695
      rd.DisconnectNet()
3696
    except errors.BlockDeviceError, err:
3697
      _Fail("Can't change network configuration to standalone mode: %s",
3698
            err, exc=True)
3699

    
3700

    
3701
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3702
  """Attaches the network on a list of drbd devices.
3703

3704
  """
3705
  bdevs = _FindDisks(nodes_ip, disks)
3706

    
3707
  if multimaster:
3708
    for idx, rd in enumerate(bdevs):
3709
      try:
3710
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3711
      except EnvironmentError, err:
3712
        _Fail("Can't create symlink: %s", err)
3713
  # reconnect disks, switch to new master configuration and if
3714
  # needed primary mode
3715
  for rd in bdevs:
3716
    try:
3717
      rd.AttachNet(multimaster)
3718
    except errors.BlockDeviceError, err:
3719
      _Fail("Can't change network configuration: %s", err)
3720

    
3721
  # wait until the disks are connected; we need to retry the re-attach
3722
  # if the device becomes standalone, as this might happen if the one
3723
  # node disconnects and reconnects in a different mode before the
3724
  # other node reconnects; in this case, one or both of the nodes will
3725
  # decide it has wrong configuration and switch to standalone
3726

    
3727
  def _Attach():
3728
    all_connected = True
3729

    
3730
    for rd in bdevs:
3731
      stats = rd.GetProcStatus()
3732

    
3733
      all_connected = (all_connected and
3734
                       (stats.is_connected or stats.is_in_resync))
3735

    
3736
      if stats.is_standalone:
3737
        # peer had different config info and this node became
3738
        # standalone, even though this should not happen with the
3739
        # new staged way of changing disk configs
3740
        try:
3741
          rd.AttachNet(multimaster)
3742
        except errors.BlockDeviceError, err:
3743
          _Fail("Can't change network configuration: %s", err)
3744

    
3745
    if not all_connected:
3746
      raise utils.RetryAgain()
3747

    
3748
  try:
3749
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3750
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3751
  except utils.RetryTimeout:
3752
    _Fail("Timeout in disk reconnecting")
3753

    
3754
  if multimaster:
3755
    # change to primary mode
3756
    for rd in bdevs:
3757
      try:
3758
        rd.Open()
3759
      except errors.BlockDeviceError, err:
3760
        _Fail("Can't change to primary mode: %s", err)
3761

    
3762

    
3763
def DrbdWaitSync(nodes_ip, disks):
3764
  """Wait until DRBDs have synchronized.
3765

3766
  """
3767
  def _helper(rd):
3768
    stats = rd.GetProcStatus()
3769
    if not (stats.is_connected or stats.is_in_resync):
3770
      raise utils.RetryAgain()
3771
    return stats
3772

    
3773
  bdevs = _FindDisks(nodes_ip, disks)
3774

    
3775
  min_resync = 100
3776
  alldone = True
3777
  for rd in bdevs:
3778
    try:
3779
      # poll each second for 15 seconds
3780
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3781
    except utils.RetryTimeout:
3782
      stats = rd.GetProcStatus()
3783
      # last check
3784
      if not (stats.is_connected or stats.is_in_resync):
3785
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3786
    alldone = alldone and (not stats.is_in_resync)
3787
    if stats.sync_percent is not None:
3788
      min_resync = min(min_resync, stats.sync_percent)
3789

    
3790
  return (alldone, min_resync)
3791

    
3792

    
3793
def GetDrbdUsermodeHelper():
3794
  """Returns DRBD usermode helper currently configured.
3795

3796
  """
3797
  try:
3798
    return drbd.DRBD8.GetUsermodeHelper()
3799
  except errors.BlockDeviceError, err:
3800
    _Fail(str(err))
3801

    
3802

    
3803
def PowercycleNode(hypervisor_type):
3804
  """Hard-powercycle the node.
3805

3806
  Because we need to return first, and schedule the powercycle in the
3807
  background, we won't be able to report failures nicely.
3808

3809
  """
3810
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3811
  try:
3812
    pid = os.fork()
3813
  except OSError:
3814
    # if we can't fork, we'll pretend that we're in the child process
3815
    pid = 0
3816
  if pid > 0:
3817
    return "Reboot scheduled in 5 seconds"
3818
  # ensure the child is running on ram
3819
  try:
3820
    utils.Mlockall()
3821
  except Exception: # pylint: disable=W0703
3822
    pass
3823
  time.sleep(5)
3824
  hyper.PowercycleNode()
3825

    
3826

    
3827
def _VerifyRestrictedCmdName(cmd):
3828
  """Verifies a restricted command name.
3829

3830
  @type cmd: string
3831
  @param cmd: Command name
3832
  @rtype: tuple; (boolean, string or None)
3833
  @return: The tuple's first element is the status; if C{False}, the second
3834
    element is an error message string, otherwise it's C{None}
3835

3836
  """
3837
  if not cmd.strip():
3838
    return (False, "Missing command name")
3839

    
3840
  if os.path.basename(cmd) != cmd:
3841
    return (False, "Invalid command name")
3842

    
3843
  if not constants.EXT_PLUGIN_MASK.match(cmd):
3844
    return (False, "Command name contains forbidden characters")
3845

    
3846
  return (True, None)
3847

    
3848

    
3849
def _CommonRestrictedCmdCheck(path, owner):
3850
  """Common checks for restricted command file system directories and files.
3851

3852
  @type path: string
3853
  @param path: Path to check
3854
  @param owner: C{None} or tuple containing UID and GID
3855
  @rtype: tuple; (boolean, string or C{os.stat} result)
3856
  @return: The tuple's first element is the status; if C{False}, the second
3857
    element is an error message string, otherwise it's the result of C{os.stat}
3858

3859
  """
3860
  if owner is None:
3861
    # Default to root as owner
3862
    owner = (0, 0)
3863

    
3864
  try:
3865
    st = os.stat(path)
3866
  except EnvironmentError, err:
3867
    return (False, "Can't stat(2) '%s': %s" % (path, err))
3868

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

    
3872
  if (st.st_uid, st.st_gid) != owner:
3873
    (owner_uid, owner_gid) = owner
3874
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
3875

    
3876
  return (True, st)
3877

    
3878

    
3879
def _VerifyRestrictedCmdDirectory(path, _owner=None):
3880
  """Verifies restricted command directory.
3881

3882
  @type path: string
3883
  @param path: Path to check
3884
  @rtype: tuple; (boolean, string or None)
3885
  @return: The tuple's first element is the status; if C{False}, the second
3886
    element is an error message string, otherwise it's C{None}
3887

3888
  """
3889
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
3890

    
3891
  if not status:
3892
    return (False, value)
3893

    
3894
  if not stat.S_ISDIR(value.st_mode):
3895
    return (False, "Path '%s' is not a directory" % path)
3896

    
3897
  return (True, None)
3898

    
3899

    
3900
def _VerifyRestrictedCmd(path, cmd, _owner=None):
3901
  """Verifies a whole restricted command and returns its executable filename.
3902

3903
  @type path: string
3904
  @param path: Directory containing restricted commands
3905
  @type cmd: string
3906
  @param cmd: Command name
3907
  @rtype: tuple; (boolean, string)
3908
  @return: The tuple's first element is the status; if C{False}, the second
3909
    element is an error message string, otherwise the second element is the
3910
    absolute path to the executable
3911

3912
  """
3913
  executable = utils.PathJoin(path, cmd)
3914

    
3915
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
3916

    
3917
  if not status:
3918
    return (False, msg)
3919

    
3920
  if not utils.IsExecutable(executable):
3921
    return (False, "access(2) thinks '%s' can't be executed" % executable)
3922

    
3923
  return (True, executable)
3924

    
3925

    
3926
def _PrepareRestrictedCmd(path, cmd,
3927
                          _verify_dir=_VerifyRestrictedCmdDirectory,
3928
                          _verify_name=_VerifyRestrictedCmdName,
3929
                          _verify_cmd=_VerifyRestrictedCmd):
3930
  """Performs a number of tests on a restricted command.
3931

3932
  @type path: string
3933
  @param path: Directory containing restricted commands
3934
  @type cmd: string
3935
  @param cmd: Command name
3936
  @return: Same as L{_VerifyRestrictedCmd}
3937

3938
  """
3939
  # Verify the directory first
3940
  (status, msg) = _verify_dir(path)
3941
  if status:
3942
    # Check command if everything was alright
3943
    (status, msg) = _verify_name(cmd)
3944

    
3945
  if not status:
3946
    return (False, msg)
3947

    
3948
  # Check actual executable
3949
  return _verify_cmd(path, cmd)
3950

    
3951

    
3952
def RunRestrictedCmd(cmd,
3953
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
3954
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
3955
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
3956
                     _sleep_fn=time.sleep,
3957
                     _prepare_fn=_PrepareRestrictedCmd,
3958
                     _runcmd_fn=utils.RunCmd,
3959
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
3960
  """Executes a restricted command after performing strict tests.
3961

3962
  @type cmd: string
3963
  @param cmd: Command name
3964
  @rtype: string
3965
  @return: Command output
3966
  @raise RPCFail: In case of an error
3967

3968
  """
3969
  logging.info("Preparing to run restricted command '%s'", cmd)
3970

    
3971
  if not _enabled:
3972
    _Fail("Restricted commands disabled at configure time")
3973

    
3974
  lock = None
3975
  try:
3976
    cmdresult = None
3977
    try:
3978
      lock = utils.FileLock.Open(_lock_file)
3979
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
3980

    
3981
      (status, value) = _prepare_fn(_path, cmd)
3982

    
3983
      if status:
3984
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
3985
                               postfork_fn=lambda _: lock.Unlock())
3986
      else:
3987
        logging.error(value)
3988
    except Exception: # pylint: disable=W0703
3989
      # Keep original error in log
3990
      logging.exception("Caught exception")
3991

    
3992
    if cmdresult is None:
3993
      logging.info("Sleeping for %0.1f seconds before returning",
3994
                   _RCMD_INVALID_DELAY)
3995
      _sleep_fn(_RCMD_INVALID_DELAY)
3996

    
3997
      # Do not include original error message in returned error
3998
      _Fail("Executing command '%s' failed" % cmd)
3999
    elif cmdresult.failed or cmdresult.fail_reason:
4000
      _Fail("Restricted command '%s' failed: %s; output: %s",
4001
            cmd, cmdresult.fail_reason, cmdresult.output)
4002
    else:
4003
      return cmdresult.output
4004
  finally:
4005
    if lock is not None:
4006
      # Release lock at last
4007
      lock.Close()
4008
      lock = None
4009

    
4010

    
4011
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
4012
  """Creates or removes the watcher pause file.
4013

4014
  @type until: None or number
4015
  @param until: Unix timestamp saying until when the watcher shouldn't run
4016

4017
  """
4018
  if until is None:
4019
    logging.info("Received request to no longer pause watcher")
4020
    utils.RemoveFile(_filename)
4021
  else:
4022
    logging.info("Received request to pause watcher until %s", until)
4023

    
4024
    if not ht.TNumber(until):
4025
      _Fail("Duration must be numeric")
4026

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

    
4029

    
4030
class HooksRunner(object):
4031
  """Hook runner.
4032

4033
  This class is instantiated on the node side (ganeti-noded) and not
4034
  on the master side.
4035

4036
  """
4037
  def __init__(self, hooks_base_dir=None):
4038
    """Constructor for hooks runner.
4039

4040
    @type hooks_base_dir: str or None
4041
    @param hooks_base_dir: if not None, this overrides the
4042
        L{pathutils.HOOKS_BASE_DIR} (useful for unittests)
4043

4044
    """
4045
    if hooks_base_dir is None:
4046
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
4047
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
4048
    # constant
4049
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
4050

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

4054
    """
4055
    assert len(node_list) == 1
4056
    node = node_list[0]
4057
    _, myself = ssconf.GetMasterAndMyself()
4058
    assert node == myself
4059

    
4060
    results = self.RunHooks(hpath, phase, env)
4061

    
4062
    # Return values in the form expected by HooksMaster
4063
    return {node: (None, False, results)}
4064

    
4065
  def RunHooks(self, hpath, phase, env):
4066
    """Run the scripts in the hooks directory.
4067

4068
    @type hpath: str
4069
    @param hpath: the path to the hooks directory which
4070
        holds the scripts
4071
    @type phase: str
4072
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
4073
        L{constants.HOOKS_PHASE_POST}
4074
    @type env: dict
4075
    @param env: dictionary with the environment for the hook
4076
    @rtype: list
4077
    @return: list of 3-element tuples:
4078
      - script path
4079
      - script result, either L{constants.HKR_SUCCESS} or
4080
        L{constants.HKR_FAIL}
4081
      - output of the script
4082

4083
    @raise errors.ProgrammerError: for invalid input
4084
        parameters
4085

4086
    """
4087
    if phase == constants.HOOKS_PHASE_PRE:
4088
      suffix = "pre"
4089
    elif phase == constants.HOOKS_PHASE_POST:
4090
      suffix = "post"
4091
    else:
4092
      _Fail("Unknown hooks phase '%s'", phase)
4093

    
4094
    subdir = "%s-%s.d" % (hpath, suffix)
4095
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
4096

    
4097
    results = []
4098

    
4099
    if not os.path.isdir(dir_name):
4100
      # for non-existing/non-dirs, we simply exit instead of logging a
4101
      # warning at every operation
4102
      return results
4103

    
4104
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
4105

    
4106
    for (relname, relstatus, runresult) in runparts_results:
4107
      if relstatus == constants.RUNPARTS_SKIP:
4108
        rrval = constants.HKR_SKIP
4109
        output = ""
4110
      elif relstatus == constants.RUNPARTS_ERR:
4111
        rrval = constants.HKR_FAIL
4112
        output = "Hook script execution error: %s" % runresult
4113
      elif relstatus == constants.RUNPARTS_RUN:
4114
        if runresult.failed:
4115
          rrval = constants.HKR_FAIL
4116
        else:
4117
          rrval = constants.HKR_SUCCESS
4118
        output = utils.SafeEncode(runresult.output.strip())
4119
      results.append(("%s/%s" % (subdir, relname), rrval, output))
4120

    
4121
    return results
4122

    
4123

    
4124
class IAllocatorRunner(object):
4125
  """IAllocator runner.
4126

4127
  This class is instantiated on the node side (ganeti-noded) and not on
4128
  the master side.
4129

4130
  """
4131
  @staticmethod
4132
  def Run(name, idata):
4133
    """Run an iallocator script.
4134

4135
    @type name: str
4136
    @param name: the iallocator script name
4137
    @type idata: str
4138
    @param idata: the allocator input data
4139

4140
    @rtype: tuple
4141
    @return: two element tuple of:
4142
       - status
4143
       - either error message or stdout of allocator (for success)
4144

4145
    """
4146
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
4147
                                  os.path.isfile)
4148
    if alloc_script is None:
4149
      _Fail("iallocator module '%s' not found in the search path", name)
4150

    
4151
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
4152
    try:
4153
      os.write(fd, idata)
4154
      os.close(fd)
4155
      result = utils.RunCmd([alloc_script, fin_name])
4156
      if result.failed:
4157
        _Fail("iallocator module '%s' failed: %s, output '%s'",
4158
              name, result.fail_reason, result.output)
4159
    finally:
4160
      os.unlink(fin_name)
4161

    
4162
    return result.stdout
4163

    
4164

    
4165
class DevCacheManager(object):
4166
  """Simple class for managing a cache of block device information.
4167

4168
  """
4169
  _DEV_PREFIX = "/dev/"
4170
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4171

    
4172
  @classmethod
4173
  def _ConvertPath(cls, dev_path):
4174
    """Converts a /dev/name path to the cache file name.
4175

4176
    This replaces slashes with underscores and strips the /dev
4177
    prefix. It then returns the full path to the cache file.
4178

4179
    @type dev_path: str
4180
    @param dev_path: the C{/dev/} path name
4181
    @rtype: str
4182
    @return: the converted path name
4183

4184
    """
4185
    if dev_path.startswith(cls._DEV_PREFIX):
4186
      dev_path = dev_path[len(cls._DEV_PREFIX):]
4187
    dev_path = dev_path.replace("/", "_")
4188
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4189
    return fpath
4190

    
4191
  @classmethod
4192
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4193
    """Updates the cache information for a given device.
4194

4195
    @type dev_path: str
4196
    @param dev_path: the pathname of the device
4197
    @type owner: str
4198
    @param owner: the owner (instance name) of the device
4199
    @type on_primary: bool
4200
    @param on_primary: whether this is the primary
4201
        node nor not
4202
    @type iv_name: str
4203
    @param iv_name: the instance-visible name of the
4204
        device, as in objects.Disk.iv_name
4205

4206
    @rtype: None
4207

4208
    """
4209
    if dev_path is None:
4210
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
4211
      return
4212
    fpath = cls._ConvertPath(dev_path)
4213
    if on_primary:
4214
      state = "primary"
4215
    else:
4216
      state = "secondary"
4217
    if iv_name is None:
4218
      iv_name = "not_visible"
4219
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4220
    try:
4221
      utils.WriteFile(fpath, data=fdata)
4222
    except EnvironmentError, err:
4223
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4224

    
4225
  @classmethod
4226
  def RemoveCache(cls, dev_path):
4227
    """Remove data for a dev_path.
4228

4229
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
4230
    path name and logging.
4231

4232
    @type dev_path: str
4233
    @param dev_path: the pathname of the device
4234

4235
    @rtype: None
4236

4237
    """
4238
    if dev_path is None:
4239
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
4240
      return
4241
    fpath = cls._ConvertPath(dev_path)
4242
    try:
4243
      utils.RemoveFile(fpath)
4244
    except EnvironmentError, err:
4245
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)