Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 31135ddd

History | View | Annotate | Download (124.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 import bdev
58
from ganeti import objects
59
from ganeti import ssconf
60
from ganeti import serializer
61
from ganeti import netutils
62
from ganeti import runtime
63
from ganeti import mcpu
64
from ganeti import compat
65
from ganeti import pathutils
66
from ganeti import vcluster
67
from ganeti import ht
68

    
69

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

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

    
87
# Actions for the master setup script
88
_MASTER_START = "start"
89
_MASTER_STOP = "stop"
90

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

    
96
#: Delay before returning an error for restricted commands
97
_RCMD_INVALID_DELAY = 10
98

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

    
104

    
105
class RPCFail(Exception):
106
  """Class denoting RPC failure.
107

108
  Its argument is the error message.
109

110
  """
111

    
112

    
113
def _Fail(msg, *args, **kwargs):
114
  """Log an error and the raise an RPCFail exception.
115

116
  This exception is then handled specially in the ganeti daemon and
117
  turned into a 'failed' return type. As such, this function is a
118
  useful shortcut for logging the error and returning it to the master
119
  daemon.
120

121
  @type msg: string
122
  @param msg: the text of the exception
123
  @raise RPCFail
124

125
  """
126
  if args:
127
    msg = msg % args
128
  if "log" not in kwargs or kwargs["log"]: # if we should log this error
129
    if "exc" in kwargs and kwargs["exc"]:
130
      logging.exception(msg)
131
    else:
132
      logging.error(msg)
133
  raise RPCFail(msg)
134

    
135

    
136
def _GetConfig():
137
  """Simple wrapper to return a SimpleStore.
138

139
  @rtype: L{ssconf.SimpleStore}
140
  @return: a SimpleStore instance
141

142
  """
143
  return ssconf.SimpleStore()
144

    
145

    
146
def _GetSshRunner(cluster_name):
147
  """Simple wrapper to return an SshRunner.
148

149
  @type cluster_name: str
150
  @param cluster_name: the cluster name, which is needed
151
      by the SshRunner constructor
152
  @rtype: L{ssh.SshRunner}
153
  @return: an SshRunner instance
154

155
  """
156
  return ssh.SshRunner(cluster_name)
157

    
158

    
159
def _Decompress(data):
160
  """Unpacks data compressed by the RPC client.
161

162
  @type data: list or tuple
163
  @param data: Data sent by RPC client
164
  @rtype: str
165
  @return: Decompressed data
166

167
  """
168
  assert isinstance(data, (list, tuple))
169
  assert len(data) == 2
170
  (encoding, content) = data
171
  if encoding == constants.RPC_ENCODING_NONE:
172
    return content
173
  elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
174
    return zlib.decompress(base64.b64decode(content))
175
  else:
176
    raise AssertionError("Unknown data encoding")
177

    
178

    
179
def _CleanDirectory(path, exclude=None):
180
  """Removes all regular files in a directory.
181

182
  @type path: str
183
  @param path: the directory to clean
184
  @type exclude: list
185
  @param exclude: list of files to be excluded, defaults
186
      to the empty list
187

188
  """
189
  if path not in _ALLOWED_CLEAN_DIRS:
190
    _Fail("Path passed to _CleanDirectory not in allowed clean targets: '%s'",
191
          path)
192

    
193
  if not os.path.isdir(path):
194
    return
195
  if exclude is None:
196
    exclude = []
197
  else:
198
    # Normalize excluded paths
199
    exclude = [os.path.normpath(i) for i in exclude]
200

    
201
  for rel_name in utils.ListVisibleFiles(path):
202
    full_name = utils.PathJoin(path, rel_name)
203
    if full_name in exclude:
204
      continue
205
    if os.path.isfile(full_name) and not os.path.islink(full_name):
206
      utils.RemoveFile(full_name)
207

    
208

    
209
def _BuildUploadFileList():
210
  """Build the list of allowed upload files.
211

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

214
  """
215
  allowed_files = set([
216
    pathutils.CLUSTER_CONF_FILE,
217
    pathutils.ETC_HOSTS,
218
    pathutils.SSH_KNOWN_HOSTS_FILE,
219
    pathutils.VNC_PASSWORD_FILE,
220
    pathutils.RAPI_CERT_FILE,
221
    pathutils.SPICE_CERT_FILE,
222
    pathutils.SPICE_CACERT_FILE,
223
    pathutils.RAPI_USERS_FILE,
224
    pathutils.CONFD_HMAC_KEY,
225
    pathutils.CLUSTER_DOMAIN_SECRET_FILE,
226
    ])
227

    
228
  for hv_name in constants.HYPER_TYPES:
229
    hv_class = hypervisor.GetHypervisorClass(hv_name)
230
    allowed_files.update(hv_class.GetAncillaryFiles()[0])
231

    
232
  assert pathutils.FILE_STORAGE_PATHS_FILE not in allowed_files, \
233
    "Allowed file storage paths should never be uploaded via RPC"
234

    
235
  return frozenset(allowed_files)
236

    
237

    
238
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
239

    
240

    
241
def JobQueuePurge():
242
  """Removes job queue files and archived jobs.
243

244
  @rtype: tuple
245
  @return: True, None
246

247
  """
248
  _CleanDirectory(pathutils.QUEUE_DIR, exclude=[pathutils.JOB_QUEUE_LOCK_FILE])
249
  _CleanDirectory(pathutils.JOB_QUEUE_ARCHIVE_DIR)
250

    
251

    
252
def GetMasterInfo():
253
  """Returns master information.
254

255
  This is an utility function to compute master information, either
256
  for consumption here or from the node daemon.
257

258
  @rtype: tuple
259
  @return: master_netdev, master_ip, master_name, primary_ip_family,
260
    master_netmask
261
  @raise RPCFail: in case of errors
262

263
  """
264
  try:
265
    cfg = _GetConfig()
266
    master_netdev = cfg.GetMasterNetdev()
267
    master_ip = cfg.GetMasterIP()
268
    master_netmask = cfg.GetMasterNetmask()
269
    master_node = cfg.GetMasterNode()
270
    primary_ip_family = cfg.GetPrimaryIPFamily()
271
  except errors.ConfigurationError, err:
272
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
273
  return (master_netdev, master_ip, master_node, primary_ip_family,
274
          master_netmask)
275

    
276

    
277
def RunLocalHooks(hook_opcode, hooks_path, env_builder_fn):
278
  """Decorator that runs hooks before and after the decorated function.
279

280
  @type hook_opcode: string
281
  @param hook_opcode: opcode of the hook
282
  @type hooks_path: string
283
  @param hooks_path: path of the hooks
284
  @type env_builder_fn: function
285
  @param env_builder_fn: function that returns a dictionary containing the
286
    environment variables for the hooks. Will get all the parameters of the
287
    decorated function.
288
  @raise RPCFail: in case of pre-hook failure
289

290
  """
291
  def decorator(fn):
292
    def wrapper(*args, **kwargs):
293
      _, myself = ssconf.GetMasterAndMyself()
294
      nodes = ([myself], [myself])  # these hooks run locally
295

    
296
      env_fn = compat.partial(env_builder_fn, *args, **kwargs)
297

    
298
      cfg = _GetConfig()
299
      hr = HooksRunner()
300
      hm = mcpu.HooksMaster(hook_opcode, hooks_path, nodes, hr.RunLocalHooks,
301
                            None, env_fn, logging.warning, cfg.GetClusterName(),
302
                            cfg.GetMasterNode())
303

    
304
      hm.RunPhase(constants.HOOKS_PHASE_PRE)
305
      result = fn(*args, **kwargs)
306
      hm.RunPhase(constants.HOOKS_PHASE_POST)
307

    
308
      return result
309
    return wrapper
310
  return decorator
311

    
312

    
313
def _BuildMasterIpEnv(master_params, use_external_mip_script=None):
314
  """Builds environment variables for master IP hooks.
315

316
  @type master_params: L{objects.MasterNetworkParameters}
317
  @param master_params: network parameters of the master
318
  @type use_external_mip_script: boolean
319
  @param use_external_mip_script: whether to use an external master IP
320
    address setup script (unused, but necessary per the implementation of the
321
    _RunLocalHooks decorator)
322

323
  """
324
  # pylint: disable=W0613
325
  ver = netutils.IPAddress.GetVersionFromAddressFamily(master_params.ip_family)
326
  env = {
327
    "MASTER_NETDEV": master_params.netdev,
328
    "MASTER_IP": master_params.ip,
329
    "MASTER_NETMASK": str(master_params.netmask),
330
    "CLUSTER_IP_VERSION": str(ver),
331
  }
332

    
333
  return env
334

    
335

    
336
def _RunMasterSetupScript(master_params, action, use_external_mip_script):
337
  """Execute the master IP address setup script.
338

339
  @type master_params: L{objects.MasterNetworkParameters}
340
  @param master_params: network parameters of the master
341
  @type action: string
342
  @param action: action to pass to the script. Must be one of
343
    L{backend._MASTER_START} or L{backend._MASTER_STOP}
344
  @type use_external_mip_script: boolean
345
  @param use_external_mip_script: whether to use an external master IP
346
    address setup script
347
  @raise backend.RPCFail: if there are errors during the execution of the
348
    script
349

350
  """
351
  env = _BuildMasterIpEnv(master_params)
352

    
353
  if use_external_mip_script:
354
    setup_script = pathutils.EXTERNAL_MASTER_SETUP_SCRIPT
355
  else:
356
    setup_script = pathutils.DEFAULT_MASTER_SETUP_SCRIPT
357

    
358
  result = utils.RunCmd([setup_script, action], env=env, reset_env=True)
359

    
360
  if result.failed:
361
    _Fail("Failed to %s the master IP. Script return value: %s, output: '%s'" %
362
          (action, result.exit_code, result.output), log=True)
363

    
364

    
365
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNUP, "master-ip-turnup",
366
               _BuildMasterIpEnv)
367
def ActivateMasterIp(master_params, use_external_mip_script):
368
  """Activate the IP address of the master daemon.
369

370
  @type master_params: L{objects.MasterNetworkParameters}
371
  @param master_params: network parameters of the master
372
  @type use_external_mip_script: boolean
373
  @param use_external_mip_script: whether to use an external master IP
374
    address setup script
375
  @raise RPCFail: in case of errors during the IP startup
376

377
  """
378
  _RunMasterSetupScript(master_params, _MASTER_START,
379
                        use_external_mip_script)
380

    
381

    
382
def StartMasterDaemons(no_voting):
383
  """Activate local node as master node.
384

385
  The function will start the master daemons (ganeti-masterd and ganeti-rapi).
386

387
  @type no_voting: boolean
388
  @param no_voting: whether to start ganeti-masterd without a node vote
389
      but still non-interactively
390
  @rtype: None
391

392
  """
393

    
394
  if no_voting:
395
    masterd_args = "--no-voting --yes-do-it"
396
  else:
397
    masterd_args = ""
398

    
399
  env = {
400
    "EXTRA_MASTERD_ARGS": masterd_args,
401
    }
402

    
403
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "start-master"], env=env)
404
  if result.failed:
405
    msg = "Can't start Ganeti master: %s" % result.output
406
    logging.error(msg)
407
    _Fail(msg)
408

    
409

    
410
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNDOWN, "master-ip-turndown",
411
               _BuildMasterIpEnv)
412
def DeactivateMasterIp(master_params, use_external_mip_script):
413
  """Deactivate the master IP on this node.
414

415
  @type master_params: L{objects.MasterNetworkParameters}
416
  @param master_params: network parameters of the master
417
  @type use_external_mip_script: boolean
418
  @param use_external_mip_script: whether to use an external master IP
419
    address setup script
420
  @raise RPCFail: in case of errors during the IP turndown
421

422
  """
423
  _RunMasterSetupScript(master_params, _MASTER_STOP,
424
                        use_external_mip_script)
425

    
426

    
427
def StopMasterDaemons():
428
  """Stop the master daemons on this node.
429

430
  Stop the master daemons (ganeti-masterd and ganeti-rapi) on this node.
431

432
  @rtype: None
433

434
  """
435
  # TODO: log and report back to the caller the error failures; we
436
  # need to decide in which case we fail the RPC for this
437

    
438
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop-master"])
439
  if result.failed:
440
    logging.error("Could not stop Ganeti master, command %s had exitcode %s"
441
                  " and error %s",
442
                  result.cmd, result.exit_code, result.output)
443

    
444

    
445
def ChangeMasterNetmask(old_netmask, netmask, master_ip, master_netdev):
446
  """Change the netmask of the master IP.
447

448
  @param old_netmask: the old value of the netmask
449
  @param netmask: the new value of the netmask
450
  @param master_ip: the master IP
451
  @param master_netdev: the master network device
452

453
  """
454
  if old_netmask == netmask:
455
    return
456

    
457
  if not netutils.IPAddress.Own(master_ip):
458
    _Fail("The master IP address is not up, not attempting to change its"
459
          " netmask")
460

    
461
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
462
                         "%s/%s" % (master_ip, netmask),
463
                         "dev", master_netdev, "label",
464
                         "%s:0" % master_netdev])
465
  if result.failed:
466
    _Fail("Could not set the new netmask on the master IP address")
467

    
468
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
469
                         "%s/%s" % (master_ip, old_netmask),
470
                         "dev", master_netdev, "label",
471
                         "%s:0" % master_netdev])
472
  if result.failed:
473
    _Fail("Could not bring down the master IP address with the old netmask")
474

    
475

    
476
def EtcHostsModify(mode, host, ip):
477
  """Modify a host entry in /etc/hosts.
478

479
  @param mode: The mode to operate. Either add or remove entry
480
  @param host: The host to operate on
481
  @param ip: The ip associated with the entry
482

483
  """
484
  if mode == constants.ETC_HOSTS_ADD:
485
    if not ip:
486
      RPCFail("Mode 'add' needs 'ip' parameter, but parameter not"
487
              " present")
488
    utils.AddHostToEtcHosts(host, ip)
489
  elif mode == constants.ETC_HOSTS_REMOVE:
490
    if ip:
491
      RPCFail("Mode 'remove' does not allow 'ip' parameter, but"
492
              " parameter is present")
493
    utils.RemoveHostFromEtcHosts(host)
494
  else:
495
    RPCFail("Mode not supported")
496

    
497

    
498
def LeaveCluster(modify_ssh_setup):
499
  """Cleans up and remove the current node.
500

501
  This function cleans up and prepares the current node to be removed
502
  from the cluster.
503

504
  If processing is successful, then it raises an
505
  L{errors.QuitGanetiException} which is used as a special case to
506
  shutdown the node daemon.
507

508
  @param modify_ssh_setup: boolean
509

510
  """
511
  _CleanDirectory(pathutils.DATA_DIR)
512
  _CleanDirectory(pathutils.CRYPTO_KEYS_DIR)
513
  JobQueuePurge()
514

    
515
  if modify_ssh_setup:
516
    try:
517
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.SSH_LOGIN_USER)
518

    
519
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
520

    
521
      utils.RemoveFile(priv_key)
522
      utils.RemoveFile(pub_key)
523
    except errors.OpExecError:
524
      logging.exception("Error while processing ssh files")
525

    
526
  try:
527
    utils.RemoveFile(pathutils.CONFD_HMAC_KEY)
528
    utils.RemoveFile(pathutils.RAPI_CERT_FILE)
529
    utils.RemoveFile(pathutils.SPICE_CERT_FILE)
530
    utils.RemoveFile(pathutils.SPICE_CACERT_FILE)
531
    utils.RemoveFile(pathutils.NODED_CERT_FILE)
532
  except: # pylint: disable=W0702
533
    logging.exception("Error while removing cluster secrets")
534

    
535
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop", constants.CONFD])
536
  if result.failed:
537
    logging.error("Command %s failed with exitcode %s and error %s",
538
                  result.cmd, result.exit_code, result.output)
539

    
540
  # Raise a custom exception (handled in ganeti-noded)
541
  raise errors.QuitGanetiException(True, "Shutdown scheduled")
542

    
543

    
544
def _GetVgInfo(name, excl_stor):
545
  """Retrieves information about a LVM volume group.
546

547
  """
548
  # TODO: GetVGInfo supports returning information for multiple VGs at once
549
  vginfo = bdev.LogicalVolume.GetVGInfo([name], excl_stor)
550
  if vginfo:
551
    vg_free = int(round(vginfo[0][0], 0))
552
    vg_size = int(round(vginfo[0][1], 0))
553
  else:
554
    vg_free = None
555
    vg_size = None
556

    
557
  return {
558
    "name": name,
559
    "vg_free": vg_free,
560
    "vg_size": vg_size,
561
    }
562

    
563

    
564
def _GetHvInfo(name):
565
  """Retrieves node information from a hypervisor.
566

567
  The information returned depends on the hypervisor. Common items:
568

569
    - vg_size is the size of the configured volume group in MiB
570
    - vg_free is the free size of the volume group in MiB
571
    - memory_dom0 is the memory allocated for domain0 in MiB
572
    - memory_free is the currently available (free) ram in MiB
573
    - memory_total is the total number of ram in MiB
574
    - hv_version: the hypervisor version, if available
575

576
  """
577
  return hypervisor.GetHypervisor(name).GetNodeInfo()
578

    
579

    
580
def _GetNamedNodeInfo(names, fn):
581
  """Calls C{fn} for all names in C{names} and returns a dictionary.
582

583
  @rtype: None or dict
584

585
  """
586
  if names is None:
587
    return None
588
  else:
589
    return map(fn, names)
590

    
591

    
592
def GetNodeInfo(vg_names, hv_names, excl_stor):
593
  """Gives back a hash with different information about the node.
594

595
  @type vg_names: list of string
596
  @param vg_names: Names of the volume groups to ask for disk space information
597
  @type hv_names: list of string
598
  @param hv_names: Names of the hypervisors to ask for node information
599
  @type excl_stor: boolean
600
  @param excl_stor: Whether exclusive_storage is active
601
  @rtype: tuple; (string, None/dict, None/dict)
602
  @return: Tuple containing boot ID, volume group information and hypervisor
603
    information
604

605
  """
606
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
607
  vg_info = _GetNamedNodeInfo(vg_names, (lambda vg: _GetVgInfo(vg, excl_stor)))
608
  hv_info = _GetNamedNodeInfo(hv_names, _GetHvInfo)
609

    
610
  return (bootid, vg_info, hv_info)
611

    
612

    
613
def _CheckExclusivePvs(pvi_list):
614
  """Check that PVs are not shared among LVs
615

616
  @type pvi_list: list of L{objects.LvmPvInfo} objects
617
  @param pvi_list: information about the PVs
618

619
  @rtype: list of tuples (string, list of strings)
620
  @return: offending volumes, as tuples: (pv_name, [lv1_name, lv2_name...])
621

622
  """
623
  res = []
624
  for pvi in pvi_list:
625
    if len(pvi.lv_list) > 1:
626
      res.append((pvi.name, pvi.lv_list))
627
  return res
628

    
629

    
630
def VerifyNode(what, cluster_name):
631
  """Verify the status of the local node.
632

633
  Based on the input L{what} parameter, various checks are done on the
634
  local node.
635

636
  If the I{filelist} key is present, this list of
637
  files is checksummed and the file/checksum pairs are returned.
638

639
  If the I{nodelist} key is present, we check that we have
640
  connectivity via ssh with the target nodes (and check the hostname
641
  report).
642

643
  If the I{node-net-test} key is present, we check that we have
644
  connectivity to the given nodes via both primary IP and, if
645
  applicable, secondary IPs.
646

647
  @type what: C{dict}
648
  @param what: a dictionary of things to check:
649
      - filelist: list of files for which to compute checksums
650
      - nodelist: list of nodes we should check ssh communication with
651
      - node-net-test: list of nodes we should check node daemon port
652
        connectivity with
653
      - hypervisor: list with hypervisors to run the verify for
654
  @rtype: dict
655
  @return: a dictionary with the same keys as the input dict, and
656
      values representing the result of the checks
657

658
  """
659
  result = {}
660
  my_name = netutils.Hostname.GetSysName()
661
  port = netutils.GetDaemonPort(constants.NODED)
662
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
663

    
664
  if constants.NV_HYPERVISOR in what and vm_capable:
665
    result[constants.NV_HYPERVISOR] = tmp = {}
666
    for hv_name in what[constants.NV_HYPERVISOR]:
667
      try:
668
        val = hypervisor.GetHypervisor(hv_name).Verify()
669
      except errors.HypervisorError, err:
670
        val = "Error while checking hypervisor: %s" % str(err)
671
      tmp[hv_name] = val
672

    
673
  if constants.NV_HVPARAMS in what and vm_capable:
674
    result[constants.NV_HVPARAMS] = tmp = []
675
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
676
      try:
677
        logging.info("Validating hv %s, %s", hv_name, hvparms)
678
        hypervisor.GetHypervisor(hv_name).ValidateParameters(hvparms)
679
      except errors.HypervisorError, err:
680
        tmp.append((source, hv_name, str(err)))
681

    
682
  if constants.NV_FILELIST in what:
683
    fingerprints = utils.FingerprintFiles(map(vcluster.LocalizeVirtualPath,
684
                                              what[constants.NV_FILELIST]))
685
    result[constants.NV_FILELIST] = \
686
      dict((vcluster.MakeVirtualPath(key), value)
687
           for (key, value) in fingerprints.items())
688

    
689
  if constants.NV_NODELIST in what:
690
    (nodes, bynode) = what[constants.NV_NODELIST]
691

    
692
    # Add nodes from other groups (different for each node)
693
    try:
694
      nodes.extend(bynode[my_name])
695
    except KeyError:
696
      pass
697

    
698
    # Use a random order
699
    random.shuffle(nodes)
700

    
701
    # Try to contact all nodes
702
    val = {}
703
    for node in nodes:
704
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
705
      if not success:
706
        val[node] = message
707

    
708
    result[constants.NV_NODELIST] = val
709

    
710
  if constants.NV_NODENETTEST in what:
711
    result[constants.NV_NODENETTEST] = tmp = {}
712
    my_pip = my_sip = None
713
    for name, pip, sip in what[constants.NV_NODENETTEST]:
714
      if name == my_name:
715
        my_pip = pip
716
        my_sip = sip
717
        break
718
    if not my_pip:
719
      tmp[my_name] = ("Can't find my own primary/secondary IP"
720
                      " in the node list")
721
    else:
722
      for name, pip, sip in what[constants.NV_NODENETTEST]:
723
        fail = []
724
        if not netutils.TcpPing(pip, port, source=my_pip):
725
          fail.append("primary")
726
        if sip != pip:
727
          if not netutils.TcpPing(sip, port, source=my_sip):
728
            fail.append("secondary")
729
        if fail:
730
          tmp[name] = ("failure using the %s interface(s)" %
731
                       " and ".join(fail))
732

    
733
  if constants.NV_MASTERIP in what:
734
    # FIXME: add checks on incoming data structures (here and in the
735
    # rest of the function)
736
    master_name, master_ip = what[constants.NV_MASTERIP]
737
    if master_name == my_name:
738
      source = constants.IP4_ADDRESS_LOCALHOST
739
    else:
740
      source = None
741
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
742
                                                     source=source)
743

    
744
  if constants.NV_USERSCRIPTS in what:
745
    result[constants.NV_USERSCRIPTS] = \
746
      [script for script in what[constants.NV_USERSCRIPTS]
747
       if not utils.IsExecutable(script)]
748

    
749
  if constants.NV_OOB_PATHS in what:
750
    result[constants.NV_OOB_PATHS] = tmp = []
751
    for path in what[constants.NV_OOB_PATHS]:
752
      try:
753
        st = os.stat(path)
754
      except OSError, err:
755
        tmp.append("error stating out of band helper: %s" % err)
756
      else:
757
        if stat.S_ISREG(st.st_mode):
758
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
759
            tmp.append(None)
760
          else:
761
            tmp.append("out of band helper %s is not executable" % path)
762
        else:
763
          tmp.append("out of band helper %s is not a file" % path)
764

    
765
  if constants.NV_LVLIST in what and vm_capable:
766
    try:
767
      val = GetVolumeList(utils.ListVolumeGroups().keys())
768
    except RPCFail, err:
769
      val = str(err)
770
    result[constants.NV_LVLIST] = val
771

    
772
  if constants.NV_INSTANCELIST in what and vm_capable:
773
    # GetInstanceList can fail
774
    try:
775
      val = GetInstanceList(what[constants.NV_INSTANCELIST])
776
    except RPCFail, err:
777
      val = str(err)
778
    result[constants.NV_INSTANCELIST] = val
779

    
780
  if constants.NV_VGLIST in what and vm_capable:
781
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
782

    
783
  if constants.NV_PVLIST in what and vm_capable:
784
    check_exclusive_pvs = constants.NV_EXCLUSIVEPVS in what
785
    val = bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
786
                                       filter_allocatable=False,
787
                                       include_lvs=check_exclusive_pvs)
788
    if check_exclusive_pvs:
789
      result[constants.NV_EXCLUSIVEPVS] = _CheckExclusivePvs(val)
790
      for pvi in val:
791
        # Avoid sending useless data on the wire
792
        pvi.lv_list = []
793
    result[constants.NV_PVLIST] = map(objects.LvmPvInfo.ToDict, val)
794

    
795
  if constants.NV_VERSION in what:
796
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
797
                                    constants.RELEASE_VERSION)
798

    
799
  if constants.NV_HVINFO in what and vm_capable:
800
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
801
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
802

    
803
  if constants.NV_DRBDLIST in what and vm_capable:
804
    try:
805
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
806
    except errors.BlockDeviceError, err:
807
      logging.warning("Can't get used minors list", exc_info=True)
808
      used_minors = str(err)
809
    result[constants.NV_DRBDLIST] = used_minors
810

    
811
  if constants.NV_DRBDHELPER in what and vm_capable:
812
    status = True
813
    try:
814
      payload = bdev.BaseDRBD.GetUsermodeHelper()
815
    except errors.BlockDeviceError, err:
816
      logging.error("Can't get DRBD usermode helper: %s", str(err))
817
      status = False
818
      payload = str(err)
819
    result[constants.NV_DRBDHELPER] = (status, payload)
820

    
821
  if constants.NV_NODESETUP in what:
822
    result[constants.NV_NODESETUP] = tmpr = []
823
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
824
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
825
                  " under /sys, missing required directories /sys/block"
826
                  " and /sys/class/net")
827
    if (not os.path.isdir("/proc/sys") or
828
        not os.path.isfile("/proc/sysrq-trigger")):
829
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
830
                  " under /proc, missing required directory /proc/sys and"
831
                  " the file /proc/sysrq-trigger")
832

    
833
  if constants.NV_TIME in what:
834
    result[constants.NV_TIME] = utils.SplitTime(time.time())
835

    
836
  if constants.NV_OSLIST in what and vm_capable:
837
    result[constants.NV_OSLIST] = DiagnoseOS()
838

    
839
  if constants.NV_BRIDGES in what and vm_capable:
840
    result[constants.NV_BRIDGES] = [bridge
841
                                    for bridge in what[constants.NV_BRIDGES]
842
                                    if not utils.BridgeExists(bridge)]
843

    
844
  if what.get(constants.NV_FILE_STORAGE_PATHS) == my_name:
845
    result[constants.NV_FILE_STORAGE_PATHS] = \
846
      bdev.ComputeWrongFileStoragePaths()
847

    
848
  return result
849

    
850

    
851
def GetBlockDevSizes(devices):
852
  """Return the size of the given block devices
853

854
  @type devices: list
855
  @param devices: list of block device nodes to query
856
  @rtype: dict
857
  @return:
858
    dictionary of all block devices under /dev (key). The value is their
859
    size in MiB.
860

861
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
862

863
  """
864
  DEV_PREFIX = "/dev/"
865
  blockdevs = {}
866

    
867
  for devpath in devices:
868
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
869
      continue
870

    
871
    try:
872
      st = os.stat(devpath)
873
    except EnvironmentError, err:
874
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
875
      continue
876

    
877
    if stat.S_ISBLK(st.st_mode):
878
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
879
      if result.failed:
880
        # We don't want to fail, just do not list this device as available
881
        logging.warning("Cannot get size for block device %s", devpath)
882
        continue
883

    
884
      size = int(result.stdout) / (1024 * 1024)
885
      blockdevs[devpath] = size
886
  return blockdevs
887

    
888

    
889
def GetVolumeList(vg_names):
890
  """Compute list of logical volumes and their size.
891

892
  @type vg_names: list
893
  @param vg_names: the volume groups whose LVs we should list, or
894
      empty for all volume groups
895
  @rtype: dict
896
  @return:
897
      dictionary of all partions (key) with value being a tuple of
898
      their size (in MiB), inactive and online status::
899

900
        {'xenvg/test1': ('20.06', True, True)}
901

902
      in case of errors, a string is returned with the error
903
      details.
904

905
  """
906
  lvs = {}
907
  sep = "|"
908
  if not vg_names:
909
    vg_names = []
910
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
911
                         "--separator=%s" % sep,
912
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
913
  if result.failed:
914
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
915

    
916
  for line in result.stdout.splitlines():
917
    line = line.strip()
918
    match = _LVSLINE_REGEX.match(line)
919
    if not match:
920
      logging.error("Invalid line returned from lvs output: '%s'", line)
921
      continue
922
    vg_name, name, size, attr = match.groups()
923
    inactive = attr[4] == "-"
924
    online = attr[5] == "o"
925
    virtual = attr[0] == "v"
926
    if virtual:
927
      # we don't want to report such volumes as existing, since they
928
      # don't really hold data
929
      continue
930
    lvs[vg_name + "/" + name] = (size, inactive, online)
931

    
932
  return lvs
933

    
934

    
935
def ListVolumeGroups():
936
  """List the volume groups and their size.
937

938
  @rtype: dict
939
  @return: dictionary with keys volume name and values the
940
      size of the volume
941

942
  """
943
  return utils.ListVolumeGroups()
944

    
945

    
946
def NodeVolumes():
947
  """List all volumes on this node.
948

949
  @rtype: list
950
  @return:
951
    A list of dictionaries, each having four keys:
952
      - name: the logical volume name,
953
      - size: the size of the logical volume
954
      - dev: the physical device on which the LV lives
955
      - vg: the volume group to which it belongs
956

957
    In case of errors, we return an empty list and log the
958
    error.
959

960
    Note that since a logical volume can live on multiple physical
961
    volumes, the resulting list might include a logical volume
962
    multiple times.
963

964
  """
965
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
966
                         "--separator=|",
967
                         "--options=lv_name,lv_size,devices,vg_name"])
968
  if result.failed:
969
    _Fail("Failed to list logical volumes, lvs output: %s",
970
          result.output)
971

    
972
  def parse_dev(dev):
973
    return dev.split("(")[0]
974

    
975
  def handle_dev(dev):
976
    return [parse_dev(x) for x in dev.split(",")]
977

    
978
  def map_line(line):
979
    line = [v.strip() for v in line]
980
    return [{"name": line[0], "size": line[1],
981
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
982

    
983
  all_devs = []
984
  for line in result.stdout.splitlines():
985
    if line.count("|") >= 3:
986
      all_devs.extend(map_line(line.split("|")))
987
    else:
988
      logging.warning("Strange line in the output from lvs: '%s'", line)
989
  return all_devs
990

    
991

    
992
def BridgesExist(bridges_list):
993
  """Check if a list of bridges exist on the current node.
994

995
  @rtype: boolean
996
  @return: C{True} if all of them exist, C{False} otherwise
997

998
  """
999
  missing = []
1000
  for bridge in bridges_list:
1001
    if not utils.BridgeExists(bridge):
1002
      missing.append(bridge)
1003

    
1004
  if missing:
1005
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
1006

    
1007

    
1008
def GetInstanceList(hypervisor_list):
1009
  """Provides a list of instances.
1010

1011
  @type hypervisor_list: list
1012
  @param hypervisor_list: the list of hypervisors to query information
1013

1014
  @rtype: list
1015
  @return: a list of all running instances on the current node
1016
    - instance1.example.com
1017
    - instance2.example.com
1018

1019
  """
1020
  results = []
1021
  for hname in hypervisor_list:
1022
    try:
1023
      names = hypervisor.GetHypervisor(hname).ListInstances()
1024
      results.extend(names)
1025
    except errors.HypervisorError, err:
1026
      _Fail("Error enumerating instances (hypervisor %s): %s",
1027
            hname, err, exc=True)
1028

    
1029
  return results
1030

    
1031

    
1032
def GetInstanceInfo(instance, hname):
1033
  """Gives back the information about an instance as a dictionary.
1034

1035
  @type instance: string
1036
  @param instance: the instance name
1037
  @type hname: string
1038
  @param hname: the hypervisor type of the instance
1039

1040
  @rtype: dict
1041
  @return: dictionary with the following keys:
1042
      - memory: memory size of instance (int)
1043
      - state: xen state of instance (string)
1044
      - time: cpu time of instance (float)
1045
      - vcpus: the number of vcpus (int)
1046

1047
  """
1048
  output = {}
1049

    
1050
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
1051
  if iinfo is not None:
1052
    output["memory"] = iinfo[2]
1053
    output["vcpus"] = iinfo[3]
1054
    output["state"] = iinfo[4]
1055
    output["time"] = iinfo[5]
1056

    
1057
  return output
1058

    
1059

    
1060
def GetInstanceMigratable(instance):
1061
  """Gives whether an instance can be migrated.
1062

1063
  @type instance: L{objects.Instance}
1064
  @param instance: object representing the instance to be checked.
1065

1066
  @rtype: tuple
1067
  @return: tuple of (result, description) where:
1068
      - result: whether the instance can be migrated or not
1069
      - description: a description of the issue, if relevant
1070

1071
  """
1072
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1073
  iname = instance.name
1074
  if iname not in hyper.ListInstances():
1075
    _Fail("Instance %s is not running", iname)
1076

    
1077
  for idx in range(len(instance.disks)):
1078
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1079
    if not os.path.islink(link_name):
1080
      logging.warning("Instance %s is missing symlink %s for disk %d",
1081
                      iname, link_name, idx)
1082

    
1083

    
1084
def GetAllInstancesInfo(hypervisor_list):
1085
  """Gather data about all instances.
1086

1087
  This is the equivalent of L{GetInstanceInfo}, except that it
1088
  computes data for all instances at once, thus being faster if one
1089
  needs data about more than one instance.
1090

1091
  @type hypervisor_list: list
1092
  @param hypervisor_list: list of hypervisors to query for instance data
1093

1094
  @rtype: dict
1095
  @return: dictionary of instance: data, with data having the following keys:
1096
      - memory: memory size of instance (int)
1097
      - state: xen state of instance (string)
1098
      - time: cpu time of instance (float)
1099
      - vcpus: the number of vcpus
1100

1101
  """
1102
  output = {}
1103

    
1104
  for hname in hypervisor_list:
1105
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
1106
    if iinfo:
1107
      for name, _, memory, vcpus, state, times in iinfo:
1108
        value = {
1109
          "memory": memory,
1110
          "vcpus": vcpus,
1111
          "state": state,
1112
          "time": times,
1113
          }
1114
        if name in output:
1115
          # we only check static parameters, like memory and vcpus,
1116
          # and not state and time which can change between the
1117
          # invocations of the different hypervisors
1118
          for key in "memory", "vcpus":
1119
            if value[key] != output[name][key]:
1120
              _Fail("Instance %s is running twice"
1121
                    " with different parameters", name)
1122
        output[name] = value
1123

    
1124
  return output
1125

    
1126

    
1127
def _InstanceLogName(kind, os_name, instance, component):
1128
  """Compute the OS log filename for a given instance and operation.
1129

1130
  The instance name and os name are passed in as strings since not all
1131
  operations have these as part of an instance object.
1132

1133
  @type kind: string
1134
  @param kind: the operation type (e.g. add, import, etc.)
1135
  @type os_name: string
1136
  @param os_name: the os name
1137
  @type instance: string
1138
  @param instance: the name of the instance being imported/added/etc.
1139
  @type component: string or None
1140
  @param component: the name of the component of the instance being
1141
      transferred
1142

1143
  """
1144
  # TODO: Use tempfile.mkstemp to create unique filename
1145
  if component:
1146
    assert "/" not in component
1147
    c_msg = "-%s" % component
1148
  else:
1149
    c_msg = ""
1150
  base = ("%s-%s-%s%s-%s.log" %
1151
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1152
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1153

    
1154

    
1155
def InstanceOsAdd(instance, reinstall, debug):
1156
  """Add an OS to an instance.
1157

1158
  @type instance: L{objects.Instance}
1159
  @param instance: Instance whose OS is to be installed
1160
  @type reinstall: boolean
1161
  @param reinstall: whether this is an instance reinstall
1162
  @type debug: integer
1163
  @param debug: debug level, passed to the OS scripts
1164
  @rtype: None
1165

1166
  """
1167
  inst_os = OSFromDisk(instance.os)
1168

    
1169
  create_env = OSEnvironment(instance, inst_os, debug)
1170
  if reinstall:
1171
    create_env["INSTANCE_REINSTALL"] = "1"
1172

    
1173
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1174

    
1175
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1176
                        cwd=inst_os.path, output=logfile, reset_env=True)
1177
  if result.failed:
1178
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1179
                  " output: %s", result.cmd, result.fail_reason, logfile,
1180
                  result.output)
1181
    lines = [utils.SafeEncode(val)
1182
             for val in utils.TailFile(logfile, lines=20)]
1183
    _Fail("OS create script failed (%s), last lines in the"
1184
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1185

    
1186

    
1187
def RunRenameInstance(instance, old_name, debug):
1188
  """Run the OS rename script for an instance.
1189

1190
  @type instance: L{objects.Instance}
1191
  @param instance: Instance whose OS is to be installed
1192
  @type old_name: string
1193
  @param old_name: previous instance name
1194
  @type debug: integer
1195
  @param debug: debug level, passed to the OS scripts
1196
  @rtype: boolean
1197
  @return: the success of the operation
1198

1199
  """
1200
  inst_os = OSFromDisk(instance.os)
1201

    
1202
  rename_env = OSEnvironment(instance, inst_os, debug)
1203
  rename_env["OLD_INSTANCE_NAME"] = old_name
1204

    
1205
  logfile = _InstanceLogName("rename", instance.os,
1206
                             "%s-%s" % (old_name, instance.name), None)
1207

    
1208
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1209
                        cwd=inst_os.path, output=logfile, reset_env=True)
1210

    
1211
  if result.failed:
1212
    logging.error("os create command '%s' returned error: %s output: %s",
1213
                  result.cmd, result.fail_reason, result.output)
1214
    lines = [utils.SafeEncode(val)
1215
             for val in utils.TailFile(logfile, lines=20)]
1216
    _Fail("OS rename script failed (%s), last lines in the"
1217
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1218

    
1219

    
1220
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1221
  """Returns symlink path for block device.
1222

1223
  """
1224
  if _dir is None:
1225
    _dir = pathutils.DISK_LINKS_DIR
1226

    
1227
  return utils.PathJoin(_dir,
1228
                        ("%s%s%s" %
1229
                         (instance_name, constants.DISK_SEPARATOR, idx)))
1230

    
1231

    
1232
def _SymlinkBlockDev(instance_name, device_path, idx):
1233
  """Set up symlinks to a instance's block device.
1234

1235
  This is an auxiliary function run when an instance is start (on the primary
1236
  node) or when an instance is migrated (on the target node).
1237

1238

1239
  @param instance_name: the name of the target instance
1240
  @param device_path: path of the physical block device, on the node
1241
  @param idx: the disk index
1242
  @return: absolute path to the disk's symlink
1243

1244
  """
1245
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1246
  try:
1247
    os.symlink(device_path, link_name)
1248
  except OSError, err:
1249
    if err.errno == errno.EEXIST:
1250
      if (not os.path.islink(link_name) or
1251
          os.readlink(link_name) != device_path):
1252
        os.remove(link_name)
1253
        os.symlink(device_path, link_name)
1254
    else:
1255
      raise
1256

    
1257
  return link_name
1258

    
1259

    
1260
def _RemoveBlockDevLinks(instance_name, disks):
1261
  """Remove the block device symlinks belonging to the given instance.
1262

1263
  """
1264
  for idx, _ in enumerate(disks):
1265
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1266
    if os.path.islink(link_name):
1267
      try:
1268
        os.remove(link_name)
1269
      except OSError:
1270
        logging.exception("Can't remove symlink '%s'", link_name)
1271

    
1272

    
1273
def _GatherAndLinkBlockDevs(instance):
1274
  """Set up an instance's block device(s).
1275

1276
  This is run on the primary node at instance startup. The block
1277
  devices must be already assembled.
1278

1279
  @type instance: L{objects.Instance}
1280
  @param instance: the instance whose disks we shoul assemble
1281
  @rtype: list
1282
  @return: list of (disk_object, device_path)
1283

1284
  """
1285
  block_devices = []
1286
  for idx, disk in enumerate(instance.disks):
1287
    device = _RecursiveFindBD(disk)
1288
    if device is None:
1289
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1290
                                    str(disk))
1291
    device.Open()
1292
    try:
1293
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1294
    except OSError, e:
1295
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1296
                                    e.strerror)
1297

    
1298
    block_devices.append((disk, link_name))
1299

    
1300
  return block_devices
1301

    
1302

    
1303
def StartInstance(instance, startup_paused):
1304
  """Start an instance.
1305

1306
  @type instance: L{objects.Instance}
1307
  @param instance: the instance object
1308
  @type startup_paused: bool
1309
  @param instance: pause instance at startup?
1310
  @rtype: None
1311

1312
  """
1313
  running_instances = GetInstanceList([instance.hypervisor])
1314

    
1315
  if instance.name in running_instances:
1316
    logging.info("Instance %s already running, not starting", instance.name)
1317
    return
1318

    
1319
  try:
1320
    block_devices = _GatherAndLinkBlockDevs(instance)
1321
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1322
    hyper.StartInstance(instance, block_devices, startup_paused)
1323
  except errors.BlockDeviceError, err:
1324
    _Fail("Block device error: %s", err, exc=True)
1325
  except errors.HypervisorError, err:
1326
    _RemoveBlockDevLinks(instance.name, instance.disks)
1327
    _Fail("Hypervisor error: %s", err, exc=True)
1328

    
1329

    
1330
def InstanceShutdown(instance, timeout):
1331
  """Shut an instance down.
1332

1333
  @note: this functions uses polling with a hardcoded timeout.
1334

1335
  @type instance: L{objects.Instance}
1336
  @param instance: the instance object
1337
  @type timeout: integer
1338
  @param timeout: maximum timeout for soft shutdown
1339
  @rtype: None
1340

1341
  """
1342
  hv_name = instance.hypervisor
1343
  hyper = hypervisor.GetHypervisor(hv_name)
1344
  iname = instance.name
1345

    
1346
  if instance.name not in hyper.ListInstances():
1347
    logging.info("Instance %s not running, doing nothing", iname)
1348
    return
1349

    
1350
  class _TryShutdown:
1351
    def __init__(self):
1352
      self.tried_once = False
1353

    
1354
    def __call__(self):
1355
      if iname not in hyper.ListInstances():
1356
        return
1357

    
1358
      try:
1359
        hyper.StopInstance(instance, retry=self.tried_once)
1360
      except errors.HypervisorError, err:
1361
        if iname not in hyper.ListInstances():
1362
          # if the instance is no longer existing, consider this a
1363
          # success and go to cleanup
1364
          return
1365

    
1366
        _Fail("Failed to stop instance %s: %s", iname, err)
1367

    
1368
      self.tried_once = True
1369

    
1370
      raise utils.RetryAgain()
1371

    
1372
  try:
1373
    utils.Retry(_TryShutdown(), 5, timeout)
1374
  except utils.RetryTimeout:
1375
    # the shutdown did not succeed
1376
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1377

    
1378
    try:
1379
      hyper.StopInstance(instance, force=True)
1380
    except errors.HypervisorError, err:
1381
      if iname in hyper.ListInstances():
1382
        # only raise an error if the instance still exists, otherwise
1383
        # the error could simply be "instance ... unknown"!
1384
        _Fail("Failed to force stop instance %s: %s", iname, err)
1385

    
1386
    time.sleep(1)
1387

    
1388
    if iname in hyper.ListInstances():
1389
      _Fail("Could not shutdown instance %s even by destroy", iname)
1390

    
1391
  try:
1392
    hyper.CleanupInstance(instance.name)
1393
  except errors.HypervisorError, err:
1394
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1395

    
1396
  _RemoveBlockDevLinks(iname, instance.disks)
1397

    
1398

    
1399
def InstanceReboot(instance, reboot_type, shutdown_timeout):
1400
  """Reboot an instance.
1401

1402
  @type instance: L{objects.Instance}
1403
  @param instance: the instance object to reboot
1404
  @type reboot_type: str
1405
  @param reboot_type: the type of reboot, one the following
1406
    constants:
1407
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1408
        instance OS, do not recreate the VM
1409
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1410
        restart the VM (at the hypervisor level)
1411
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1412
        not accepted here, since that mode is handled differently, in
1413
        cmdlib, and translates into full stop and start of the
1414
        instance (instead of a call_instance_reboot RPC)
1415
  @type shutdown_timeout: integer
1416
  @param shutdown_timeout: maximum timeout for soft shutdown
1417
  @rtype: None
1418

1419
  """
1420
  running_instances = GetInstanceList([instance.hypervisor])
1421

    
1422
  if instance.name not in running_instances:
1423
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1424

    
1425
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1426
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1427
    try:
1428
      hyper.RebootInstance(instance)
1429
    except errors.HypervisorError, err:
1430
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1431
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1432
    try:
1433
      InstanceShutdown(instance, shutdown_timeout)
1434
      return StartInstance(instance, False)
1435
    except errors.HypervisorError, err:
1436
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1437
  else:
1438
    _Fail("Invalid reboot_type received: %s", reboot_type)
1439

    
1440

    
1441
def InstanceBalloonMemory(instance, memory):
1442
  """Resize an instance's memory.
1443

1444
  @type instance: L{objects.Instance}
1445
  @param instance: the instance object
1446
  @type memory: int
1447
  @param memory: new memory amount in MB
1448
  @rtype: None
1449

1450
  """
1451
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1452
  running = hyper.ListInstances()
1453
  if instance.name not in running:
1454
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1455
    return
1456
  try:
1457
    hyper.BalloonInstanceMemory(instance, memory)
1458
  except errors.HypervisorError, err:
1459
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1460

    
1461

    
1462
def MigrationInfo(instance):
1463
  """Gather information about an instance to be migrated.
1464

1465
  @type instance: L{objects.Instance}
1466
  @param instance: the instance definition
1467

1468
  """
1469
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1470
  try:
1471
    info = hyper.MigrationInfo(instance)
1472
  except errors.HypervisorError, err:
1473
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1474
  return info
1475

    
1476

    
1477
def AcceptInstance(instance, info, target):
1478
  """Prepare the node to accept an instance.
1479

1480
  @type instance: L{objects.Instance}
1481
  @param instance: the instance definition
1482
  @type info: string/data (opaque)
1483
  @param info: migration information, from the source node
1484
  @type target: string
1485
  @param target: target host (usually ip), on this node
1486

1487
  """
1488
  # TODO: why is this required only for DTS_EXT_MIRROR?
1489
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1490
    # Create the symlinks, as the disks are not active
1491
    # in any way
1492
    try:
1493
      _GatherAndLinkBlockDevs(instance)
1494
    except errors.BlockDeviceError, err:
1495
      _Fail("Block device error: %s", err, exc=True)
1496

    
1497
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1498
  try:
1499
    hyper.AcceptInstance(instance, info, target)
1500
  except errors.HypervisorError, err:
1501
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1502
      _RemoveBlockDevLinks(instance.name, instance.disks)
1503
    _Fail("Failed to accept instance: %s", err, exc=True)
1504

    
1505

    
1506
def FinalizeMigrationDst(instance, info, success):
1507
  """Finalize any preparation to accept an instance.
1508

1509
  @type instance: L{objects.Instance}
1510
  @param instance: the instance definition
1511
  @type info: string/data (opaque)
1512
  @param info: migration information, from the source node
1513
  @type success: boolean
1514
  @param success: whether the migration was a success or a failure
1515

1516
  """
1517
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1518
  try:
1519
    hyper.FinalizeMigrationDst(instance, info, success)
1520
  except errors.HypervisorError, err:
1521
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1522

    
1523

    
1524
def MigrateInstance(instance, target, live):
1525
  """Migrates an instance to another node.
1526

1527
  @type instance: L{objects.Instance}
1528
  @param instance: the instance definition
1529
  @type target: string
1530
  @param target: the target node name
1531
  @type live: boolean
1532
  @param live: whether the migration should be done live or not (the
1533
      interpretation of this parameter is left to the hypervisor)
1534
  @raise RPCFail: if migration fails for some reason
1535

1536
  """
1537
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1538

    
1539
  try:
1540
    hyper.MigrateInstance(instance, target, live)
1541
  except errors.HypervisorError, err:
1542
    _Fail("Failed to migrate instance: %s", err, exc=True)
1543

    
1544

    
1545
def FinalizeMigrationSource(instance, success, live):
1546
  """Finalize the instance migration on the source node.
1547

1548
  @type instance: L{objects.Instance}
1549
  @param instance: the instance definition of the migrated instance
1550
  @type success: bool
1551
  @param success: whether the migration succeeded or not
1552
  @type live: bool
1553
  @param live: whether the user requested a live migration or not
1554
  @raise RPCFail: If the execution fails for some reason
1555

1556
  """
1557
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1558

    
1559
  try:
1560
    hyper.FinalizeMigrationSource(instance, success, live)
1561
  except Exception, err:  # pylint: disable=W0703
1562
    _Fail("Failed to finalize the migration on the source node: %s", err,
1563
          exc=True)
1564

    
1565

    
1566
def GetMigrationStatus(instance):
1567
  """Get the migration status
1568

1569
  @type instance: L{objects.Instance}
1570
  @param instance: the instance that is being migrated
1571
  @rtype: L{objects.MigrationStatus}
1572
  @return: the status of the current migration (one of
1573
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1574
           progress info that can be retrieved from the hypervisor
1575
  @raise RPCFail: If the migration status cannot be retrieved
1576

1577
  """
1578
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1579
  try:
1580
    return hyper.GetMigrationStatus(instance)
1581
  except Exception, err:  # pylint: disable=W0703
1582
    _Fail("Failed to get migration status: %s", err, exc=True)
1583

    
1584
def HotAddDisk(instance, disk, dev_path, seq):
1585
  """Hot add a nic
1586

1587
  """
1588
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1589
  return hyper.HotAddDisk(instance, disk, dev_path, seq)
1590

    
1591
def HotDelDisk(instance, disk, seq):
1592
  """Hot add a nic
1593

1594
  """
1595
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1596
  return hyper.HotDelDisk(instance, disk, seq)
1597

    
1598
def HotAddNic(instance, nic, seq):
1599
  """Hot add a nic
1600

1601
  """
1602
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1603
  return hyper.HotAddNic(instance, nic, seq)
1604

    
1605
def HotDelNic(instance, nic, seq):
1606
  """Hot add a nic
1607

1608
  """
1609
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1610
  return hyper.HotDelNic(instance, nic, seq)
1611

    
1612

    
1613
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
1614
  """Creates a block device for an instance.
1615

1616
  @type disk: L{objects.Disk}
1617
  @param disk: the object describing the disk we should create
1618
  @type size: int
1619
  @param size: the size of the physical underlying device, in MiB
1620
  @type owner: str
1621
  @param owner: the name of the instance for which disk is created,
1622
      used for device cache data
1623
  @type on_primary: boolean
1624
  @param on_primary:  indicates if it is the primary node or not
1625
  @type info: string
1626
  @param info: string that will be sent to the physical device
1627
      creation, used for example to set (LVM) tags on LVs
1628
  @type excl_stor: boolean
1629
  @param excl_stor: Whether exclusive_storage is active
1630

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

1635
  """
1636
  # TODO: remove the obsolete "size" argument
1637
  # pylint: disable=W0613
1638
  clist = []
1639
  if disk.children:
1640
    for child in disk.children:
1641
      try:
1642
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1643
      except errors.BlockDeviceError, err:
1644
        _Fail("Can't assemble device %s: %s", child, err)
1645
      if on_primary or disk.AssembleOnSecondary():
1646
        # we need the children open in case the device itself has to
1647
        # be assembled
1648
        try:
1649
          # pylint: disable=E1103
1650
          crdev.Open()
1651
        except errors.BlockDeviceError, err:
1652
          _Fail("Can't make child '%s' read-write: %s", child, err)
1653
      clist.append(crdev)
1654

    
1655
  try:
1656
    device = bdev.Create(disk, clist, excl_stor)
1657
  except errors.BlockDeviceError, err:
1658
    _Fail("Can't create block device: %s", err)
1659

    
1660
  if on_primary or disk.AssembleOnSecondary():
1661
    try:
1662
      device.Assemble()
1663
    except errors.BlockDeviceError, err:
1664
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1665
    if on_primary or disk.OpenOnSecondary():
1666
      try:
1667
        device.Open(force=True)
1668
      except errors.BlockDeviceError, err:
1669
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1670
    DevCacheManager.UpdateCache(device.dev_path, owner,
1671
                                on_primary, disk.iv_name)
1672

    
1673
  device.SetInfo(info)
1674

    
1675
  return device.unique_id
1676

    
1677

    
1678
def _WipeDevice(path, offset, size):
1679
  """This function actually wipes the device.
1680

1681
  @param path: The path to the device to wipe
1682
  @param offset: The offset in MiB in the file
1683
  @param size: The size in MiB to write
1684

1685
  """
1686
  # Internal sizes are always in Mebibytes; if the following "dd" command
1687
  # should use a different block size the offset and size given to this
1688
  # function must be adjusted accordingly before being passed to "dd".
1689
  block_size = 1024 * 1024
1690

    
1691
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1692
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
1693
         "count=%d" % size]
1694
  result = utils.RunCmd(cmd)
1695

    
1696
  if result.failed:
1697
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1698
          result.fail_reason, result.output)
1699

    
1700

    
1701
def BlockdevWipe(disk, offset, size):
1702
  """Wipes a block device.
1703

1704
  @type disk: L{objects.Disk}
1705
  @param disk: the disk object we want to wipe
1706
  @type offset: int
1707
  @param offset: The offset in MiB in the file
1708
  @type size: int
1709
  @param size: The size in MiB to write
1710

1711
  """
1712
  try:
1713
    rdev = _RecursiveFindBD(disk)
1714
  except errors.BlockDeviceError:
1715
    rdev = None
1716

    
1717
  if not rdev:
1718
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1719

    
1720
  # Do cross verify some of the parameters
1721
  if offset < 0:
1722
    _Fail("Negative offset")
1723
  if size < 0:
1724
    _Fail("Negative size")
1725
  if offset > rdev.size:
1726
    _Fail("Offset is bigger than device size")
1727
  if (offset + size) > rdev.size:
1728
    _Fail("The provided offset and size to wipe is bigger than device size")
1729

    
1730
  _WipeDevice(rdev.dev_path, offset, size)
1731

    
1732

    
1733
def BlockdevPauseResumeSync(disks, pause):
1734
  """Pause or resume the sync of the block device.
1735

1736
  @type disks: list of L{objects.Disk}
1737
  @param disks: the disks object we want to pause/resume
1738
  @type pause: bool
1739
  @param pause: Wheater to pause or resume
1740

1741
  """
1742
  success = []
1743
  for disk in disks:
1744
    try:
1745
      rdev = _RecursiveFindBD(disk)
1746
    except errors.BlockDeviceError:
1747
      rdev = None
1748

    
1749
    if not rdev:
1750
      success.append((False, ("Cannot change sync for device %s:"
1751
                              " device not found" % disk.iv_name)))
1752
      continue
1753

    
1754
    result = rdev.PauseResumeSync(pause)
1755

    
1756
    if result:
1757
      success.append((result, None))
1758
    else:
1759
      if pause:
1760
        msg = "Pause"
1761
      else:
1762
        msg = "Resume"
1763
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1764

    
1765
  return success
1766

    
1767

    
1768
def BlockdevRemove(disk):
1769
  """Remove a block device.
1770

1771
  @note: This is intended to be called recursively.
1772

1773
  @type disk: L{objects.Disk}
1774
  @param disk: the disk object we should remove
1775
  @rtype: boolean
1776
  @return: the success of the operation
1777

1778
  """
1779
  msgs = []
1780
  try:
1781
    rdev = _RecursiveFindBD(disk)
1782
  except errors.BlockDeviceError, err:
1783
    # probably can't attach
1784
    logging.info("Can't attach to device %s in remove", disk)
1785
    rdev = None
1786
  if rdev is not None:
1787
    r_path = rdev.dev_path
1788
    try:
1789
      rdev.Remove()
1790
    except errors.BlockDeviceError, err:
1791
      msgs.append(str(err))
1792
    if not msgs:
1793
      DevCacheManager.RemoveCache(r_path)
1794

    
1795
  if disk.children:
1796
    for child in disk.children:
1797
      try:
1798
        BlockdevRemove(child)
1799
      except RPCFail, err:
1800
        msgs.append(str(err))
1801

    
1802
  if msgs:
1803
    _Fail("; ".join(msgs))
1804

    
1805

    
1806
def _RecursiveAssembleBD(disk, owner, as_primary):
1807
  """Activate a block device for an instance.
1808

1809
  This is run on the primary and secondary nodes for an instance.
1810

1811
  @note: this function is called recursively.
1812

1813
  @type disk: L{objects.Disk}
1814
  @param disk: the disk we try to assemble
1815
  @type owner: str
1816
  @param owner: the name of the instance which owns the disk
1817
  @type as_primary: boolean
1818
  @param as_primary: if we should make the block device
1819
      read/write
1820

1821
  @return: the assembled device or None (in case no device
1822
      was assembled)
1823
  @raise errors.BlockDeviceError: in case there is an error
1824
      during the activation of the children or the device
1825
      itself
1826

1827
  """
1828
  children = []
1829
  if disk.children:
1830
    mcn = disk.ChildrenNeeded()
1831
    if mcn == -1:
1832
      mcn = 0 # max number of Nones allowed
1833
    else:
1834
      mcn = len(disk.children) - mcn # max number of Nones
1835
    for chld_disk in disk.children:
1836
      try:
1837
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1838
      except errors.BlockDeviceError, err:
1839
        if children.count(None) >= mcn:
1840
          raise
1841
        cdev = None
1842
        logging.error("Error in child activation (but continuing): %s",
1843
                      str(err))
1844
      children.append(cdev)
1845

    
1846
  if as_primary or disk.AssembleOnSecondary():
1847
    r_dev = bdev.Assemble(disk, children)
1848
    result = r_dev
1849
    if as_primary or disk.OpenOnSecondary():
1850
      r_dev.Open()
1851
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1852
                                as_primary, disk.iv_name)
1853

    
1854
  else:
1855
    result = True
1856
  return result
1857

    
1858

    
1859
def BlockdevAssemble(disk, owner, as_primary, idx):
1860
  """Activate a block device for an instance.
1861

1862
  This is a wrapper over _RecursiveAssembleBD.
1863

1864
  @rtype: str or boolean
1865
  @return: a C{/dev/...} path for primary nodes, and
1866
      C{True} for secondary nodes
1867

1868
  """
1869
  try:
1870
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1871
    if isinstance(result, bdev.BlockDev):
1872
      # pylint: disable=E1103
1873
      result = result.dev_path
1874
      if as_primary:
1875
        _SymlinkBlockDev(owner, result, idx)
1876
  except errors.BlockDeviceError, err:
1877
    _Fail("Error while assembling disk: %s", err, exc=True)
1878
  except OSError, err:
1879
    _Fail("Error while symlinking disk: %s", err, exc=True)
1880

    
1881
  return result
1882

    
1883

    
1884
def BlockdevShutdown(disk):
1885
  """Shut down a block device.
1886

1887
  First, if the device is assembled (Attach() is successful), then
1888
  the device is shutdown. Then the children of the device are
1889
  shutdown.
1890

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

1895
  @type disk: L{objects.Disk}
1896
  @param disk: the description of the disk we should
1897
      shutdown
1898
  @rtype: None
1899

1900
  """
1901
  msgs = []
1902
  r_dev = _RecursiveFindBD(disk)
1903
  if r_dev is not None:
1904
    r_path = r_dev.dev_path
1905
    try:
1906
      r_dev.Shutdown()
1907
      DevCacheManager.RemoveCache(r_path)
1908
    except errors.BlockDeviceError, err:
1909
      msgs.append(str(err))
1910

    
1911
  if disk.children:
1912
    for child in disk.children:
1913
      try:
1914
        BlockdevShutdown(child)
1915
      except RPCFail, err:
1916
        msgs.append(str(err))
1917

    
1918
  if msgs:
1919
    _Fail("; ".join(msgs))
1920

    
1921

    
1922
def BlockdevAddchildren(parent_cdev, new_cdevs):
1923
  """Extend a mirrored block device.
1924

1925
  @type parent_cdev: L{objects.Disk}
1926
  @param parent_cdev: the disk to which we should add children
1927
  @type new_cdevs: list of L{objects.Disk}
1928
  @param new_cdevs: the list of children which we should add
1929
  @rtype: None
1930

1931
  """
1932
  parent_bdev = _RecursiveFindBD(parent_cdev)
1933
  if parent_bdev is None:
1934
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1935
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1936
  if new_bdevs.count(None) > 0:
1937
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1938
  parent_bdev.AddChildren(new_bdevs)
1939

    
1940

    
1941
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1942
  """Shrink a mirrored block device.
1943

1944
  @type parent_cdev: L{objects.Disk}
1945
  @param parent_cdev: the disk from which we should remove children
1946
  @type new_cdevs: list of L{objects.Disk}
1947
  @param new_cdevs: the list of children which we should remove
1948
  @rtype: None
1949

1950
  """
1951
  parent_bdev = _RecursiveFindBD(parent_cdev)
1952
  if parent_bdev is None:
1953
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1954
  devs = []
1955
  for disk in new_cdevs:
1956
    rpath = disk.StaticDevPath()
1957
    if rpath is None:
1958
      bd = _RecursiveFindBD(disk)
1959
      if bd is None:
1960
        _Fail("Can't find device %s while removing children", disk)
1961
      else:
1962
        devs.append(bd.dev_path)
1963
    else:
1964
      if not utils.IsNormAbsPath(rpath):
1965
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
1966
      devs.append(rpath)
1967
  parent_bdev.RemoveChildren(devs)
1968

    
1969

    
1970
def BlockdevGetmirrorstatus(disks):
1971
  """Get the mirroring status of a list of devices.
1972

1973
  @type disks: list of L{objects.Disk}
1974
  @param disks: the list of disks which we should query
1975
  @rtype: disk
1976
  @return: List of L{objects.BlockDevStatus}, one for each disk
1977
  @raise errors.BlockDeviceError: if any of the disks cannot be
1978
      found
1979

1980
  """
1981
  stats = []
1982
  for dsk in disks:
1983
    rbd = _RecursiveFindBD(dsk)
1984
    if rbd is None:
1985
      _Fail("Can't find device %s", dsk)
1986

    
1987
    stats.append(rbd.CombinedSyncStatus())
1988

    
1989
  return stats
1990

    
1991

    
1992
def BlockdevGetmirrorstatusMulti(disks):
1993
  """Get the mirroring status of a list of devices.
1994

1995
  @type disks: list of L{objects.Disk}
1996
  @param disks: the list of disks which we should query
1997
  @rtype: disk
1998
  @return: List of tuples, (bool, status), one for each disk; bool denotes
1999
    success/failure, status is L{objects.BlockDevStatus} on success, string
2000
    otherwise
2001

2002
  """
2003
  result = []
2004
  for disk in disks:
2005
    try:
2006
      rbd = _RecursiveFindBD(disk)
2007
      if rbd is None:
2008
        result.append((False, "Can't find device %s" % disk))
2009
        continue
2010

    
2011
      status = rbd.CombinedSyncStatus()
2012
    except errors.BlockDeviceError, err:
2013
      logging.exception("Error while getting disk status")
2014
      result.append((False, str(err)))
2015
    else:
2016
      result.append((True, status))
2017

    
2018
  assert len(disks) == len(result)
2019

    
2020
  return result
2021

    
2022

    
2023
def _RecursiveFindBD(disk):
2024
  """Check if a device is activated.
2025

2026
  If so, return information about the real device.
2027

2028
  @type disk: L{objects.Disk}
2029
  @param disk: the disk object we need to find
2030

2031
  @return: None if the device can't be found,
2032
      otherwise the device instance
2033

2034
  """
2035
  children = []
2036
  if disk.children:
2037
    for chdisk in disk.children:
2038
      children.append(_RecursiveFindBD(chdisk))
2039

    
2040
  return bdev.FindDevice(disk, children)
2041

    
2042

    
2043
def _OpenRealBD(disk):
2044
  """Opens the underlying block device of a disk.
2045

2046
  @type disk: L{objects.Disk}
2047
  @param disk: the disk object we want to open
2048

2049
  """
2050
  real_disk = _RecursiveFindBD(disk)
2051
  if real_disk is None:
2052
    _Fail("Block device '%s' is not set up", disk)
2053

    
2054
  real_disk.Open()
2055

    
2056
  return real_disk
2057

    
2058

    
2059
def BlockdevFind(disk):
2060
  """Check if a device is activated.
2061

2062
  If it is, return information about the real device.
2063

2064
  @type disk: L{objects.Disk}
2065
  @param disk: the disk to find
2066
  @rtype: None or objects.BlockDevStatus
2067
  @return: None if the disk cannot be found, otherwise a the current
2068
           information
2069

2070
  """
2071
  try:
2072
    rbd = _RecursiveFindBD(disk)
2073
  except errors.BlockDeviceError, err:
2074
    _Fail("Failed to find device: %s", err, exc=True)
2075

    
2076
  if rbd is None:
2077
    return None
2078

    
2079
  return rbd.GetSyncStatus()
2080

    
2081

    
2082
def BlockdevGetsize(disks):
2083
  """Computes the size of the given disks.
2084

2085
  If a disk is not found, returns None instead.
2086

2087
  @type disks: list of L{objects.Disk}
2088
  @param disks: the list of disk to compute the size for
2089
  @rtype: list
2090
  @return: list with elements None if the disk cannot be found,
2091
      otherwise the size
2092

2093
  """
2094
  result = []
2095
  for cf in disks:
2096
    try:
2097
      rbd = _RecursiveFindBD(cf)
2098
    except errors.BlockDeviceError:
2099
      result.append(None)
2100
      continue
2101
    if rbd is None:
2102
      result.append(None)
2103
    else:
2104
      result.append(rbd.GetActualSize())
2105
  return result
2106

    
2107

    
2108
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2109
  """Export a block device to a remote node.
2110

2111
  @type disk: L{objects.Disk}
2112
  @param disk: the description of the disk to export
2113
  @type dest_node: str
2114
  @param dest_node: the destination node to export to
2115
  @type dest_path: str
2116
  @param dest_path: the destination path on the target node
2117
  @type cluster_name: str
2118
  @param cluster_name: the cluster name, needed for SSH hostalias
2119
  @rtype: None
2120

2121
  """
2122
  real_disk = _OpenRealBD(disk)
2123

    
2124
  # the block size on the read dd is 1MiB to match our units
2125
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2126
                               "dd if=%s bs=1048576 count=%s",
2127
                               real_disk.dev_path, str(disk.size))
2128

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

    
2138
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2139
                                                   constants.SSH_LOGIN_USER,
2140
                                                   destcmd)
2141

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

    
2145
  result = utils.RunCmd(["bash", "-c", command])
2146

    
2147
  if result.failed:
2148
    _Fail("Disk copy command '%s' returned error: %s"
2149
          " output: %s", command, result.fail_reason, result.output)
2150

    
2151

    
2152
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2153
  """Write a file to the filesystem.
2154

2155
  This allows the master to overwrite(!) a file. It will only perform
2156
  the operation if the file belongs to a list of configuration files.
2157

2158
  @type file_name: str
2159
  @param file_name: the target file name
2160
  @type data: str
2161
  @param data: the new contents of the file
2162
  @type mode: int
2163
  @param mode: the mode to give the file (can be None)
2164
  @type uid: string
2165
  @param uid: the owner of the file
2166
  @type gid: string
2167
  @param gid: the group of the file
2168
  @type atime: float
2169
  @param atime: the atime to set on the file (can be None)
2170
  @type mtime: float
2171
  @param mtime: the mtime to set on the file (can be None)
2172
  @rtype: None
2173

2174
  """
2175
  file_name = vcluster.LocalizeVirtualPath(file_name)
2176

    
2177
  if not os.path.isabs(file_name):
2178
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2179

    
2180
  if file_name not in _ALLOWED_UPLOAD_FILES:
2181
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2182
          file_name)
2183

    
2184
  raw_data = _Decompress(data)
2185

    
2186
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2187
    _Fail("Invalid username/groupname type")
2188

    
2189
  getents = runtime.GetEnts()
2190
  uid = getents.LookupUser(uid)
2191
  gid = getents.LookupGroup(gid)
2192

    
2193
  utils.SafeWriteFile(file_name, None,
2194
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2195
                      atime=atime, mtime=mtime)
2196

    
2197

    
2198
def RunOob(oob_program, command, node, timeout):
2199
  """Executes oob_program with given command on given node.
2200

2201
  @param oob_program: The path to the executable oob_program
2202
  @param command: The command to invoke on oob_program
2203
  @param node: The node given as an argument to the program
2204
  @param timeout: Timeout after which we kill the oob program
2205

2206
  @return: stdout
2207
  @raise RPCFail: If execution fails for some reason
2208

2209
  """
2210
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2211

    
2212
  if result.failed:
2213
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2214
          result.fail_reason, result.output)
2215

    
2216
  return result.stdout
2217

    
2218

    
2219
def _OSOndiskAPIVersion(os_dir):
2220
  """Compute and return the API version of a given OS.
2221

2222
  This function will try to read the API version of the OS residing in
2223
  the 'os_dir' directory.
2224

2225
  @type os_dir: str
2226
  @param os_dir: the directory in which we should look for the OS
2227
  @rtype: tuple
2228
  @return: tuple (status, data) with status denoting the validity and
2229
      data holding either the vaid versions or an error message
2230

2231
  """
2232
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2233

    
2234
  try:
2235
    st = os.stat(api_file)
2236
  except EnvironmentError, err:
2237
    return False, ("Required file '%s' not found under path %s: %s" %
2238
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2239

    
2240
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2241
    return False, ("File '%s' in %s is not a regular file" %
2242
                   (constants.OS_API_FILE, os_dir))
2243

    
2244
  try:
2245
    api_versions = utils.ReadFile(api_file).splitlines()
2246
  except EnvironmentError, err:
2247
    return False, ("Error while reading the API version file at %s: %s" %
2248
                   (api_file, utils.ErrnoOrStr(err)))
2249

    
2250
  try:
2251
    api_versions = [int(version.strip()) for version in api_versions]
2252
  except (TypeError, ValueError), err:
2253
    return False, ("API version(s) can't be converted to integer: %s" %
2254
                   str(err))
2255

    
2256
  return True, api_versions
2257

    
2258

    
2259
def DiagnoseOS(top_dirs=None):
2260
  """Compute the validity for all OSes.
2261

2262
  @type top_dirs: list
2263
  @param top_dirs: the list of directories in which to
2264
      search (if not given defaults to
2265
      L{pathutils.OS_SEARCH_PATH})
2266
  @rtype: list of L{objects.OS}
2267
  @return: a list of tuples (name, path, status, diagnose, variants,
2268
      parameters, api_version) for all (potential) OSes under all
2269
      search paths, where:
2270
          - name is the (potential) OS name
2271
          - path is the full path to the OS
2272
          - status True/False is the validity of the OS
2273
          - diagnose is the error message for an invalid OS, otherwise empty
2274
          - variants is a list of supported OS variants, if any
2275
          - parameters is a list of (name, help) parameters, if any
2276
          - api_version is a list of support OS API versions
2277

2278
  """
2279
  if top_dirs is None:
2280
    top_dirs = pathutils.OS_SEARCH_PATH
2281

    
2282
  result = []
2283
  for dir_name in top_dirs:
2284
    if os.path.isdir(dir_name):
2285
      try:
2286
        f_names = utils.ListVisibleFiles(dir_name)
2287
      except EnvironmentError, err:
2288
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2289
        break
2290
      for name in f_names:
2291
        os_path = utils.PathJoin(dir_name, name)
2292
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2293
        if status:
2294
          diagnose = ""
2295
          variants = os_inst.supported_variants
2296
          parameters = os_inst.supported_parameters
2297
          api_versions = os_inst.api_versions
2298
        else:
2299
          diagnose = os_inst
2300
          variants = parameters = api_versions = []
2301
        result.append((name, os_path, status, diagnose, variants,
2302
                       parameters, api_versions))
2303

    
2304
  return result
2305

    
2306

    
2307
def _TryOSFromDisk(name, base_dir=None):
2308
  """Create an OS instance from disk.
2309

2310
  This function will return an OS instance if the given name is a
2311
  valid OS name.
2312

2313
  @type base_dir: string
2314
  @keyword base_dir: Base directory containing OS installations.
2315
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2316
  @rtype: tuple
2317
  @return: success and either the OS instance if we find a valid one,
2318
      or error message
2319

2320
  """
2321
  if base_dir is None:
2322
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2323
  else:
2324
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2325

    
2326
  if os_dir is None:
2327
    return False, "Directory for OS %s not found in search path" % name
2328

    
2329
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2330
  if not status:
2331
    # push the error up
2332
    return status, api_versions
2333

    
2334
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2335
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2336
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2337

    
2338
  # OS Files dictionary, we will populate it with the absolute path
2339
  # names; if the value is True, then it is a required file, otherwise
2340
  # an optional one
2341
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2342

    
2343
  if max(api_versions) >= constants.OS_API_V15:
2344
    os_files[constants.OS_VARIANTS_FILE] = False
2345

    
2346
  if max(api_versions) >= constants.OS_API_V20:
2347
    os_files[constants.OS_PARAMETERS_FILE] = True
2348
  else:
2349
    del os_files[constants.OS_SCRIPT_VERIFY]
2350

    
2351
  for (filename, required) in os_files.items():
2352
    os_files[filename] = utils.PathJoin(os_dir, filename)
2353

    
2354
    try:
2355
      st = os.stat(os_files[filename])
2356
    except EnvironmentError, err:
2357
      if err.errno == errno.ENOENT and not required:
2358
        del os_files[filename]
2359
        continue
2360
      return False, ("File '%s' under path '%s' is missing (%s)" %
2361
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2362

    
2363
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2364
      return False, ("File '%s' under path '%s' is not a regular file" %
2365
                     (filename, os_dir))
2366

    
2367
    if filename in constants.OS_SCRIPTS:
2368
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2369
        return False, ("File '%s' under path '%s' is not executable" %
2370
                       (filename, os_dir))
2371

    
2372
  variants = []
2373
  if constants.OS_VARIANTS_FILE in os_files:
2374
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2375
    try:
2376
      variants = \
2377
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2378
    except EnvironmentError, err:
2379
      # we accept missing files, but not other errors
2380
      if err.errno != errno.ENOENT:
2381
        return False, ("Error while reading the OS variants file at %s: %s" %
2382
                       (variants_file, utils.ErrnoOrStr(err)))
2383

    
2384
  parameters = []
2385
  if constants.OS_PARAMETERS_FILE in os_files:
2386
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2387
    try:
2388
      parameters = utils.ReadFile(parameters_file).splitlines()
2389
    except EnvironmentError, err:
2390
      return False, ("Error while reading the OS parameters file at %s: %s" %
2391
                     (parameters_file, utils.ErrnoOrStr(err)))
2392
    parameters = [v.split(None, 1) for v in parameters]
2393

    
2394
  os_obj = objects.OS(name=name, path=os_dir,
2395
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2396
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2397
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2398
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2399
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2400
                                                 None),
2401
                      supported_variants=variants,
2402
                      supported_parameters=parameters,
2403
                      api_versions=api_versions)
2404
  return True, os_obj
2405

    
2406

    
2407
def OSFromDisk(name, base_dir=None):
2408
  """Create an OS instance from disk.
2409

2410
  This function will return an OS instance if the given name is a
2411
  valid OS name. Otherwise, it will raise an appropriate
2412
  L{RPCFail} exception, detailing why this is not a valid OS.
2413

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

2417
  @type base_dir: string
2418
  @keyword base_dir: Base directory containing OS installations.
2419
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2420
  @rtype: L{objects.OS}
2421
  @return: the OS instance if we find a valid one
2422
  @raise RPCFail: if we don't find a valid OS
2423

2424
  """
2425
  name_only = objects.OS.GetName(name)
2426
  status, payload = _TryOSFromDisk(name_only, base_dir)
2427

    
2428
  if not status:
2429
    _Fail(payload)
2430

    
2431
  return payload
2432

    
2433

    
2434
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2435
  """Calculate the basic environment for an os script.
2436

2437
  @type os_name: str
2438
  @param os_name: full operating system name (including variant)
2439
  @type inst_os: L{objects.OS}
2440
  @param inst_os: operating system for which the environment is being built
2441
  @type os_params: dict
2442
  @param os_params: the OS parameters
2443
  @type debug: integer
2444
  @param debug: debug level (0 or 1, for OS Api 10)
2445
  @rtype: dict
2446
  @return: dict of environment variables
2447
  @raise errors.BlockDeviceError: if the block device
2448
      cannot be found
2449

2450
  """
2451
  result = {}
2452
  api_version = \
2453
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2454
  result["OS_API_VERSION"] = "%d" % api_version
2455
  result["OS_NAME"] = inst_os.name
2456
  result["DEBUG_LEVEL"] = "%d" % debug
2457

    
2458
  # OS variants
2459
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2460
    variant = objects.OS.GetVariant(os_name)
2461
    if not variant:
2462
      variant = inst_os.supported_variants[0]
2463
  else:
2464
    variant = ""
2465
  result["OS_VARIANT"] = variant
2466

    
2467
  # OS params
2468
  for pname, pvalue in os_params.items():
2469
    result["OSP_%s" % pname.upper()] = pvalue
2470

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

    
2476
  return result
2477

    
2478

    
2479
def OSEnvironment(instance, inst_os, debug=0):
2480
  """Calculate the environment for an os script.
2481

2482
  @type instance: L{objects.Instance}
2483
  @param instance: target instance for the os script run
2484
  @type inst_os: L{objects.OS}
2485
  @param inst_os: operating system for which the environment is being built
2486
  @type debug: integer
2487
  @param debug: debug level (0 or 1, for OS Api 10)
2488
  @rtype: dict
2489
  @return: dict of environment variables
2490
  @raise errors.BlockDeviceError: if the block device
2491
      cannot be found
2492

2493
  """
2494
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2495

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

    
2499
  result["HYPERVISOR"] = instance.hypervisor
2500
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2501
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2502
  result["INSTANCE_SECONDARY_NODES"] = \
2503
      ("%s" % " ".join(instance.secondary_nodes))
2504

    
2505
  # Disks
2506
  for idx, disk in enumerate(instance.disks):
2507
    real_disk = _OpenRealBD(disk)
2508
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2509
    result["DISK_%d_ACCESS" % idx] = disk.mode
2510
    if constants.HV_DISK_TYPE in instance.hvparams:
2511
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2512
        instance.hvparams[constants.HV_DISK_TYPE]
2513
    if disk.dev_type in constants.LDS_BLOCK:
2514
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2515
    elif disk.dev_type == constants.LD_FILE:
2516
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2517
        "file:%s" % disk.physical_id[0]
2518

    
2519
  # NICs
2520
  for idx, nic in enumerate(instance.nics):
2521
    result["NIC_%d_MAC" % idx] = nic.mac
2522
    if nic.ip:
2523
      result["NIC_%d_IP" % idx] = nic.ip
2524
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2525
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2526
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2527
    if nic.nicparams[constants.NIC_LINK]:
2528
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2529
    if nic.netinfo:
2530
      nobj = objects.Network.FromDict(nic.netinfo)
2531
      result.update(nobj.HooksDict("NIC_%d_" % idx))
2532
    if constants.HV_NIC_TYPE in instance.hvparams:
2533
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2534
        instance.hvparams[constants.HV_NIC_TYPE]
2535

    
2536
  # HV/BE params
2537
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2538
    for key, value in source.items():
2539
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2540

    
2541
  return result
2542

    
2543

    
2544
def DiagnoseExtStorage(top_dirs=None):
2545
  """Compute the validity for all ExtStorage Providers.
2546

2547
  @type top_dirs: list
2548
  @param top_dirs: the list of directories in which to
2549
      search (if not given defaults to
2550
      L{pathutils.ES_SEARCH_PATH})
2551
  @rtype: list of L{objects.ExtStorage}
2552
  @return: a list of tuples (name, path, status, diagnose, parameters)
2553
      for all (potential) ExtStorage Providers under all
2554
      search paths, where:
2555
          - name is the (potential) ExtStorage Provider
2556
          - path is the full path to the ExtStorage Provider
2557
          - status True/False is the validity of the ExtStorage Provider
2558
          - diagnose is the error message for an invalid ExtStorage Provider,
2559
            otherwise empty
2560
          - parameters is a list of (name, help) parameters, if any
2561

2562
  """
2563
  if top_dirs is None:
2564
    top_dirs = pathutils.ES_SEARCH_PATH
2565

    
2566
  result = []
2567
  for dir_name in top_dirs:
2568
    if os.path.isdir(dir_name):
2569
      try:
2570
        f_names = utils.ListVisibleFiles(dir_name)
2571
      except EnvironmentError, err:
2572
        logging.exception("Can't list the ExtStorage directory %s: %s",
2573
                          dir_name, err)
2574
        break
2575
      for name in f_names:
2576
        es_path = utils.PathJoin(dir_name, name)
2577
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2578
        if status:
2579
          diagnose = ""
2580
          parameters = es_inst.supported_parameters
2581
        else:
2582
          diagnose = es_inst
2583
          parameters = []
2584
        result.append((name, es_path, status, diagnose, parameters))
2585

    
2586
  return result
2587

    
2588

    
2589
def BlockdevGrow(disk, amount, dryrun, backingstore):
2590
  """Grow a stack of block devices.
2591

2592
  This function is called recursively, with the childrens being the
2593
  first ones to resize.
2594

2595
  @type disk: L{objects.Disk}
2596
  @param disk: the disk to be grown
2597
  @type amount: integer
2598
  @param amount: the amount (in mebibytes) to grow with
2599
  @type dryrun: boolean
2600
  @param dryrun: whether to execute the operation in simulation mode
2601
      only, without actually increasing the size
2602
  @param backingstore: whether to execute the operation on backing storage
2603
      only, or on "logical" storage only; e.g. DRBD is logical storage,
2604
      whereas LVM, file, RBD are backing storage
2605
  @rtype: (status, result)
2606
  @return: a tuple with the status of the operation (True/False), and
2607
      the errors message if status is False
2608

2609
  """
2610
  r_dev = _RecursiveFindBD(disk)
2611
  if r_dev is None:
2612
    _Fail("Cannot find block device %s", disk)
2613

    
2614
  try:
2615
    r_dev.Grow(amount, dryrun, backingstore)
2616
  except errors.BlockDeviceError, err:
2617
    _Fail("Failed to grow block device: %s", err, exc=True)
2618

    
2619

    
2620
def BlockdevSnapshot(disk):
2621
  """Create a snapshot copy of a block device.
2622

2623
  This function is called recursively, and the snapshot is actually created
2624
  just for the leaf lvm backend device.
2625

2626
  @type disk: L{objects.Disk}
2627
  @param disk: the disk to be snapshotted
2628
  @rtype: string
2629
  @return: snapshot disk ID as (vg, lv)
2630

2631
  """
2632
  if disk.dev_type == constants.LD_DRBD8:
2633
    if not disk.children:
2634
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2635
            disk.unique_id)
2636
    return BlockdevSnapshot(disk.children[0])
2637
  elif disk.dev_type == constants.LD_LV:
2638
    r_dev = _RecursiveFindBD(disk)
2639
    if r_dev is not None:
2640
      # FIXME: choose a saner value for the snapshot size
2641
      # let's stay on the safe side and ask for the full size, for now
2642
      return r_dev.Snapshot(disk.size)
2643
    else:
2644
      _Fail("Cannot find block device %s", disk)
2645
  else:
2646
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2647
          disk.unique_id, disk.dev_type)
2648

    
2649

    
2650
def BlockdevSetInfo(disk, info):
2651
  """Sets 'metadata' information on block devices.
2652

2653
  This function sets 'info' metadata on block devices. Initial
2654
  information is set at device creation; this function should be used
2655
  for example after renames.
2656

2657
  @type disk: L{objects.Disk}
2658
  @param disk: the disk to be grown
2659
  @type info: string
2660
  @param info: new 'info' metadata
2661
  @rtype: (status, result)
2662
  @return: a tuple with the status of the operation (True/False), and
2663
      the errors message if status is False
2664

2665
  """
2666
  r_dev = _RecursiveFindBD(disk)
2667
  if r_dev is None:
2668
    _Fail("Cannot find block device %s", disk)
2669

    
2670
  try:
2671
    r_dev.SetInfo(info)
2672
  except errors.BlockDeviceError, err:
2673
    _Fail("Failed to set information on block device: %s", err, exc=True)
2674

    
2675

    
2676
def FinalizeExport(instance, snap_disks):
2677
  """Write out the export configuration information.
2678

2679
  @type instance: L{objects.Instance}
2680
  @param instance: the instance which we export, used for
2681
      saving configuration
2682
  @type snap_disks: list of L{objects.Disk}
2683
  @param snap_disks: list of snapshot block devices, which
2684
      will be used to get the actual name of the dump file
2685

2686
  @rtype: None
2687

2688
  """
2689
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
2690
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
2691

    
2692
  config = objects.SerializableConfigParser()
2693

    
2694
  config.add_section(constants.INISECT_EXP)
2695
  config.set(constants.INISECT_EXP, "version", "0")
2696
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2697
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2698
  config.set(constants.INISECT_EXP, "os", instance.os)
2699
  config.set(constants.INISECT_EXP, "compression", "none")
2700

    
2701
  config.add_section(constants.INISECT_INS)
2702
  config.set(constants.INISECT_INS, "name", instance.name)
2703
  config.set(constants.INISECT_INS, "maxmem", "%d" %
2704
             instance.beparams[constants.BE_MAXMEM])
2705
  config.set(constants.INISECT_INS, "minmem", "%d" %
2706
             instance.beparams[constants.BE_MINMEM])
2707
  # "memory" is deprecated, but useful for exporting to old ganeti versions
2708
  config.set(constants.INISECT_INS, "memory", "%d" %
2709
             instance.beparams[constants.BE_MAXMEM])
2710
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2711
             instance.beparams[constants.BE_VCPUS])
2712
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2713
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2714
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2715

    
2716
  nic_total = 0
2717
  for nic_count, nic in enumerate(instance.nics):
2718
    nic_total += 1
2719
    config.set(constants.INISECT_INS, "nic%d_mac" %
2720
               nic_count, "%s" % nic.mac)
2721
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2722
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
2723
               "%s" % nic.network)
2724
    for param in constants.NICS_PARAMETER_TYPES:
2725
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2726
                 "%s" % nic.nicparams.get(param, None))
2727
  # TODO: redundant: on load can read nics until it doesn't exist
2728
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2729

    
2730
  disk_total = 0
2731
  for disk_count, disk in enumerate(snap_disks):
2732
    if disk:
2733
      disk_total += 1
2734
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2735
                 ("%s" % disk.iv_name))
2736
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2737
                 ("%s" % disk.physical_id[1]))
2738
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2739
                 ("%d" % disk.size))
2740

    
2741
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2742

    
2743
  # New-style hypervisor/backend parameters
2744

    
2745
  config.add_section(constants.INISECT_HYP)
2746
  for name, value in instance.hvparams.items():
2747
    if name not in constants.HVC_GLOBALS:
2748
      config.set(constants.INISECT_HYP, name, str(value))
2749

    
2750
  config.add_section(constants.INISECT_BEP)
2751
  for name, value in instance.beparams.items():
2752
    config.set(constants.INISECT_BEP, name, str(value))
2753

    
2754
  config.add_section(constants.INISECT_OSP)
2755
  for name, value in instance.osparams.items():
2756
    config.set(constants.INISECT_OSP, name, str(value))
2757

    
2758
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2759
                  data=config.Dumps())
2760
  shutil.rmtree(finaldestdir, ignore_errors=True)
2761
  shutil.move(destdir, finaldestdir)
2762

    
2763

    
2764
def ExportInfo(dest):
2765
  """Get export configuration information.
2766

2767
  @type dest: str
2768
  @param dest: directory containing the export
2769

2770
  @rtype: L{objects.SerializableConfigParser}
2771
  @return: a serializable config file containing the
2772
      export info
2773

2774
  """
2775
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2776

    
2777
  config = objects.SerializableConfigParser()
2778
  config.read(cff)
2779

    
2780
  if (not config.has_section(constants.INISECT_EXP) or
2781
      not config.has_section(constants.INISECT_INS)):
2782
    _Fail("Export info file doesn't have the required fields")
2783

    
2784
  return config.Dumps()
2785

    
2786

    
2787
def ListExports():
2788
  """Return a list of exports currently available on this machine.
2789

2790
  @rtype: list
2791
  @return: list of the exports
2792

2793
  """
2794
  if os.path.isdir(pathutils.EXPORT_DIR):
2795
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
2796
  else:
2797
    _Fail("No exports directory")
2798

    
2799

    
2800
def RemoveExport(export):
2801
  """Remove an existing export from the node.
2802

2803
  @type export: str
2804
  @param export: the name of the export to remove
2805
  @rtype: None
2806

2807
  """
2808
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
2809

    
2810
  try:
2811
    shutil.rmtree(target)
2812
  except EnvironmentError, err:
2813
    _Fail("Error while removing the export: %s", err, exc=True)
2814

    
2815

    
2816
def BlockdevRename(devlist):
2817
  """Rename a list of block devices.
2818

2819
  @type devlist: list of tuples
2820
  @param devlist: list of tuples of the form  (disk,
2821
      new_logical_id, new_physical_id); disk is an
2822
      L{objects.Disk} object describing the current disk,
2823
      and new logical_id/physical_id is the name we
2824
      rename it to
2825
  @rtype: boolean
2826
  @return: True if all renames succeeded, False otherwise
2827

2828
  """
2829
  msgs = []
2830
  result = True
2831
  for disk, unique_id in devlist:
2832
    dev = _RecursiveFindBD(disk)
2833
    if dev is None:
2834
      msgs.append("Can't find device %s in rename" % str(disk))
2835
      result = False
2836
      continue
2837
    try:
2838
      old_rpath = dev.dev_path
2839
      dev.Rename(unique_id)
2840
      new_rpath = dev.dev_path
2841
      if old_rpath != new_rpath:
2842
        DevCacheManager.RemoveCache(old_rpath)
2843
        # FIXME: we should add the new cache information here, like:
2844
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2845
        # but we don't have the owner here - maybe parse from existing
2846
        # cache? for now, we only lose lvm data when we rename, which
2847
        # is less critical than DRBD or MD
2848
    except errors.BlockDeviceError, err:
2849
      msgs.append("Can't rename device '%s' to '%s': %s" %
2850
                  (dev, unique_id, err))
2851
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2852
      result = False
2853
  if not result:
2854
    _Fail("; ".join(msgs))
2855

    
2856

    
2857
def _TransformFileStorageDir(fs_dir):
2858
  """Checks whether given file_storage_dir is valid.
2859

2860
  Checks wheter the given fs_dir is within the cluster-wide default
2861
  file_storage_dir or the shared_file_storage_dir, which are stored in
2862
  SimpleStore. Only paths under those directories are allowed.
2863

2864
  @type fs_dir: str
2865
  @param fs_dir: the path to check
2866

2867
  @return: the normalized path if valid, None otherwise
2868

2869
  """
2870
  if not (constants.ENABLE_FILE_STORAGE or
2871
          constants.ENABLE_SHARED_FILE_STORAGE):
2872
    _Fail("File storage disabled at configure time")
2873

    
2874
  bdev.CheckFileStoragePath(fs_dir)
2875

    
2876
  return os.path.normpath(fs_dir)
2877

    
2878

    
2879
def CreateFileStorageDir(file_storage_dir):
2880
  """Create file storage directory.
2881

2882
  @type file_storage_dir: str
2883
  @param file_storage_dir: directory to create
2884

2885
  @rtype: tuple
2886
  @return: tuple with first element a boolean indicating wheter dir
2887
      creation was successful or not
2888

2889
  """
2890
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2891
  if os.path.exists(file_storage_dir):
2892
    if not os.path.isdir(file_storage_dir):
2893
      _Fail("Specified storage dir '%s' is not a directory",
2894
            file_storage_dir)
2895
  else:
2896
    try:
2897
      os.makedirs(file_storage_dir, 0750)
2898
    except OSError, err:
2899
      _Fail("Cannot create file storage directory '%s': %s",
2900
            file_storage_dir, err, exc=True)
2901

    
2902

    
2903
def RemoveFileStorageDir(file_storage_dir):
2904
  """Remove file storage directory.
2905

2906
  Remove it only if it's empty. If not log an error and return.
2907

2908
  @type file_storage_dir: str
2909
  @param file_storage_dir: the directory we should cleanup
2910
  @rtype: tuple (success,)
2911
  @return: tuple of one element, C{success}, denoting
2912
      whether the operation was successful
2913

2914
  """
2915
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2916
  if os.path.exists(file_storage_dir):
2917
    if not os.path.isdir(file_storage_dir):
2918
      _Fail("Specified Storage directory '%s' is not a directory",
2919
            file_storage_dir)
2920
    # deletes dir only if empty, otherwise we want to fail the rpc call
2921
    try:
2922
      os.rmdir(file_storage_dir)
2923
    except OSError, err:
2924
      _Fail("Cannot remove file storage directory '%s': %s",
2925
            file_storage_dir, err)
2926

    
2927

    
2928
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2929
  """Rename the file storage directory.
2930

2931
  @type old_file_storage_dir: str
2932
  @param old_file_storage_dir: the current path
2933
  @type new_file_storage_dir: str
2934
  @param new_file_storage_dir: the name we should rename to
2935
  @rtype: tuple (success,)
2936
  @return: tuple of one element, C{success}, denoting
2937
      whether the operation was successful
2938

2939
  """
2940
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2941
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2942
  if not os.path.exists(new_file_storage_dir):
2943
    if os.path.isdir(old_file_storage_dir):
2944
      try:
2945
        os.rename(old_file_storage_dir, new_file_storage_dir)
2946
      except OSError, err:
2947
        _Fail("Cannot rename '%s' to '%s': %s",
2948
              old_file_storage_dir, new_file_storage_dir, err)
2949
    else:
2950
      _Fail("Specified storage dir '%s' is not a directory",
2951
            old_file_storage_dir)
2952
  else:
2953
    if os.path.exists(old_file_storage_dir):
2954
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2955
            old_file_storage_dir, new_file_storage_dir)
2956

    
2957

    
2958
def _EnsureJobQueueFile(file_name):
2959
  """Checks whether the given filename is in the queue directory.
2960

2961
  @type file_name: str
2962
  @param file_name: the file name we should check
2963
  @rtype: None
2964
  @raises RPCFail: if the file is not valid
2965

2966
  """
2967
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
2968
    _Fail("Passed job queue file '%s' does not belong to"
2969
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
2970

    
2971

    
2972
def JobQueueUpdate(file_name, content):
2973
  """Updates a file in the queue directory.
2974

2975
  This is just a wrapper over L{utils.io.WriteFile}, with proper
2976
  checking.
2977

2978
  @type file_name: str
2979
  @param file_name: the job file name
2980
  @type content: str
2981
  @param content: the new job contents
2982
  @rtype: boolean
2983
  @return: the success of the operation
2984

2985
  """
2986
  file_name = vcluster.LocalizeVirtualPath(file_name)
2987

    
2988
  _EnsureJobQueueFile(file_name)
2989
  getents = runtime.GetEnts()
2990

    
2991
  # Write and replace the file atomically
2992
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
2993
                  gid=getents.masterd_gid)
2994

    
2995

    
2996
def JobQueueRename(old, new):
2997
  """Renames a job queue file.
2998

2999
  This is just a wrapper over os.rename with proper checking.
3000

3001
  @type old: str
3002
  @param old: the old (actual) file name
3003
  @type new: str
3004
  @param new: the desired file name
3005
  @rtype: tuple
3006
  @return: the success of the operation and payload
3007

3008
  """
3009
  old = vcluster.LocalizeVirtualPath(old)
3010
  new = vcluster.LocalizeVirtualPath(new)
3011

    
3012
  _EnsureJobQueueFile(old)
3013
  _EnsureJobQueueFile(new)
3014

    
3015
  getents = runtime.GetEnts()
3016

    
3017
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0700,
3018
                   dir_uid=getents.masterd_uid, dir_gid=getents.masterd_gid)
3019

    
3020

    
3021
def BlockdevClose(instance_name, disks):
3022
  """Closes the given block devices.
3023

3024
  This means they will be switched to secondary mode (in case of
3025
  DRBD).
3026

3027
  @param instance_name: if the argument is not empty, the symlinks
3028
      of this instance will be removed
3029
  @type disks: list of L{objects.Disk}
3030
  @param disks: the list of disks to be closed
3031
  @rtype: tuple (success, message)
3032
  @return: a tuple of success and message, where success
3033
      indicates the succes of the operation, and message
3034
      which will contain the error details in case we
3035
      failed
3036

3037
  """
3038
  bdevs = []
3039
  for cf in disks:
3040
    rd = _RecursiveFindBD(cf)
3041
    if rd is None:
3042
      _Fail("Can't find device %s", cf)
3043
    bdevs.append(rd)
3044

    
3045
  msg = []
3046
  for rd in bdevs:
3047
    try:
3048
      rd.Close()
3049
    except errors.BlockDeviceError, err:
3050
      msg.append(str(err))
3051
  if msg:
3052
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3053
  else:
3054
    if instance_name:
3055
      _RemoveBlockDevLinks(instance_name, disks)
3056

    
3057

    
3058
def ValidateHVParams(hvname, hvparams):
3059
  """Validates the given hypervisor parameters.
3060

3061
  @type hvname: string
3062
  @param hvname: the hypervisor name
3063
  @type hvparams: dict
3064
  @param hvparams: the hypervisor parameters to be validated
3065
  @rtype: None
3066

3067
  """
3068
  try:
3069
    hv_type = hypervisor.GetHypervisor(hvname)
3070
    hv_type.ValidateParameters(hvparams)
3071
  except errors.HypervisorError, err:
3072
    _Fail(str(err), log=False)
3073

    
3074

    
3075
def _CheckOSPList(os_obj, parameters):
3076
  """Check whether a list of parameters is supported by the OS.
3077

3078
  @type os_obj: L{objects.OS}
3079
  @param os_obj: OS object to check
3080
  @type parameters: list
3081
  @param parameters: the list of parameters to check
3082

3083
  """
3084
  supported = [v[0] for v in os_obj.supported_parameters]
3085
  delta = frozenset(parameters).difference(supported)
3086
  if delta:
3087
    _Fail("The following parameters are not supported"
3088
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3089

    
3090

    
3091
def ValidateOS(required, osname, checks, osparams):
3092
  """Validate the given OS' parameters.
3093

3094
  @type required: boolean
3095
  @param required: whether absence of the OS should translate into
3096
      failure or not
3097
  @type osname: string
3098
  @param osname: the OS to be validated
3099
  @type checks: list
3100
  @param checks: list of the checks to run (currently only 'parameters')
3101
  @type osparams: dict
3102
  @param osparams: dictionary with OS parameters
3103
  @rtype: boolean
3104
  @return: True if the validation passed, or False if the OS was not
3105
      found and L{required} was false
3106

3107
  """
3108
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3109
    _Fail("Unknown checks required for OS %s: %s", osname,
3110
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3111

    
3112
  name_only = objects.OS.GetName(osname)
3113
  status, tbv = _TryOSFromDisk(name_only, None)
3114

    
3115
  if not status:
3116
    if required:
3117
      _Fail(tbv)
3118
    else:
3119
      return False
3120

    
3121
  if max(tbv.api_versions) < constants.OS_API_V20:
3122
    return True
3123

    
3124
  if constants.OS_VALIDATE_PARAMETERS in checks:
3125
    _CheckOSPList(tbv, osparams.keys())
3126

    
3127
  validate_env = OSCoreEnv(osname, tbv, osparams)
3128
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3129
                        cwd=tbv.path, reset_env=True)
3130
  if result.failed:
3131
    logging.error("os validate command '%s' returned error: %s output: %s",
3132
                  result.cmd, result.fail_reason, result.output)
3133
    _Fail("OS validation script failed (%s), output: %s",
3134
          result.fail_reason, result.output, log=False)
3135

    
3136
  return True
3137

    
3138

    
3139
def DemoteFromMC():
3140
  """Demotes the current node from master candidate role.
3141

3142
  """
3143
  # try to ensure we're not the master by mistake
3144
  master, myself = ssconf.GetMasterAndMyself()
3145
  if master == myself:
3146
    _Fail("ssconf status shows I'm the master node, will not demote")
3147

    
3148
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3149
  if not result.failed:
3150
    _Fail("The master daemon is running, will not demote")
3151

    
3152
  try:
3153
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3154
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3155
  except EnvironmentError, err:
3156
    if err.errno != errno.ENOENT:
3157
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3158

    
3159
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3160

    
3161

    
3162
def _GetX509Filenames(cryptodir, name):
3163
  """Returns the full paths for the private key and certificate.
3164

3165
  """
3166
  return (utils.PathJoin(cryptodir, name),
3167
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3168
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3169

    
3170

    
3171
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3172
  """Creates a new X509 certificate for SSL/TLS.
3173

3174
  @type validity: int
3175
  @param validity: Validity in seconds
3176
  @rtype: tuple; (string, string)
3177
  @return: Certificate name and public part
3178

3179
  """
3180
  (key_pem, cert_pem) = \
3181
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3182
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3183

    
3184
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3185
                              prefix="x509-%s-" % utils.TimestampForFilename())
3186
  try:
3187
    name = os.path.basename(cert_dir)
3188
    assert len(name) > 5
3189

    
3190
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3191

    
3192
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3193
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3194

    
3195
    # Never return private key as it shouldn't leave the node
3196
    return (name, cert_pem)
3197
  except Exception:
3198
    shutil.rmtree(cert_dir, ignore_errors=True)
3199
    raise
3200

    
3201

    
3202
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3203
  """Removes a X509 certificate.
3204

3205
  @type name: string
3206
  @param name: Certificate name
3207

3208
  """
3209
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3210

    
3211
  utils.RemoveFile(key_file)
3212
  utils.RemoveFile(cert_file)
3213

    
3214
  try:
3215
    os.rmdir(cert_dir)
3216
  except EnvironmentError, err:
3217
    _Fail("Cannot remove certificate directory '%s': %s",
3218
          cert_dir, err)
3219

    
3220

    
3221
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3222
  """Returns the command for the requested input/output.
3223

3224
  @type instance: L{objects.Instance}
3225
  @param instance: The instance object
3226
  @param mode: Import/export mode
3227
  @param ieio: Input/output type
3228
  @param ieargs: Input/output arguments
3229

3230
  """
3231
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3232

    
3233
  env = None
3234
  prefix = None
3235
  suffix = None
3236
  exp_size = None
3237

    
3238
  if ieio == constants.IEIO_FILE:
3239
    (filename, ) = ieargs
3240

    
3241
    if not utils.IsNormAbsPath(filename):
3242
      _Fail("Path '%s' is not normalized or absolute", filename)
3243

    
3244
    real_filename = os.path.realpath(filename)
3245
    directory = os.path.dirname(real_filename)
3246

    
3247
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3248
      _Fail("File '%s' is not under exports directory '%s': %s",
3249
            filename, pathutils.EXPORT_DIR, real_filename)
3250

    
3251
    # Create directory
3252
    utils.Makedirs(directory, mode=0750)
3253

    
3254
    quoted_filename = utils.ShellQuote(filename)
3255

    
3256
    if mode == constants.IEM_IMPORT:
3257
      suffix = "> %s" % quoted_filename
3258
    elif mode == constants.IEM_EXPORT:
3259
      suffix = "< %s" % quoted_filename
3260

    
3261
      # Retrieve file size
3262
      try:
3263
        st = os.stat(filename)
3264
      except EnvironmentError, err:
3265
        logging.error("Can't stat(2) %s: %s", filename, err)
3266
      else:
3267
        exp_size = utils.BytesToMebibyte(st.st_size)
3268

    
3269
  elif ieio == constants.IEIO_RAW_DISK:
3270
    (disk, ) = ieargs
3271

    
3272
    real_disk = _OpenRealBD(disk)
3273

    
3274
    if mode == constants.IEM_IMPORT:
3275
      # we set here a smaller block size as, due to transport buffering, more
3276
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3277
      # is not already there or we pass a wrong path; we use notrunc to no
3278
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3279
      # much memory; this means that at best, we flush every 64k, which will
3280
      # not be very fast
3281
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3282
                                    " bs=%s oflag=dsync"),
3283
                                    real_disk.dev_path,
3284
                                    str(64 * 1024))
3285

    
3286
    elif mode == constants.IEM_EXPORT:
3287
      # the block size on the read dd is 1MiB to match our units
3288
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3289
                                   real_disk.dev_path,
3290
                                   str(1024 * 1024), # 1 MB
3291
                                   str(disk.size))
3292
      exp_size = disk.size
3293

    
3294
  elif ieio == constants.IEIO_SCRIPT:
3295
    (disk, disk_index, ) = ieargs
3296

    
3297
    assert isinstance(disk_index, (int, long))
3298

    
3299
    real_disk = _OpenRealBD(disk)
3300

    
3301
    inst_os = OSFromDisk(instance.os)
3302
    env = OSEnvironment(instance, inst_os)
3303

    
3304
    if mode == constants.IEM_IMPORT:
3305
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3306
      env["IMPORT_INDEX"] = str(disk_index)
3307
      script = inst_os.import_script
3308

    
3309
    elif mode == constants.IEM_EXPORT:
3310
      env["EXPORT_DEVICE"] = real_disk.dev_path
3311
      env["EXPORT_INDEX"] = str(disk_index)
3312
      script = inst_os.export_script
3313

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

    
3317
    if mode == constants.IEM_IMPORT:
3318
      suffix = "| %s" % script_cmd
3319

    
3320
    elif mode == constants.IEM_EXPORT:
3321
      prefix = "%s |" % script_cmd
3322

    
3323
    # Let script predict size
3324
    exp_size = constants.IE_CUSTOM_SIZE
3325

    
3326
  else:
3327
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3328

    
3329
  return (env, prefix, suffix, exp_size)
3330

    
3331

    
3332
def _CreateImportExportStatusDir(prefix):
3333
  """Creates status directory for import/export.
3334

3335
  """
3336
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3337
                          prefix=("%s-%s-" %
3338
                                  (prefix, utils.TimestampForFilename())))
3339

    
3340

    
3341
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3342
                            ieio, ieioargs):
3343
  """Starts an import or export daemon.
3344

3345
  @param mode: Import/output mode
3346
  @type opts: L{objects.ImportExportOptions}
3347
  @param opts: Daemon options
3348
  @type host: string
3349
  @param host: Remote host for export (None for import)
3350
  @type port: int
3351
  @param port: Remote port for export (None for import)
3352
  @type instance: L{objects.Instance}
3353
  @param instance: Instance object
3354
  @type component: string
3355
  @param component: which part of the instance is transferred now,
3356
      e.g. 'disk/0'
3357
  @param ieio: Input/output type
3358
  @param ieioargs: Input/output arguments
3359

3360
  """
3361
  if mode == constants.IEM_IMPORT:
3362
    prefix = "import"
3363

    
3364
    if not (host is None and port is None):
3365
      _Fail("Can not specify host or port on import")
3366

    
3367
  elif mode == constants.IEM_EXPORT:
3368
    prefix = "export"
3369

    
3370
    if host is None or port is None:
3371
      _Fail("Host and port must be specified for an export")
3372

    
3373
  else:
3374
    _Fail("Invalid mode %r", mode)
3375

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

    
3379
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3380
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3381

    
3382
  if opts.key_name is None:
3383
    # Use server.pem
3384
    key_path = pathutils.NODED_CERT_FILE
3385
    cert_path = pathutils.NODED_CERT_FILE
3386
    assert opts.ca_pem is None
3387
  else:
3388
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3389
                                                 opts.key_name)
3390
    assert opts.ca_pem is not None
3391

    
3392
  for i in [key_path, cert_path]:
3393
    if not os.path.exists(i):
3394
      _Fail("File '%s' does not exist" % i)
3395

    
3396
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3397
  try:
3398
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3399
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3400
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3401

    
3402
    if opts.ca_pem is None:
3403
      # Use server.pem
3404
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3405
    else:
3406
      ca = opts.ca_pem
3407

    
3408
    # Write CA file
3409
    utils.WriteFile(ca_file, data=ca, mode=0400)
3410

    
3411
    cmd = [
3412
      pathutils.IMPORT_EXPORT_DAEMON,
3413
      status_file, mode,
3414
      "--key=%s" % key_path,
3415
      "--cert=%s" % cert_path,
3416
      "--ca=%s" % ca_file,
3417
      ]
3418

    
3419
    if host:
3420
      cmd.append("--host=%s" % host)
3421

    
3422
    if port:
3423
      cmd.append("--port=%s" % port)
3424

    
3425
    if opts.ipv6:
3426
      cmd.append("--ipv6")
3427
    else:
3428
      cmd.append("--ipv4")
3429

    
3430
    if opts.compress:
3431
      cmd.append("--compress=%s" % opts.compress)
3432

    
3433
    if opts.magic:
3434
      cmd.append("--magic=%s" % opts.magic)
3435

    
3436
    if exp_size is not None:
3437
      cmd.append("--expected-size=%s" % exp_size)
3438

    
3439
    if cmd_prefix:
3440
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3441

    
3442
    if cmd_suffix:
3443
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3444

    
3445
    if mode == constants.IEM_EXPORT:
3446
      # Retry connection a few times when connecting to remote peer
3447
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3448
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3449
    elif opts.connect_timeout is not None:
3450
      assert mode == constants.IEM_IMPORT
3451
      # Overall timeout for establishing connection while listening
3452
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3453

    
3454
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3455

    
3456
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3457
    # support for receiving a file descriptor for output
3458
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3459
                      output=logfile)
3460

    
3461
    # The import/export name is simply the status directory name
3462
    return os.path.basename(status_dir)
3463

    
3464
  except Exception:
3465
    shutil.rmtree(status_dir, ignore_errors=True)
3466
    raise
3467

    
3468

    
3469
def GetImportExportStatus(names):
3470
  """Returns import/export daemon status.
3471

3472
  @type names: sequence
3473
  @param names: List of names
3474
  @rtype: List of dicts
3475
  @return: Returns a list of the state of each named import/export or None if a
3476
           status couldn't be read
3477

3478
  """
3479
  result = []
3480

    
3481
  for name in names:
3482
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3483
                                 _IES_STATUS_FILE)
3484

    
3485
    try:
3486
      data = utils.ReadFile(status_file)
3487
    except EnvironmentError, err:
3488
      if err.errno != errno.ENOENT:
3489
        raise
3490
      data = None
3491

    
3492
    if not data:
3493
      result.append(None)
3494
      continue
3495

    
3496
    result.append(serializer.LoadJson(data))
3497

    
3498
  return result
3499

    
3500

    
3501
def AbortImportExport(name):
3502
  """Sends SIGTERM to a running import/export daemon.
3503

3504
  """
3505
  logging.info("Abort import/export %s", name)
3506

    
3507
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3508
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3509

    
3510
  if pid:
3511
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3512
                 name, pid)
3513
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3514

    
3515

    
3516
def CleanupImportExport(name):
3517
  """Cleanup after an import or export.
3518

3519
  If the import/export daemon is still running it's killed. Afterwards the
3520
  whole status directory is removed.
3521

3522
  """
3523
  logging.info("Finalizing import/export %s", name)
3524

    
3525
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3526

    
3527
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3528

    
3529
  if pid:
3530
    logging.info("Import/export %s is still running with PID %s",
3531
                 name, pid)
3532
    utils.KillProcess(pid, waitpid=False)
3533

    
3534
  shutil.rmtree(status_dir, ignore_errors=True)
3535

    
3536

    
3537
def _FindDisks(nodes_ip, disks):
3538
  """Sets the physical ID on disks and returns the block devices.
3539

3540
  """
3541
  # set the correct physical ID
3542
  my_name = netutils.Hostname.GetSysName()
3543
  for cf in disks:
3544
    cf.SetPhysicalID(my_name, nodes_ip)
3545

    
3546
  bdevs = []
3547

    
3548
  for cf in disks:
3549
    rd = _RecursiveFindBD(cf)
3550
    if rd is None:
3551
      _Fail("Can't find device %s", cf)
3552
    bdevs.append(rd)
3553
  return bdevs
3554

    
3555

    
3556
def DrbdDisconnectNet(nodes_ip, disks):
3557
  """Disconnects the network on a list of drbd devices.
3558

3559
  """
3560
  bdevs = _FindDisks(nodes_ip, disks)
3561

    
3562
  # disconnect disks
3563
  for rd in bdevs:
3564
    try:
3565
      rd.DisconnectNet()
3566
    except errors.BlockDeviceError, err:
3567
      _Fail("Can't change network configuration to standalone mode: %s",
3568
            err, exc=True)
3569

    
3570

    
3571
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3572
  """Attaches the network on a list of drbd devices.
3573

3574
  """
3575
  bdevs = _FindDisks(nodes_ip, disks)
3576

    
3577
  if multimaster:
3578
    for idx, rd in enumerate(bdevs):
3579
      try:
3580
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3581
      except EnvironmentError, err:
3582
        _Fail("Can't create symlink: %s", err)
3583
  # reconnect disks, switch to new master configuration and if
3584
  # needed primary mode
3585
  for rd in bdevs:
3586
    try:
3587
      rd.AttachNet(multimaster)
3588
    except errors.BlockDeviceError, err:
3589
      _Fail("Can't change network configuration: %s", err)
3590

    
3591
  # wait until the disks are connected; we need to retry the re-attach
3592
  # if the device becomes standalone, as this might happen if the one
3593
  # node disconnects and reconnects in a different mode before the
3594
  # other node reconnects; in this case, one or both of the nodes will
3595
  # decide it has wrong configuration and switch to standalone
3596

    
3597
  def _Attach():
3598
    all_connected = True
3599

    
3600
    for rd in bdevs:
3601
      stats = rd.GetProcStatus()
3602

    
3603
      all_connected = (all_connected and
3604
                       (stats.is_connected or stats.is_in_resync))
3605

    
3606
      if stats.is_standalone:
3607
        # peer had different config info and this node became
3608
        # standalone, even though this should not happen with the
3609
        # new staged way of changing disk configs
3610
        try:
3611
          rd.AttachNet(multimaster)
3612
        except errors.BlockDeviceError, err:
3613
          _Fail("Can't change network configuration: %s", err)
3614

    
3615
    if not all_connected:
3616
      raise utils.RetryAgain()
3617

    
3618
  try:
3619
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3620
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3621
  except utils.RetryTimeout:
3622
    _Fail("Timeout in disk reconnecting")
3623

    
3624
  if multimaster:
3625
    # change to primary mode
3626
    for rd in bdevs:
3627
      try:
3628
        rd.Open()
3629
      except errors.BlockDeviceError, err:
3630
        _Fail("Can't change to primary mode: %s", err)
3631

    
3632

    
3633
def DrbdWaitSync(nodes_ip, disks):
3634
  """Wait until DRBDs have synchronized.
3635

3636
  """
3637
  def _helper(rd):
3638
    stats = rd.GetProcStatus()
3639
    if not (stats.is_connected or stats.is_in_resync):
3640
      raise utils.RetryAgain()
3641
    return stats
3642

    
3643
  bdevs = _FindDisks(nodes_ip, disks)
3644

    
3645
  min_resync = 100
3646
  alldone = True
3647
  for rd in bdevs:
3648
    try:
3649
      # poll each second for 15 seconds
3650
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3651
    except utils.RetryTimeout:
3652
      stats = rd.GetProcStatus()
3653
      # last check
3654
      if not (stats.is_connected or stats.is_in_resync):
3655
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3656
    alldone = alldone and (not stats.is_in_resync)
3657
    if stats.sync_percent is not None:
3658
      min_resync = min(min_resync, stats.sync_percent)
3659

    
3660
  return (alldone, min_resync)
3661

    
3662

    
3663
def GetDrbdUsermodeHelper():
3664
  """Returns DRBD usermode helper currently configured.
3665

3666
  """
3667
  try:
3668
    return bdev.BaseDRBD.GetUsermodeHelper()
3669
  except errors.BlockDeviceError, err:
3670
    _Fail(str(err))
3671

    
3672

    
3673
def PowercycleNode(hypervisor_type):
3674
  """Hard-powercycle the node.
3675

3676
  Because we need to return first, and schedule the powercycle in the
3677
  background, we won't be able to report failures nicely.
3678

3679
  """
3680
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3681
  try:
3682
    pid = os.fork()
3683
  except OSError:
3684
    # if we can't fork, we'll pretend that we're in the child process
3685
    pid = 0
3686
  if pid > 0:
3687
    return "Reboot scheduled in 5 seconds"
3688
  # ensure the child is running on ram
3689
  try:
3690
    utils.Mlockall()
3691
  except Exception: # pylint: disable=W0703
3692
    pass
3693
  time.sleep(5)
3694
  hyper.PowercycleNode()
3695

    
3696

    
3697
def _VerifyRestrictedCmdName(cmd):
3698
  """Verifies a restricted command name.
3699

3700
  @type cmd: string
3701
  @param cmd: Command name
3702
  @rtype: tuple; (boolean, string or None)
3703
  @return: The tuple's first element is the status; if C{False}, the second
3704
    element is an error message string, otherwise it's C{None}
3705

3706
  """
3707
  if not cmd.strip():
3708
    return (False, "Missing command name")
3709

    
3710
  if os.path.basename(cmd) != cmd:
3711
    return (False, "Invalid command name")
3712

    
3713
  if not constants.EXT_PLUGIN_MASK.match(cmd):
3714
    return (False, "Command name contains forbidden characters")
3715

    
3716
  return (True, None)
3717

    
3718

    
3719
def _CommonRestrictedCmdCheck(path, owner):
3720
  """Common checks for restricted command file system directories and files.
3721

3722
  @type path: string
3723
  @param path: Path to check
3724
  @param owner: C{None} or tuple containing UID and GID
3725
  @rtype: tuple; (boolean, string or C{os.stat} result)
3726
  @return: The tuple's first element is the status; if C{False}, the second
3727
    element is an error message string, otherwise it's the result of C{os.stat}
3728

3729
  """
3730
  if owner is None:
3731
    # Default to root as owner
3732
    owner = (0, 0)
3733

    
3734
  try:
3735
    st = os.stat(path)
3736
  except EnvironmentError, err:
3737
    return (False, "Can't stat(2) '%s': %s" % (path, err))
3738

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

    
3742
  if (st.st_uid, st.st_gid) != owner:
3743
    (owner_uid, owner_gid) = owner
3744
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
3745

    
3746
  return (True, st)
3747

    
3748

    
3749
def _VerifyRestrictedCmdDirectory(path, _owner=None):
3750
  """Verifies restricted command directory.
3751

3752
  @type path: string
3753
  @param path: Path to check
3754
  @rtype: tuple; (boolean, string or None)
3755
  @return: The tuple's first element is the status; if C{False}, the second
3756
    element is an error message string, otherwise it's C{None}
3757

3758
  """
3759
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
3760

    
3761
  if not status:
3762
    return (False, value)
3763

    
3764
  if not stat.S_ISDIR(value.st_mode):
3765
    return (False, "Path '%s' is not a directory" % path)
3766

    
3767
  return (True, None)
3768

    
3769

    
3770
def _VerifyRestrictedCmd(path, cmd, _owner=None):
3771
  """Verifies a whole restricted command and returns its executable filename.
3772

3773
  @type path: string
3774
  @param path: Directory containing restricted commands
3775
  @type cmd: string
3776
  @param cmd: Command name
3777
  @rtype: tuple; (boolean, string)
3778
  @return: The tuple's first element is the status; if C{False}, the second
3779
    element is an error message string, otherwise the second element is the
3780
    absolute path to the executable
3781

3782
  """
3783
  executable = utils.PathJoin(path, cmd)
3784

    
3785
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
3786

    
3787
  if not status:
3788
    return (False, msg)
3789

    
3790
  if not utils.IsExecutable(executable):
3791
    return (False, "access(2) thinks '%s' can't be executed" % executable)
3792

    
3793
  return (True, executable)
3794

    
3795

    
3796
def _PrepareRestrictedCmd(path, cmd,
3797
                          _verify_dir=_VerifyRestrictedCmdDirectory,
3798
                          _verify_name=_VerifyRestrictedCmdName,
3799
                          _verify_cmd=_VerifyRestrictedCmd):
3800
  """Performs a number of tests on a restricted command.
3801

3802
  @type path: string
3803
  @param path: Directory containing restricted commands
3804
  @type cmd: string
3805
  @param cmd: Command name
3806
  @return: Same as L{_VerifyRestrictedCmd}
3807

3808
  """
3809
  # Verify the directory first
3810
  (status, msg) = _verify_dir(path)
3811
  if status:
3812
    # Check command if everything was alright
3813
    (status, msg) = _verify_name(cmd)
3814

    
3815
  if not status:
3816
    return (False, msg)
3817

    
3818
  # Check actual executable
3819
  return _verify_cmd(path, cmd)
3820

    
3821

    
3822
def RunRestrictedCmd(cmd,
3823
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
3824
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
3825
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
3826
                     _sleep_fn=time.sleep,
3827
                     _prepare_fn=_PrepareRestrictedCmd,
3828
                     _runcmd_fn=utils.RunCmd,
3829
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
3830
  """Executes a restricted command after performing strict tests.
3831

3832
  @type cmd: string
3833
  @param cmd: Command name
3834
  @rtype: string
3835
  @return: Command output
3836
  @raise RPCFail: In case of an error
3837

3838
  """
3839
  logging.info("Preparing to run restricted command '%s'", cmd)
3840

    
3841
  if not _enabled:
3842
    _Fail("Restricted commands disabled at configure time")
3843

    
3844
  lock = None
3845
  try:
3846
    cmdresult = None
3847
    try:
3848
      lock = utils.FileLock.Open(_lock_file)
3849
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
3850

    
3851
      (status, value) = _prepare_fn(_path, cmd)
3852

    
3853
      if status:
3854
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
3855
                               postfork_fn=lambda _: lock.Unlock())
3856
      else:
3857
        logging.error(value)
3858
    except Exception: # pylint: disable=W0703
3859
      # Keep original error in log
3860
      logging.exception("Caught exception")
3861

    
3862
    if cmdresult is None:
3863
      logging.info("Sleeping for %0.1f seconds before returning",
3864
                   _RCMD_INVALID_DELAY)
3865
      _sleep_fn(_RCMD_INVALID_DELAY)
3866

    
3867
      # Do not include original error message in returned error
3868
      _Fail("Executing command '%s' failed" % cmd)
3869
    elif cmdresult.failed or cmdresult.fail_reason:
3870
      _Fail("Restricted command '%s' failed: %s; output: %s",
3871
            cmd, cmdresult.fail_reason, cmdresult.output)
3872
    else:
3873
      return cmdresult.output
3874
  finally:
3875
    if lock is not None:
3876
      # Release lock at last
3877
      lock.Close()
3878
      lock = None
3879

    
3880

    
3881
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
3882
  """Creates or removes the watcher pause file.
3883

3884
  @type until: None or number
3885
  @param until: Unix timestamp saying until when the watcher shouldn't run
3886

3887
  """
3888
  if until is None:
3889
    logging.info("Received request to no longer pause watcher")
3890
    utils.RemoveFile(_filename)
3891
  else:
3892
    logging.info("Received request to pause watcher until %s", until)
3893

    
3894
    if not ht.TNumber(until):
3895
      _Fail("Duration must be numeric")
3896

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

    
3899

    
3900
class HooksRunner(object):
3901
  """Hook runner.
3902

3903
  This class is instantiated on the node side (ganeti-noded) and not
3904
  on the master side.
3905

3906
  """
3907
  def __init__(self, hooks_base_dir=None):
3908
    """Constructor for hooks runner.
3909

3910
    @type hooks_base_dir: str or None
3911
    @param hooks_base_dir: if not None, this overrides the
3912
        L{pathutils.HOOKS_BASE_DIR} (useful for unittests)
3913

3914
    """
3915
    if hooks_base_dir is None:
3916
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
3917
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3918
    # constant
3919
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
3920

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

3924
    """
3925
    assert len(node_list) == 1
3926
    node = node_list[0]
3927
    _, myself = ssconf.GetMasterAndMyself()
3928
    assert node == myself
3929

    
3930
    results = self.RunHooks(hpath, phase, env)
3931

    
3932
    # Return values in the form expected by HooksMaster
3933
    return {node: (None, False, results)}
3934

    
3935
  def RunHooks(self, hpath, phase, env):
3936
    """Run the scripts in the hooks directory.
3937

3938
    @type hpath: str
3939
    @param hpath: the path to the hooks directory which
3940
        holds the scripts
3941
    @type phase: str
3942
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
3943
        L{constants.HOOKS_PHASE_POST}
3944
    @type env: dict
3945
    @param env: dictionary with the environment for the hook
3946
    @rtype: list
3947
    @return: list of 3-element tuples:
3948
      - script path
3949
      - script result, either L{constants.HKR_SUCCESS} or
3950
        L{constants.HKR_FAIL}
3951
      - output of the script
3952

3953
    @raise errors.ProgrammerError: for invalid input
3954
        parameters
3955

3956
    """
3957
    if phase == constants.HOOKS_PHASE_PRE:
3958
      suffix = "pre"
3959
    elif phase == constants.HOOKS_PHASE_POST:
3960
      suffix = "post"
3961
    else:
3962
      _Fail("Unknown hooks phase '%s'", phase)
3963

    
3964
    subdir = "%s-%s.d" % (hpath, suffix)
3965
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3966

    
3967
    results = []
3968

    
3969
    if not os.path.isdir(dir_name):
3970
      # for non-existing/non-dirs, we simply exit instead of logging a
3971
      # warning at every operation
3972
      return results
3973

    
3974
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3975

    
3976
    for (relname, relstatus, runresult) in runparts_results:
3977
      if relstatus == constants.RUNPARTS_SKIP:
3978
        rrval = constants.HKR_SKIP
3979
        output = ""
3980
      elif relstatus == constants.RUNPARTS_ERR:
3981
        rrval = constants.HKR_FAIL
3982
        output = "Hook script execution error: %s" % runresult
3983
      elif relstatus == constants.RUNPARTS_RUN:
3984
        if runresult.failed:
3985
          rrval = constants.HKR_FAIL
3986
        else:
3987
          rrval = constants.HKR_SUCCESS
3988
        output = utils.SafeEncode(runresult.output.strip())
3989
      results.append(("%s/%s" % (subdir, relname), rrval, output))
3990

    
3991
    return results
3992

    
3993

    
3994
class IAllocatorRunner(object):
3995
  """IAllocator runner.
3996

3997
  This class is instantiated on the node side (ganeti-noded) and not on
3998
  the master side.
3999

4000
  """
4001
  @staticmethod
4002
  def Run(name, idata):
4003
    """Run an iallocator script.
4004

4005
    @type name: str
4006
    @param name: the iallocator script name
4007
    @type idata: str
4008
    @param idata: the allocator input data
4009

4010
    @rtype: tuple
4011
    @return: two element tuple of:
4012
       - status
4013
       - either error message or stdout of allocator (for success)
4014

4015
    """
4016
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
4017
                                  os.path.isfile)
4018
    if alloc_script is None:
4019
      _Fail("iallocator module '%s' not found in the search path", name)
4020

    
4021
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
4022
    try:
4023
      os.write(fd, idata)
4024
      os.close(fd)
4025
      result = utils.RunCmd([alloc_script, fin_name])
4026
      if result.failed:
4027
        _Fail("iallocator module '%s' failed: %s, output '%s'",
4028
              name, result.fail_reason, result.output)
4029
    finally:
4030
      os.unlink(fin_name)
4031

    
4032
    return result.stdout
4033

    
4034

    
4035
class DevCacheManager(object):
4036
  """Simple class for managing a cache of block device information.
4037

4038
  """
4039
  _DEV_PREFIX = "/dev/"
4040
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4041

    
4042
  @classmethod
4043
  def _ConvertPath(cls, dev_path):
4044
    """Converts a /dev/name path to the cache file name.
4045

4046
    This replaces slashes with underscores and strips the /dev
4047
    prefix. It then returns the full path to the cache file.
4048

4049
    @type dev_path: str
4050
    @param dev_path: the C{/dev/} path name
4051
    @rtype: str
4052
    @return: the converted path name
4053

4054
    """
4055
    if dev_path.startswith(cls._DEV_PREFIX):
4056
      dev_path = dev_path[len(cls._DEV_PREFIX):]
4057
    dev_path = dev_path.replace("/", "_")
4058
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4059
    return fpath
4060

    
4061
  @classmethod
4062
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4063
    """Updates the cache information for a given device.
4064

4065
    @type dev_path: str
4066
    @param dev_path: the pathname of the device
4067
    @type owner: str
4068
    @param owner: the owner (instance name) of the device
4069
    @type on_primary: bool
4070
    @param on_primary: whether this is the primary
4071
        node nor not
4072
    @type iv_name: str
4073
    @param iv_name: the instance-visible name of the
4074
        device, as in objects.Disk.iv_name
4075

4076
    @rtype: None
4077

4078
    """
4079
    if dev_path is None:
4080
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
4081
      return
4082
    fpath = cls._ConvertPath(dev_path)
4083
    if on_primary:
4084
      state = "primary"
4085
    else:
4086
      state = "secondary"
4087
    if iv_name is None:
4088
      iv_name = "not_visible"
4089
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4090
    try:
4091
      utils.WriteFile(fpath, data=fdata)
4092
    except EnvironmentError, err:
4093
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4094

    
4095
  @classmethod
4096
  def RemoveCache(cls, dev_path):
4097
    """Remove data for a dev_path.
4098

4099
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
4100
    path name and logging.
4101

4102
    @type dev_path: str
4103
    @param dev_path: the pathname of the device
4104

4105
    @rtype: None
4106

4107
    """
4108
    if dev_path is None:
4109
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
4110
      return
4111
    fpath = cls._ConvertPath(dev_path)
4112
    try:
4113
      utils.RemoveFile(fpath)
4114
    except EnvironmentError, err:
4115
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)