Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 89ff748d

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

    
71

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

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

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

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

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

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

    
106

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

110
  Its argument is the error message.
111

112
  """
113

    
114

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

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

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

    
126

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

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

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

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

    
142

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

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

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

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

    
165

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

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

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

    
175

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

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

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

    
188

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

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

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

    
208

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

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

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

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

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

    
238

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

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

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

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

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

    
265
  return frozenset(allowed_files)
266

    
267

    
268
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
269

    
270

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

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

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

    
281

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

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

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

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

    
306

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

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

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

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

    
328
      cfg = _GetConfig()
329
      hr = HooksRunner()
330
      hm = mcpu.HooksMaster(hook_opcode, hooks_path, nodes, hr.RunLocalHooks,
331
                            None, env_fn, logging.warning, cfg.GetClusterName(),
332
                            cfg.GetMasterNode())
333

    
334
      hm.RunPhase(constants.HOOKS_PHASE_PRE)
335
      result = fn(*args, **kwargs)
336
      hm.RunPhase(constants.HOOKS_PHASE_POST)
337

    
338
      return result
339
    return wrapper
340
  return decorator
341

    
342

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

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

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

    
363
  return env
364

    
365

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

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

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

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

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

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

    
394

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

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

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

    
411

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

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

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

422
  """
423

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

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

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

    
439

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

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

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

    
456

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

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

462
  @rtype: None
463

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

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

    
474

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

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

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

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

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

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

    
505

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

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

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

    
527

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

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

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

538
  @param modify_ssh_setup: boolean
539

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

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

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

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

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

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

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

    
573

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

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

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

    
593

    
594
def _GetHvInfo(name):
595
  """Retrieves node information from a hypervisor.
596

597
  The information returned depends on the hypervisor. Common items:
598

599
    - vg_size is the size of the configured volume group in MiB
600
    - vg_free is the free size of the volume group in MiB
601
    - memory_dom0 is the memory allocated for domain0 in MiB
602
    - memory_free is the currently available (free) ram in MiB
603
    - memory_total is the total number of ram in MiB
604
    - hv_version: the hypervisor version, if available
605

606
  """
607
  return hypervisor.GetHypervisor(name).GetNodeInfo()
608

    
609

    
610
def _GetNamedNodeInfo(names, fn):
611
  """Calls C{fn} for all names in C{names} and returns a dictionary.
612

613
  @rtype: None or dict
614

615
  """
616
  if names is None:
617
    return None
618
  else:
619
    return map(fn, names)
620

    
621

    
622
def GetNodeInfo(vg_names, hv_names, excl_stor):
623
  """Gives back a hash with different information about the node.
624

625
  @type vg_names: list of string
626
  @param vg_names: Names of the volume groups to ask for disk space information
627
  @type hv_names: list of string
628
  @param hv_names: Names of the hypervisors to ask for node information
629
  @type excl_stor: boolean
630
  @param excl_stor: Whether exclusive_storage is active
631
  @rtype: tuple; (string, None/dict, None/dict)
632
  @return: Tuple containing boot ID, volume group information and hypervisor
633
    information
634

635
  """
636
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
637
  vg_info = _GetNamedNodeInfo(vg_names, (lambda vg: _GetVgInfo(vg, excl_stor)))
638
  hv_info = _GetNamedNodeInfo(hv_names, _GetHvInfo)
639

    
640
  return (bootid, vg_info, hv_info)
641

    
642

    
643
def _CheckExclusivePvs(pvi_list):
644
  """Check that PVs are not shared among LVs
645

646
  @type pvi_list: list of L{objects.LvmPvInfo} objects
647
  @param pvi_list: information about the PVs
648

649
  @rtype: list of tuples (string, list of strings)
650
  @return: offending volumes, as tuples: (pv_name, [lv1_name, lv2_name...])
651

652
  """
653
  res = []
654
  for pvi in pvi_list:
655
    if len(pvi.lv_list) > 1:
656
      res.append((pvi.name, pvi.lv_list))
657
  return res
658

    
659

    
660
def VerifyNode(what, cluster_name):
661
  """Verify the status of the local node.
662

663
  Based on the input L{what} parameter, various checks are done on the
664
  local node.
665

666
  If the I{filelist} key is present, this list of
667
  files is checksummed and the file/checksum pairs are returned.
668

669
  If the I{nodelist} key is present, we check that we have
670
  connectivity via ssh with the target nodes (and check the hostname
671
  report).
672

673
  If the I{node-net-test} key is present, we check that we have
674
  connectivity to the given nodes via both primary IP and, if
675
  applicable, secondary IPs.
676

677
  @type what: C{dict}
678
  @param what: a dictionary of things to check:
679
      - filelist: list of files for which to compute checksums
680
      - nodelist: list of nodes we should check ssh communication with
681
      - node-net-test: list of nodes we should check node daemon port
682
        connectivity with
683
      - hypervisor: list with hypervisors to run the verify for
684
  @rtype: dict
685
  @return: a dictionary with the same keys as the input dict, and
686
      values representing the result of the checks
687

688
  """
689
  result = {}
690
  my_name = netutils.Hostname.GetSysName()
691
  port = netutils.GetDaemonPort(constants.NODED)
692
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
693

    
694
  if constants.NV_HYPERVISOR in what and vm_capable:
695
    result[constants.NV_HYPERVISOR] = tmp = {}
696
    for hv_name in what[constants.NV_HYPERVISOR]:
697
      try:
698
        val = hypervisor.GetHypervisor(hv_name).Verify()
699
      except errors.HypervisorError, err:
700
        val = "Error while checking hypervisor: %s" % str(err)
701
      tmp[hv_name] = val
702

    
703
  if constants.NV_HVPARAMS in what and vm_capable:
704
    result[constants.NV_HVPARAMS] = tmp = []
705
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
706
      try:
707
        logging.info("Validating hv %s, %s", hv_name, hvparms)
708
        hypervisor.GetHypervisor(hv_name).ValidateParameters(hvparms)
709
      except errors.HypervisorError, err:
710
        tmp.append((source, hv_name, str(err)))
711

    
712
  if constants.NV_FILELIST in what:
713
    fingerprints = utils.FingerprintFiles(map(vcluster.LocalizeVirtualPath,
714
                                              what[constants.NV_FILELIST]))
715
    result[constants.NV_FILELIST] = \
716
      dict((vcluster.MakeVirtualPath(key), value)
717
           for (key, value) in fingerprints.items())
718

    
719
  if constants.NV_NODELIST in what:
720
    (nodes, bynode) = what[constants.NV_NODELIST]
721

    
722
    # Add nodes from other groups (different for each node)
723
    try:
724
      nodes.extend(bynode[my_name])
725
    except KeyError:
726
      pass
727

    
728
    # Use a random order
729
    random.shuffle(nodes)
730

    
731
    # Try to contact all nodes
732
    val = {}
733
    for node in nodes:
734
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
735
      if not success:
736
        val[node] = message
737

    
738
    result[constants.NV_NODELIST] = val
739

    
740
  if constants.NV_NODENETTEST in what:
741
    result[constants.NV_NODENETTEST] = tmp = {}
742
    my_pip = my_sip = None
743
    for name, pip, sip in what[constants.NV_NODENETTEST]:
744
      if name == my_name:
745
        my_pip = pip
746
        my_sip = sip
747
        break
748
    if not my_pip:
749
      tmp[my_name] = ("Can't find my own primary/secondary IP"
750
                      " in the node list")
751
    else:
752
      for name, pip, sip in what[constants.NV_NODENETTEST]:
753
        fail = []
754
        if not netutils.TcpPing(pip, port, source=my_pip):
755
          fail.append("primary")
756
        if sip != pip:
757
          if not netutils.TcpPing(sip, port, source=my_sip):
758
            fail.append("secondary")
759
        if fail:
760
          tmp[name] = ("failure using the %s interface(s)" %
761
                       " and ".join(fail))
762

    
763
  if constants.NV_MASTERIP in what:
764
    # FIXME: add checks on incoming data structures (here and in the
765
    # rest of the function)
766
    master_name, master_ip = what[constants.NV_MASTERIP]
767
    if master_name == my_name:
768
      source = constants.IP4_ADDRESS_LOCALHOST
769
    else:
770
      source = None
771
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
772
                                                     source=source)
773

    
774
  if constants.NV_USERSCRIPTS in what:
775
    result[constants.NV_USERSCRIPTS] = \
776
      [script for script in what[constants.NV_USERSCRIPTS]
777
       if not utils.IsExecutable(script)]
778

    
779
  if constants.NV_OOB_PATHS in what:
780
    result[constants.NV_OOB_PATHS] = tmp = []
781
    for path in what[constants.NV_OOB_PATHS]:
782
      try:
783
        st = os.stat(path)
784
      except OSError, err:
785
        tmp.append("error stating out of band helper: %s" % err)
786
      else:
787
        if stat.S_ISREG(st.st_mode):
788
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
789
            tmp.append(None)
790
          else:
791
            tmp.append("out of band helper %s is not executable" % path)
792
        else:
793
          tmp.append("out of band helper %s is not a file" % path)
794

    
795
  if constants.NV_LVLIST in what and vm_capable:
796
    try:
797
      val = GetVolumeList(utils.ListVolumeGroups().keys())
798
    except RPCFail, err:
799
      val = str(err)
800
    result[constants.NV_LVLIST] = val
801

    
802
  if constants.NV_INSTANCELIST in what and vm_capable:
803
    # GetInstanceList can fail
804
    try:
805
      val = GetInstanceList(what[constants.NV_INSTANCELIST])
806
    except RPCFail, err:
807
      val = str(err)
808
    result[constants.NV_INSTANCELIST] = val
809

    
810
  if constants.NV_VGLIST in what and vm_capable:
811
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
812

    
813
  if constants.NV_PVLIST in what and vm_capable:
814
    check_exclusive_pvs = constants.NV_EXCLUSIVEPVS in what
815
    val = bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
816
                                       filter_allocatable=False,
817
                                       include_lvs=check_exclusive_pvs)
818
    if check_exclusive_pvs:
819
      result[constants.NV_EXCLUSIVEPVS] = _CheckExclusivePvs(val)
820
      for pvi in val:
821
        # Avoid sending useless data on the wire
822
        pvi.lv_list = []
823
    result[constants.NV_PVLIST] = map(objects.LvmPvInfo.ToDict, val)
824

    
825
  if constants.NV_VERSION in what:
826
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
827
                                    constants.RELEASE_VERSION)
828

    
829
  if constants.NV_HVINFO in what and vm_capable:
830
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
831
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
832

    
833
  if constants.NV_DRBDLIST in what and vm_capable:
834
    try:
835
      used_minors = drbd.DRBD8.GetUsedDevs().keys()
836
    except errors.BlockDeviceError, err:
837
      logging.warning("Can't get used minors list", exc_info=True)
838
      used_minors = str(err)
839
    result[constants.NV_DRBDLIST] = used_minors
840

    
841
  if constants.NV_DRBDHELPER in what and vm_capable:
842
    status = True
843
    try:
844
      payload = drbd.BaseDRBD.GetUsermodeHelper()
845
    except errors.BlockDeviceError, err:
846
      logging.error("Can't get DRBD usermode helper: %s", str(err))
847
      status = False
848
      payload = str(err)
849
    result[constants.NV_DRBDHELPER] = (status, payload)
850

    
851
  if constants.NV_NODESETUP in what:
852
    result[constants.NV_NODESETUP] = tmpr = []
853
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
854
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
855
                  " under /sys, missing required directories /sys/block"
856
                  " and /sys/class/net")
857
    if (not os.path.isdir("/proc/sys") or
858
        not os.path.isfile("/proc/sysrq-trigger")):
859
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
860
                  " under /proc, missing required directory /proc/sys and"
861
                  " the file /proc/sysrq-trigger")
862

    
863
  if constants.NV_TIME in what:
864
    result[constants.NV_TIME] = utils.SplitTime(time.time())
865

    
866
  if constants.NV_OSLIST in what and vm_capable:
867
    result[constants.NV_OSLIST] = DiagnoseOS()
868

    
869
  if constants.NV_BRIDGES in what and vm_capable:
870
    result[constants.NV_BRIDGES] = [bridge
871
                                    for bridge in what[constants.NV_BRIDGES]
872
                                    if not utils.BridgeExists(bridge)]
873

    
874
  if what.get(constants.NV_FILE_STORAGE_PATHS) == my_name:
875
    result[constants.NV_FILE_STORAGE_PATHS] = \
876
      bdev.ComputeWrongFileStoragePaths()
877

    
878
  return result
879

    
880

    
881
def GetBlockDevSizes(devices):
882
  """Return the size of the given block devices
883

884
  @type devices: list
885
  @param devices: list of block device nodes to query
886
  @rtype: dict
887
  @return:
888
    dictionary of all block devices under /dev (key). The value is their
889
    size in MiB.
890

891
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
892

893
  """
894
  DEV_PREFIX = "/dev/"
895
  blockdevs = {}
896

    
897
  for devpath in devices:
898
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
899
      continue
900

    
901
    try:
902
      st = os.stat(devpath)
903
    except EnvironmentError, err:
904
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
905
      continue
906

    
907
    if stat.S_ISBLK(st.st_mode):
908
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
909
      if result.failed:
910
        # We don't want to fail, just do not list this device as available
911
        logging.warning("Cannot get size for block device %s", devpath)
912
        continue
913

    
914
      size = int(result.stdout) / (1024 * 1024)
915
      blockdevs[devpath] = size
916
  return blockdevs
917

    
918

    
919
def GetVolumeList(vg_names):
920
  """Compute list of logical volumes and their size.
921

922
  @type vg_names: list
923
  @param vg_names: the volume groups whose LVs we should list, or
924
      empty for all volume groups
925
  @rtype: dict
926
  @return:
927
      dictionary of all partions (key) with value being a tuple of
928
      their size (in MiB), inactive and online status::
929

930
        {'xenvg/test1': ('20.06', True, True)}
931

932
      in case of errors, a string is returned with the error
933
      details.
934

935
  """
936
  lvs = {}
937
  sep = "|"
938
  if not vg_names:
939
    vg_names = []
940
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
941
                         "--separator=%s" % sep,
942
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
943
  if result.failed:
944
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
945

    
946
  for line in result.stdout.splitlines():
947
    line = line.strip()
948
    match = _LVSLINE_REGEX.match(line)
949
    if not match:
950
      logging.error("Invalid line returned from lvs output: '%s'", line)
951
      continue
952
    vg_name, name, size, attr = match.groups()
953
    inactive = attr[4] == "-"
954
    online = attr[5] == "o"
955
    virtual = attr[0] == "v"
956
    if virtual:
957
      # we don't want to report such volumes as existing, since they
958
      # don't really hold data
959
      continue
960
    lvs[vg_name + "/" + name] = (size, inactive, online)
961

    
962
  return lvs
963

    
964

    
965
def ListVolumeGroups():
966
  """List the volume groups and their size.
967

968
  @rtype: dict
969
  @return: dictionary with keys volume name and values the
970
      size of the volume
971

972
  """
973
  return utils.ListVolumeGroups()
974

    
975

    
976
def NodeVolumes():
977
  """List all volumes on this node.
978

979
  @rtype: list
980
  @return:
981
    A list of dictionaries, each having four keys:
982
      - name: the logical volume name,
983
      - size: the size of the logical volume
984
      - dev: the physical device on which the LV lives
985
      - vg: the volume group to which it belongs
986

987
    In case of errors, we return an empty list and log the
988
    error.
989

990
    Note that since a logical volume can live on multiple physical
991
    volumes, the resulting list might include a logical volume
992
    multiple times.
993

994
  """
995
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
996
                         "--separator=|",
997
                         "--options=lv_name,lv_size,devices,vg_name"])
998
  if result.failed:
999
    _Fail("Failed to list logical volumes, lvs output: %s",
1000
          result.output)
1001

    
1002
  def parse_dev(dev):
1003
    return dev.split("(")[0]
1004

    
1005
  def handle_dev(dev):
1006
    return [parse_dev(x) for x in dev.split(",")]
1007

    
1008
  def map_line(line):
1009
    line = [v.strip() for v in line]
1010
    return [{"name": line[0], "size": line[1],
1011
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
1012

    
1013
  all_devs = []
1014
  for line in result.stdout.splitlines():
1015
    if line.count("|") >= 3:
1016
      all_devs.extend(map_line(line.split("|")))
1017
    else:
1018
      logging.warning("Strange line in the output from lvs: '%s'", line)
1019
  return all_devs
1020

    
1021

    
1022
def BridgesExist(bridges_list):
1023
  """Check if a list of bridges exist on the current node.
1024

1025
  @rtype: boolean
1026
  @return: C{True} if all of them exist, C{False} otherwise
1027

1028
  """
1029
  missing = []
1030
  for bridge in bridges_list:
1031
    if not utils.BridgeExists(bridge):
1032
      missing.append(bridge)
1033

    
1034
  if missing:
1035
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
1036

    
1037

    
1038
def GetInstanceList(hypervisor_list):
1039
  """Provides a list of instances.
1040

1041
  @type hypervisor_list: list
1042
  @param hypervisor_list: the list of hypervisors to query information
1043

1044
  @rtype: list
1045
  @return: a list of all running instances on the current node
1046
    - instance1.example.com
1047
    - instance2.example.com
1048

1049
  """
1050
  results = []
1051
  for hname in hypervisor_list:
1052
    try:
1053
      names = hypervisor.GetHypervisor(hname).ListInstances()
1054
      results.extend(names)
1055
    except errors.HypervisorError, err:
1056
      _Fail("Error enumerating instances (hypervisor %s): %s",
1057
            hname, err, exc=True)
1058

    
1059
  return results
1060

    
1061

    
1062
def GetInstanceInfo(instance, hname):
1063
  """Gives back the information about an instance as a dictionary.
1064

1065
  @type instance: string
1066
  @param instance: the instance name
1067
  @type hname: string
1068
  @param hname: the hypervisor type of the instance
1069

1070
  @rtype: dict
1071
  @return: dictionary with the following keys:
1072
      - memory: memory size of instance (int)
1073
      - state: xen state of instance (string)
1074
      - time: cpu time of instance (float)
1075
      - vcpus: the number of vcpus (int)
1076

1077
  """
1078
  output = {}
1079

    
1080
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
1081
  if iinfo is not None:
1082
    output["memory"] = iinfo[2]
1083
    output["vcpus"] = iinfo[3]
1084
    output["state"] = iinfo[4]
1085
    output["time"] = iinfo[5]
1086

    
1087
  return output
1088

    
1089

    
1090
def GetInstanceMigratable(instance):
1091
  """Gives whether an instance can be migrated.
1092

1093
  @type instance: L{objects.Instance}
1094
  @param instance: object representing the instance to be checked.
1095

1096
  @rtype: tuple
1097
  @return: tuple of (result, description) where:
1098
      - result: whether the instance can be migrated or not
1099
      - description: a description of the issue, if relevant
1100

1101
  """
1102
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1103
  iname = instance.name
1104
  if iname not in hyper.ListInstances():
1105
    _Fail("Instance %s is not running", iname)
1106

    
1107
  for idx in range(len(instance.disks)):
1108
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1109
    if not os.path.islink(link_name):
1110
      logging.warning("Instance %s is missing symlink %s for disk %d",
1111
                      iname, link_name, idx)
1112

    
1113

    
1114
def GetAllInstancesInfo(hypervisor_list):
1115
  """Gather data about all instances.
1116

1117
  This is the equivalent of L{GetInstanceInfo}, except that it
1118
  computes data for all instances at once, thus being faster if one
1119
  needs data about more than one instance.
1120

1121
  @type hypervisor_list: list
1122
  @param hypervisor_list: list of hypervisors to query for instance data
1123

1124
  @rtype: dict
1125
  @return: dictionary of instance: data, with data having the following keys:
1126
      - memory: memory size of instance (int)
1127
      - state: xen state of instance (string)
1128
      - time: cpu time of instance (float)
1129
      - vcpus: the number of vcpus
1130

1131
  """
1132
  output = {}
1133

    
1134
  for hname in hypervisor_list:
1135
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
1136
    if iinfo:
1137
      for name, _, memory, vcpus, state, times in iinfo:
1138
        value = {
1139
          "memory": memory,
1140
          "vcpus": vcpus,
1141
          "state": state,
1142
          "time": times,
1143
          }
1144
        if name in output:
1145
          # we only check static parameters, like memory and vcpus,
1146
          # and not state and time which can change between the
1147
          # invocations of the different hypervisors
1148
          for key in "memory", "vcpus":
1149
            if value[key] != output[name][key]:
1150
              _Fail("Instance %s is running twice"
1151
                    " with different parameters", name)
1152
        output[name] = value
1153

    
1154
  return output
1155

    
1156

    
1157
def _InstanceLogName(kind, os_name, instance, component):
1158
  """Compute the OS log filename for a given instance and operation.
1159

1160
  The instance name and os name are passed in as strings since not all
1161
  operations have these as part of an instance object.
1162

1163
  @type kind: string
1164
  @param kind: the operation type (e.g. add, import, etc.)
1165
  @type os_name: string
1166
  @param os_name: the os name
1167
  @type instance: string
1168
  @param instance: the name of the instance being imported/added/etc.
1169
  @type component: string or None
1170
  @param component: the name of the component of the instance being
1171
      transferred
1172

1173
  """
1174
  # TODO: Use tempfile.mkstemp to create unique filename
1175
  if component:
1176
    assert "/" not in component
1177
    c_msg = "-%s" % component
1178
  else:
1179
    c_msg = ""
1180
  base = ("%s-%s-%s%s-%s.log" %
1181
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1182
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1183

    
1184

    
1185
def InstanceOsAdd(instance, reinstall, debug):
1186
  """Add an OS to an instance.
1187

1188
  @type instance: L{objects.Instance}
1189
  @param instance: Instance whose OS is to be installed
1190
  @type reinstall: boolean
1191
  @param reinstall: whether this is an instance reinstall
1192
  @type debug: integer
1193
  @param debug: debug level, passed to the OS scripts
1194
  @rtype: None
1195

1196
  """
1197
  inst_os = OSFromDisk(instance.os)
1198

    
1199
  create_env = OSEnvironment(instance, inst_os, debug)
1200
  if reinstall:
1201
    create_env["INSTANCE_REINSTALL"] = "1"
1202

    
1203
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1204

    
1205
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1206
                        cwd=inst_os.path, output=logfile, reset_env=True)
1207
  if result.failed:
1208
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1209
                  " output: %s", result.cmd, result.fail_reason, logfile,
1210
                  result.output)
1211
    lines = [utils.SafeEncode(val)
1212
             for val in utils.TailFile(logfile, lines=20)]
1213
    _Fail("OS create script failed (%s), last lines in the"
1214
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1215

    
1216

    
1217
def RunRenameInstance(instance, old_name, debug):
1218
  """Run the OS rename script for an instance.
1219

1220
  @type instance: L{objects.Instance}
1221
  @param instance: Instance whose OS is to be installed
1222
  @type old_name: string
1223
  @param old_name: previous instance name
1224
  @type debug: integer
1225
  @param debug: debug level, passed to the OS scripts
1226
  @rtype: boolean
1227
  @return: the success of the operation
1228

1229
  """
1230
  inst_os = OSFromDisk(instance.os)
1231

    
1232
  rename_env = OSEnvironment(instance, inst_os, debug)
1233
  rename_env["OLD_INSTANCE_NAME"] = old_name
1234

    
1235
  logfile = _InstanceLogName("rename", instance.os,
1236
                             "%s-%s" % (old_name, instance.name), None)
1237

    
1238
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1239
                        cwd=inst_os.path, output=logfile, reset_env=True)
1240

    
1241
  if result.failed:
1242
    logging.error("os create command '%s' returned error: %s output: %s",
1243
                  result.cmd, result.fail_reason, result.output)
1244
    lines = [utils.SafeEncode(val)
1245
             for val in utils.TailFile(logfile, lines=20)]
1246
    _Fail("OS rename script failed (%s), last lines in the"
1247
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1248

    
1249

    
1250
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1251
  """Returns symlink path for block device.
1252

1253
  """
1254
  if _dir is None:
1255
    _dir = pathutils.DISK_LINKS_DIR
1256

    
1257
  return utils.PathJoin(_dir,
1258
                        ("%s%s%s" %
1259
                         (instance_name, constants.DISK_SEPARATOR, idx)))
1260

    
1261

    
1262
def _SymlinkBlockDev(instance_name, device_path, idx):
1263
  """Set up symlinks to a instance's block device.
1264

1265
  This is an auxiliary function run when an instance is start (on the primary
1266
  node) or when an instance is migrated (on the target node).
1267

1268

1269
  @param instance_name: the name of the target instance
1270
  @param device_path: path of the physical block device, on the node
1271
  @param idx: the disk index
1272
  @return: absolute path to the disk's symlink
1273

1274
  """
1275
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1276
  try:
1277
    os.symlink(device_path, link_name)
1278
  except OSError, err:
1279
    if err.errno == errno.EEXIST:
1280
      if (not os.path.islink(link_name) or
1281
          os.readlink(link_name) != device_path):
1282
        os.remove(link_name)
1283
        os.symlink(device_path, link_name)
1284
    else:
1285
      raise
1286

    
1287
  return link_name
1288

    
1289

    
1290
def _RemoveBlockDevLinks(instance_name, disks):
1291
  """Remove the block device symlinks belonging to the given instance.
1292

1293
  """
1294
  for idx, _ in enumerate(disks):
1295
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1296
    if os.path.islink(link_name):
1297
      try:
1298
        os.remove(link_name)
1299
      except OSError:
1300
        logging.exception("Can't remove symlink '%s'", link_name)
1301

    
1302

    
1303
def _GatherAndLinkBlockDevs(instance):
1304
  """Set up an instance's block device(s).
1305

1306
  This is run on the primary node at instance startup. The block
1307
  devices must be already assembled.
1308

1309
  @type instance: L{objects.Instance}
1310
  @param instance: the instance whose disks we shoul assemble
1311
  @rtype: list
1312
  @return: list of (disk_object, device_path)
1313

1314
  """
1315
  block_devices = []
1316
  for idx, disk in enumerate(instance.disks):
1317
    device = _RecursiveFindBD(disk)
1318
    if device is None:
1319
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1320
                                    str(disk))
1321
    device.Open()
1322
    try:
1323
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1324
    except OSError, e:
1325
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1326
                                    e.strerror)
1327

    
1328
    block_devices.append((disk, link_name))
1329

    
1330
  return block_devices
1331

    
1332

    
1333
def StartInstance(instance, startup_paused):
1334
  """Start an instance.
1335

1336
  @type instance: L{objects.Instance}
1337
  @param instance: the instance object
1338
  @type startup_paused: bool
1339
  @param instance: pause instance at startup?
1340
  @rtype: None
1341

1342
  """
1343
  running_instances = GetInstanceList([instance.hypervisor])
1344

    
1345
  if instance.name in running_instances:
1346
    logging.info("Instance %s already running, not starting", instance.name)
1347
    return
1348

    
1349
  try:
1350
    block_devices = _GatherAndLinkBlockDevs(instance)
1351
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1352
    hyper.StartInstance(instance, block_devices, startup_paused)
1353
  except errors.BlockDeviceError, err:
1354
    _Fail("Block device error: %s", err, exc=True)
1355
  except errors.HypervisorError, err:
1356
    _RemoveBlockDevLinks(instance.name, instance.disks)
1357
    _Fail("Hypervisor error: %s", err, exc=True)
1358

    
1359

    
1360
def InstanceShutdown(instance, timeout):
1361
  """Shut an instance down.
1362

1363
  @note: this functions uses polling with a hardcoded timeout.
1364

1365
  @type instance: L{objects.Instance}
1366
  @param instance: the instance object
1367
  @type timeout: integer
1368
  @param timeout: maximum timeout for soft shutdown
1369
  @rtype: None
1370

1371
  """
1372
  hv_name = instance.hypervisor
1373
  hyper = hypervisor.GetHypervisor(hv_name)
1374
  iname = instance.name
1375

    
1376
  if instance.name not in hyper.ListInstances():
1377
    logging.info("Instance %s not running, doing nothing", iname)
1378
    return
1379

    
1380
  class _TryShutdown:
1381
    def __init__(self):
1382
      self.tried_once = False
1383

    
1384
    def __call__(self):
1385
      if iname not in hyper.ListInstances():
1386
        return
1387

    
1388
      try:
1389
        hyper.StopInstance(instance, retry=self.tried_once)
1390
      except errors.HypervisorError, err:
1391
        if iname not in hyper.ListInstances():
1392
          # if the instance is no longer existing, consider this a
1393
          # success and go to cleanup
1394
          return
1395

    
1396
        _Fail("Failed to stop instance %s: %s", iname, err)
1397

    
1398
      self.tried_once = True
1399

    
1400
      raise utils.RetryAgain()
1401

    
1402
  try:
1403
    utils.Retry(_TryShutdown(), 5, timeout)
1404
  except utils.RetryTimeout:
1405
    # the shutdown did not succeed
1406
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1407

    
1408
    try:
1409
      hyper.StopInstance(instance, force=True)
1410
    except errors.HypervisorError, err:
1411
      if iname in hyper.ListInstances():
1412
        # only raise an error if the instance still exists, otherwise
1413
        # the error could simply be "instance ... unknown"!
1414
        _Fail("Failed to force stop instance %s: %s", iname, err)
1415

    
1416
    time.sleep(1)
1417

    
1418
    if iname in hyper.ListInstances():
1419
      _Fail("Could not shutdown instance %s even by destroy", iname)
1420

    
1421
  try:
1422
    hyper.CleanupInstance(instance.name)
1423
  except errors.HypervisorError, err:
1424
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1425

    
1426
  _RemoveBlockDevLinks(iname, instance.disks)
1427

    
1428

    
1429
def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1430
  """Reboot an instance.
1431

1432
  @type instance: L{objects.Instance}
1433
  @param instance: the instance object to reboot
1434
  @type reboot_type: str
1435
  @param reboot_type: the type of reboot, one the following
1436
    constants:
1437
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1438
        instance OS, do not recreate the VM
1439
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1440
        restart the VM (at the hypervisor level)
1441
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1442
        not accepted here, since that mode is handled differently, in
1443
        cmdlib, and translates into full stop and start of the
1444
        instance (instead of a call_instance_reboot RPC)
1445
  @type shutdown_timeout: integer
1446
  @param shutdown_timeout: maximum timeout for soft shutdown
1447
  @type reason: list of reasons
1448
  @param reason: the reason trail for this reboot
1449
  @rtype: None
1450

1451
  """
1452
  running_instances = GetInstanceList([instance.hypervisor])
1453

    
1454
  if instance.name not in running_instances:
1455
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1456

    
1457
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1458
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1459
    try:
1460
      hyper.RebootInstance(instance)
1461
    except errors.HypervisorError, err:
1462
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1463
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1464
    try:
1465
      InstanceShutdown(instance, shutdown_timeout)
1466
      result = StartInstance(instance, False)
1467
      _StoreInstReasonTrail(instance.name, reason)
1468
      return result
1469
    except errors.HypervisorError, err:
1470
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1471
  else:
1472
    _Fail("Invalid reboot_type received: %s", reboot_type)
1473

    
1474

    
1475
def InstanceBalloonMemory(instance, memory):
1476
  """Resize an instance's memory.
1477

1478
  @type instance: L{objects.Instance}
1479
  @param instance: the instance object
1480
  @type memory: int
1481
  @param memory: new memory amount in MB
1482
  @rtype: None
1483

1484
  """
1485
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1486
  running = hyper.ListInstances()
1487
  if instance.name not in running:
1488
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1489
    return
1490
  try:
1491
    hyper.BalloonInstanceMemory(instance, memory)
1492
  except errors.HypervisorError, err:
1493
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1494

    
1495

    
1496
def MigrationInfo(instance):
1497
  """Gather information about an instance to be migrated.
1498

1499
  @type instance: L{objects.Instance}
1500
  @param instance: the instance definition
1501

1502
  """
1503
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1504
  try:
1505
    info = hyper.MigrationInfo(instance)
1506
  except errors.HypervisorError, err:
1507
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1508
  return info
1509

    
1510

    
1511
def AcceptInstance(instance, info, target):
1512
  """Prepare the node to accept an instance.
1513

1514
  @type instance: L{objects.Instance}
1515
  @param instance: the instance definition
1516
  @type info: string/data (opaque)
1517
  @param info: migration information, from the source node
1518
  @type target: string
1519
  @param target: target host (usually ip), on this node
1520

1521
  """
1522
  # TODO: why is this required only for DTS_EXT_MIRROR?
1523
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1524
    # Create the symlinks, as the disks are not active
1525
    # in any way
1526
    try:
1527
      _GatherAndLinkBlockDevs(instance)
1528
    except errors.BlockDeviceError, err:
1529
      _Fail("Block device error: %s", err, exc=True)
1530

    
1531
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1532
  try:
1533
    hyper.AcceptInstance(instance, info, target)
1534
  except errors.HypervisorError, err:
1535
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1536
      _RemoveBlockDevLinks(instance.name, instance.disks)
1537
    _Fail("Failed to accept instance: %s", err, exc=True)
1538

    
1539

    
1540
def FinalizeMigrationDst(instance, info, success):
1541
  """Finalize any preparation to accept an instance.
1542

1543
  @type instance: L{objects.Instance}
1544
  @param instance: the instance definition
1545
  @type info: string/data (opaque)
1546
  @param info: migration information, from the source node
1547
  @type success: boolean
1548
  @param success: whether the migration was a success or a failure
1549

1550
  """
1551
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1552
  try:
1553
    hyper.FinalizeMigrationDst(instance, info, success)
1554
  except errors.HypervisorError, err:
1555
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1556

    
1557

    
1558
def MigrateInstance(instance, target, live):
1559
  """Migrates an instance to another node.
1560

1561
  @type instance: L{objects.Instance}
1562
  @param instance: the instance definition
1563
  @type target: string
1564
  @param target: the target node name
1565
  @type live: boolean
1566
  @param live: whether the migration should be done live or not (the
1567
      interpretation of this parameter is left to the hypervisor)
1568
  @raise RPCFail: if migration fails for some reason
1569

1570
  """
1571
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1572

    
1573
  try:
1574
    hyper.MigrateInstance(instance, target, live)
1575
  except errors.HypervisorError, err:
1576
    _Fail("Failed to migrate instance: %s", err, exc=True)
1577

    
1578

    
1579
def FinalizeMigrationSource(instance, success, live):
1580
  """Finalize the instance migration on the source node.
1581

1582
  @type instance: L{objects.Instance}
1583
  @param instance: the instance definition of the migrated instance
1584
  @type success: bool
1585
  @param success: whether the migration succeeded or not
1586
  @type live: bool
1587
  @param live: whether the user requested a live migration or not
1588
  @raise RPCFail: If the execution fails for some reason
1589

1590
  """
1591
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1592

    
1593
  try:
1594
    hyper.FinalizeMigrationSource(instance, success, live)
1595
  except Exception, err:  # pylint: disable=W0703
1596
    _Fail("Failed to finalize the migration on the source node: %s", err,
1597
          exc=True)
1598

    
1599

    
1600
def GetMigrationStatus(instance):
1601
  """Get the migration status
1602

1603
  @type instance: L{objects.Instance}
1604
  @param instance: the instance that is being migrated
1605
  @rtype: L{objects.MigrationStatus}
1606
  @return: the status of the current migration (one of
1607
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1608
           progress info that can be retrieved from the hypervisor
1609
  @raise RPCFail: If the migration status cannot be retrieved
1610

1611
  """
1612
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1613
  try:
1614
    return hyper.GetMigrationStatus(instance)
1615
  except Exception, err:  # pylint: disable=W0703
1616
    _Fail("Failed to get migration status: %s", err, exc=True)
1617

    
1618

    
1619
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
1620
  """Creates a block device for an instance.
1621

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

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

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

    
1661
  try:
1662
    device = bdev.Create(disk, clist, excl_stor)
1663
  except errors.BlockDeviceError, err:
1664
    _Fail("Can't create block device: %s", err)
1665

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

    
1679
  device.SetInfo(info)
1680

    
1681
  return device.unique_id
1682

    
1683

    
1684
def _WipeDevice(path, offset, size):
1685
  """This function actually wipes the device.
1686

1687
  @param path: The path to the device to wipe
1688
  @param offset: The offset in MiB in the file
1689
  @param size: The size in MiB to write
1690

1691
  """
1692
  # Internal sizes are always in Mebibytes; if the following "dd" command
1693
  # should use a different block size the offset and size given to this
1694
  # function must be adjusted accordingly before being passed to "dd".
1695
  block_size = 1024 * 1024
1696

    
1697
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1698
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
1699
         "count=%d" % size]
1700
  result = utils.RunCmd(cmd)
1701

    
1702
  if result.failed:
1703
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1704
          result.fail_reason, result.output)
1705

    
1706

    
1707
def BlockdevWipe(disk, offset, size):
1708
  """Wipes a block device.
1709

1710
  @type disk: L{objects.Disk}
1711
  @param disk: the disk object we want to wipe
1712
  @type offset: int
1713
  @param offset: The offset in MiB in the file
1714
  @type size: int
1715
  @param size: The size in MiB to write
1716

1717
  """
1718
  try:
1719
    rdev = _RecursiveFindBD(disk)
1720
  except errors.BlockDeviceError:
1721
    rdev = None
1722

    
1723
  if not rdev:
1724
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1725

    
1726
  # Do cross verify some of the parameters
1727
  if offset < 0:
1728
    _Fail("Negative offset")
1729
  if size < 0:
1730
    _Fail("Negative size")
1731
  if offset > rdev.size:
1732
    _Fail("Offset is bigger than device size")
1733
  if (offset + size) > rdev.size:
1734
    _Fail("The provided offset and size to wipe is bigger than device size")
1735

    
1736
  _WipeDevice(rdev.dev_path, offset, size)
1737

    
1738

    
1739
def BlockdevPauseResumeSync(disks, pause):
1740
  """Pause or resume the sync of the block device.
1741

1742
  @type disks: list of L{objects.Disk}
1743
  @param disks: the disks object we want to pause/resume
1744
  @type pause: bool
1745
  @param pause: Wheater to pause or resume
1746

1747
  """
1748
  success = []
1749
  for disk in disks:
1750
    try:
1751
      rdev = _RecursiveFindBD(disk)
1752
    except errors.BlockDeviceError:
1753
      rdev = None
1754

    
1755
    if not rdev:
1756
      success.append((False, ("Cannot change sync for device %s:"
1757
                              " device not found" % disk.iv_name)))
1758
      continue
1759

    
1760
    result = rdev.PauseResumeSync(pause)
1761

    
1762
    if result:
1763
      success.append((result, None))
1764
    else:
1765
      if pause:
1766
        msg = "Pause"
1767
      else:
1768
        msg = "Resume"
1769
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1770

    
1771
  return success
1772

    
1773

    
1774
def BlockdevRemove(disk):
1775
  """Remove a block device.
1776

1777
  @note: This is intended to be called recursively.
1778

1779
  @type disk: L{objects.Disk}
1780
  @param disk: the disk object we should remove
1781
  @rtype: boolean
1782
  @return: the success of the operation
1783

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

    
1801
  if disk.children:
1802
    for child in disk.children:
1803
      try:
1804
        BlockdevRemove(child)
1805
      except RPCFail, err:
1806
        msgs.append(str(err))
1807

    
1808
  if msgs:
1809
    _Fail("; ".join(msgs))
1810

    
1811

    
1812
def _RecursiveAssembleBD(disk, owner, as_primary):
1813
  """Activate a block device for an instance.
1814

1815
  This is run on the primary and secondary nodes for an instance.
1816

1817
  @note: this function is called recursively.
1818

1819
  @type disk: L{objects.Disk}
1820
  @param disk: the disk we try to assemble
1821
  @type owner: str
1822
  @param owner: the name of the instance which owns the disk
1823
  @type as_primary: boolean
1824
  @param as_primary: if we should make the block device
1825
      read/write
1826

1827
  @return: the assembled device or None (in case no device
1828
      was assembled)
1829
  @raise errors.BlockDeviceError: in case there is an error
1830
      during the activation of the children or the device
1831
      itself
1832

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

    
1852
  if as_primary or disk.AssembleOnSecondary():
1853
    r_dev = bdev.Assemble(disk, children)
1854
    result = r_dev
1855
    if as_primary or disk.OpenOnSecondary():
1856
      r_dev.Open()
1857
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1858
                                as_primary, disk.iv_name)
1859

    
1860
  else:
1861
    result = True
1862
  return result
1863

    
1864

    
1865
def BlockdevAssemble(disk, owner, as_primary, idx):
1866
  """Activate a block device for an instance.
1867

1868
  This is a wrapper over _RecursiveAssembleBD.
1869

1870
  @rtype: str or boolean
1871
  @return: a C{/dev/...} path for primary nodes, and
1872
      C{True} for secondary nodes
1873

1874
  """
1875
  try:
1876
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1877
    if isinstance(result, BlockDev):
1878
      # pylint: disable=E1103
1879
      result = result.dev_path
1880
      if as_primary:
1881
        _SymlinkBlockDev(owner, result, idx)
1882
  except errors.BlockDeviceError, err:
1883
    _Fail("Error while assembling disk: %s", err, exc=True)
1884
  except OSError, err:
1885
    _Fail("Error while symlinking disk: %s", err, exc=True)
1886

    
1887
  return result
1888

    
1889

    
1890
def BlockdevShutdown(disk):
1891
  """Shut down a block device.
1892

1893
  First, if the device is assembled (Attach() is successful), then
1894
  the device is shutdown. Then the children of the device are
1895
  shutdown.
1896

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

1901
  @type disk: L{objects.Disk}
1902
  @param disk: the description of the disk we should
1903
      shutdown
1904
  @rtype: None
1905

1906
  """
1907
  msgs = []
1908
  r_dev = _RecursiveFindBD(disk)
1909
  if r_dev is not None:
1910
    r_path = r_dev.dev_path
1911
    try:
1912
      r_dev.Shutdown()
1913
      DevCacheManager.RemoveCache(r_path)
1914
    except errors.BlockDeviceError, err:
1915
      msgs.append(str(err))
1916

    
1917
  if disk.children:
1918
    for child in disk.children:
1919
      try:
1920
        BlockdevShutdown(child)
1921
      except RPCFail, err:
1922
        msgs.append(str(err))
1923

    
1924
  if msgs:
1925
    _Fail("; ".join(msgs))
1926

    
1927

    
1928
def BlockdevAddchildren(parent_cdev, new_cdevs):
1929
  """Extend a mirrored block device.
1930

1931
  @type parent_cdev: L{objects.Disk}
1932
  @param parent_cdev: the disk to which we should add children
1933
  @type new_cdevs: list of L{objects.Disk}
1934
  @param new_cdevs: the list of children which we should add
1935
  @rtype: None
1936

1937
  """
1938
  parent_bdev = _RecursiveFindBD(parent_cdev)
1939
  if parent_bdev is None:
1940
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1941
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1942
  if new_bdevs.count(None) > 0:
1943
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1944
  parent_bdev.AddChildren(new_bdevs)
1945

    
1946

    
1947
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1948
  """Shrink a mirrored block device.
1949

1950
  @type parent_cdev: L{objects.Disk}
1951
  @param parent_cdev: the disk from which we should remove children
1952
  @type new_cdevs: list of L{objects.Disk}
1953
  @param new_cdevs: the list of children which we should remove
1954
  @rtype: None
1955

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

    
1975

    
1976
def BlockdevGetmirrorstatus(disks):
1977
  """Get the mirroring status of a list of devices.
1978

1979
  @type disks: list of L{objects.Disk}
1980
  @param disks: the list of disks which we should query
1981
  @rtype: disk
1982
  @return: List of L{objects.BlockDevStatus}, one for each disk
1983
  @raise errors.BlockDeviceError: if any of the disks cannot be
1984
      found
1985

1986
  """
1987
  stats = []
1988
  for dsk in disks:
1989
    rbd = _RecursiveFindBD(dsk)
1990
    if rbd is None:
1991
      _Fail("Can't find device %s", dsk)
1992

    
1993
    stats.append(rbd.CombinedSyncStatus())
1994

    
1995
  return stats
1996

    
1997

    
1998
def BlockdevGetmirrorstatusMulti(disks):
1999
  """Get the mirroring status of a list of devices.
2000

2001
  @type disks: list of L{objects.Disk}
2002
  @param disks: the list of disks which we should query
2003
  @rtype: disk
2004
  @return: List of tuples, (bool, status), one for each disk; bool denotes
2005
    success/failure, status is L{objects.BlockDevStatus} on success, string
2006
    otherwise
2007

2008
  """
2009
  result = []
2010
  for disk in disks:
2011
    try:
2012
      rbd = _RecursiveFindBD(disk)
2013
      if rbd is None:
2014
        result.append((False, "Can't find device %s" % disk))
2015
        continue
2016

    
2017
      status = rbd.CombinedSyncStatus()
2018
    except errors.BlockDeviceError, err:
2019
      logging.exception("Error while getting disk status")
2020
      result.append((False, str(err)))
2021
    else:
2022
      result.append((True, status))
2023

    
2024
  assert len(disks) == len(result)
2025

    
2026
  return result
2027

    
2028

    
2029
def _RecursiveFindBD(disk):
2030
  """Check if a device is activated.
2031

2032
  If so, return information about the real device.
2033

2034
  @type disk: L{objects.Disk}
2035
  @param disk: the disk object we need to find
2036

2037
  @return: None if the device can't be found,
2038
      otherwise the device instance
2039

2040
  """
2041
  children = []
2042
  if disk.children:
2043
    for chdisk in disk.children:
2044
      children.append(_RecursiveFindBD(chdisk))
2045

    
2046
  return bdev.FindDevice(disk, children)
2047

    
2048

    
2049
def _OpenRealBD(disk):
2050
  """Opens the underlying block device of a disk.
2051

2052
  @type disk: L{objects.Disk}
2053
  @param disk: the disk object we want to open
2054

2055
  """
2056
  real_disk = _RecursiveFindBD(disk)
2057
  if real_disk is None:
2058
    _Fail("Block device '%s' is not set up", disk)
2059

    
2060
  real_disk.Open()
2061

    
2062
  return real_disk
2063

    
2064

    
2065
def BlockdevFind(disk):
2066
  """Check if a device is activated.
2067

2068
  If it is, return information about the real device.
2069

2070
  @type disk: L{objects.Disk}
2071
  @param disk: the disk to find
2072
  @rtype: None or objects.BlockDevStatus
2073
  @return: None if the disk cannot be found, otherwise a the current
2074
           information
2075

2076
  """
2077
  try:
2078
    rbd = _RecursiveFindBD(disk)
2079
  except errors.BlockDeviceError, err:
2080
    _Fail("Failed to find device: %s", err, exc=True)
2081

    
2082
  if rbd is None:
2083
    return None
2084

    
2085
  return rbd.GetSyncStatus()
2086

    
2087

    
2088
def BlockdevGetsize(disks):
2089
  """Computes the size of the given disks.
2090

2091
  If a disk is not found, returns None instead.
2092

2093
  @type disks: list of L{objects.Disk}
2094
  @param disks: the list of disk to compute the size for
2095
  @rtype: list
2096
  @return: list with elements None if the disk cannot be found,
2097
      otherwise the size
2098

2099
  """
2100
  result = []
2101
  for cf in disks:
2102
    try:
2103
      rbd = _RecursiveFindBD(cf)
2104
    except errors.BlockDeviceError:
2105
      result.append(None)
2106
      continue
2107
    if rbd is None:
2108
      result.append(None)
2109
    else:
2110
      result.append(rbd.GetActualSize())
2111
  return result
2112

    
2113

    
2114
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2115
  """Export a block device to a remote node.
2116

2117
  @type disk: L{objects.Disk}
2118
  @param disk: the description of the disk to export
2119
  @type dest_node: str
2120
  @param dest_node: the destination node to export to
2121
  @type dest_path: str
2122
  @param dest_path: the destination path on the target node
2123
  @type cluster_name: str
2124
  @param cluster_name: the cluster name, needed for SSH hostalias
2125
  @rtype: None
2126

2127
  """
2128
  real_disk = _OpenRealBD(disk)
2129

    
2130
  # the block size on the read dd is 1MiB to match our units
2131
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2132
                               "dd if=%s bs=1048576 count=%s",
2133
                               real_disk.dev_path, str(disk.size))
2134

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

    
2144
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2145
                                                   constants.SSH_LOGIN_USER,
2146
                                                   destcmd)
2147

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

    
2151
  result = utils.RunCmd(["bash", "-c", command])
2152

    
2153
  if result.failed:
2154
    _Fail("Disk copy command '%s' returned error: %s"
2155
          " output: %s", command, result.fail_reason, result.output)
2156

    
2157

    
2158
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2159
  """Write a file to the filesystem.
2160

2161
  This allows the master to overwrite(!) a file. It will only perform
2162
  the operation if the file belongs to a list of configuration files.
2163

2164
  @type file_name: str
2165
  @param file_name: the target file name
2166
  @type data: str
2167
  @param data: the new contents of the file
2168
  @type mode: int
2169
  @param mode: the mode to give the file (can be None)
2170
  @type uid: string
2171
  @param uid: the owner of the file
2172
  @type gid: string
2173
  @param gid: the group of the file
2174
  @type atime: float
2175
  @param atime: the atime to set on the file (can be None)
2176
  @type mtime: float
2177
  @param mtime: the mtime to set on the file (can be None)
2178
  @rtype: None
2179

2180
  """
2181
  file_name = vcluster.LocalizeVirtualPath(file_name)
2182

    
2183
  if not os.path.isabs(file_name):
2184
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2185

    
2186
  if file_name not in _ALLOWED_UPLOAD_FILES:
2187
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2188
          file_name)
2189

    
2190
  raw_data = _Decompress(data)
2191

    
2192
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2193
    _Fail("Invalid username/groupname type")
2194

    
2195
  getents = runtime.GetEnts()
2196
  uid = getents.LookupUser(uid)
2197
  gid = getents.LookupGroup(gid)
2198

    
2199
  utils.SafeWriteFile(file_name, None,
2200
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2201
                      atime=atime, mtime=mtime)
2202

    
2203

    
2204
def RunOob(oob_program, command, node, timeout):
2205
  """Executes oob_program with given command on given node.
2206

2207
  @param oob_program: The path to the executable oob_program
2208
  @param command: The command to invoke on oob_program
2209
  @param node: The node given as an argument to the program
2210
  @param timeout: Timeout after which we kill the oob program
2211

2212
  @return: stdout
2213
  @raise RPCFail: If execution fails for some reason
2214

2215
  """
2216
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2217

    
2218
  if result.failed:
2219
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2220
          result.fail_reason, result.output)
2221

    
2222
  return result.stdout
2223

    
2224

    
2225
def _OSOndiskAPIVersion(os_dir):
2226
  """Compute and return the API version of a given OS.
2227

2228
  This function will try to read the API version of the OS residing in
2229
  the 'os_dir' directory.
2230

2231
  @type os_dir: str
2232
  @param os_dir: the directory in which we should look for the OS
2233
  @rtype: tuple
2234
  @return: tuple (status, data) with status denoting the validity and
2235
      data holding either the vaid versions or an error message
2236

2237
  """
2238
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2239

    
2240
  try:
2241
    st = os.stat(api_file)
2242
  except EnvironmentError, err:
2243
    return False, ("Required file '%s' not found under path %s: %s" %
2244
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2245

    
2246
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2247
    return False, ("File '%s' in %s is not a regular file" %
2248
                   (constants.OS_API_FILE, os_dir))
2249

    
2250
  try:
2251
    api_versions = utils.ReadFile(api_file).splitlines()
2252
  except EnvironmentError, err:
2253
    return False, ("Error while reading the API version file at %s: %s" %
2254
                   (api_file, utils.ErrnoOrStr(err)))
2255

    
2256
  try:
2257
    api_versions = [int(version.strip()) for version in api_versions]
2258
  except (TypeError, ValueError), err:
2259
    return False, ("API version(s) can't be converted to integer: %s" %
2260
                   str(err))
2261

    
2262
  return True, api_versions
2263

    
2264

    
2265
def DiagnoseOS(top_dirs=None):
2266
  """Compute the validity for all OSes.
2267

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

2284
  """
2285
  if top_dirs is None:
2286
    top_dirs = pathutils.OS_SEARCH_PATH
2287

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

    
2310
  return result
2311

    
2312

    
2313
def _TryOSFromDisk(name, base_dir=None):
2314
  """Create an OS instance from disk.
2315

2316
  This function will return an OS instance if the given name is a
2317
  valid OS name.
2318

2319
  @type base_dir: string
2320
  @keyword base_dir: Base directory containing OS installations.
2321
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2322
  @rtype: tuple
2323
  @return: success and either the OS instance if we find a valid one,
2324
      or error message
2325

2326
  """
2327
  if base_dir is None:
2328
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2329
  else:
2330
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2331

    
2332
  if os_dir is None:
2333
    return False, "Directory for OS %s not found in search path" % name
2334

    
2335
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2336
  if not status:
2337
    # push the error up
2338
    return status, api_versions
2339

    
2340
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2341
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2342
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2343

    
2344
  # OS Files dictionary, we will populate it with the absolute path
2345
  # names; if the value is True, then it is a required file, otherwise
2346
  # an optional one
2347
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2348

    
2349
  if max(api_versions) >= constants.OS_API_V15:
2350
    os_files[constants.OS_VARIANTS_FILE] = False
2351

    
2352
  if max(api_versions) >= constants.OS_API_V20:
2353
    os_files[constants.OS_PARAMETERS_FILE] = True
2354
  else:
2355
    del os_files[constants.OS_SCRIPT_VERIFY]
2356

    
2357
  for (filename, required) in os_files.items():
2358
    os_files[filename] = utils.PathJoin(os_dir, filename)
2359

    
2360
    try:
2361
      st = os.stat(os_files[filename])
2362
    except EnvironmentError, err:
2363
      if err.errno == errno.ENOENT and not required:
2364
        del os_files[filename]
2365
        continue
2366
      return False, ("File '%s' under path '%s' is missing (%s)" %
2367
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2368

    
2369
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2370
      return False, ("File '%s' under path '%s' is not a regular file" %
2371
                     (filename, os_dir))
2372

    
2373
    if filename in constants.OS_SCRIPTS:
2374
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2375
        return False, ("File '%s' under path '%s' is not executable" %
2376
                       (filename, os_dir))
2377

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

    
2390
  parameters = []
2391
  if constants.OS_PARAMETERS_FILE in os_files:
2392
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2393
    try:
2394
      parameters = utils.ReadFile(parameters_file).splitlines()
2395
    except EnvironmentError, err:
2396
      return False, ("Error while reading the OS parameters file at %s: %s" %
2397
                     (parameters_file, utils.ErrnoOrStr(err)))
2398
    parameters = [v.split(None, 1) for v in parameters]
2399

    
2400
  os_obj = objects.OS(name=name, path=os_dir,
2401
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2402
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2403
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2404
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2405
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2406
                                                 None),
2407
                      supported_variants=variants,
2408
                      supported_parameters=parameters,
2409
                      api_versions=api_versions)
2410
  return True, os_obj
2411

    
2412

    
2413
def OSFromDisk(name, base_dir=None):
2414
  """Create an OS instance from disk.
2415

2416
  This function will return an OS instance if the given name is a
2417
  valid OS name. Otherwise, it will raise an appropriate
2418
  L{RPCFail} exception, detailing why this is not a valid OS.
2419

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

2423
  @type base_dir: string
2424
  @keyword base_dir: Base directory containing OS installations.
2425
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2426
  @rtype: L{objects.OS}
2427
  @return: the OS instance if we find a valid one
2428
  @raise RPCFail: if we don't find a valid OS
2429

2430
  """
2431
  name_only = objects.OS.GetName(name)
2432
  status, payload = _TryOSFromDisk(name_only, base_dir)
2433

    
2434
  if not status:
2435
    _Fail(payload)
2436

    
2437
  return payload
2438

    
2439

    
2440
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2441
  """Calculate the basic environment for an os script.
2442

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

2456
  """
2457
  result = {}
2458
  api_version = \
2459
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2460
  result["OS_API_VERSION"] = "%d" % api_version
2461
  result["OS_NAME"] = inst_os.name
2462
  result["DEBUG_LEVEL"] = "%d" % debug
2463

    
2464
  # OS variants
2465
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2466
    variant = objects.OS.GetVariant(os_name)
2467
    if not variant:
2468
      variant = inst_os.supported_variants[0]
2469
  else:
2470
    variant = ""
2471
  result["OS_VARIANT"] = variant
2472

    
2473
  # OS params
2474
  for pname, pvalue in os_params.items():
2475
    result["OSP_%s" % pname.upper()] = pvalue
2476

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

    
2482
  return result
2483

    
2484

    
2485
def OSEnvironment(instance, inst_os, debug=0):
2486
  """Calculate the environment for an os script.
2487

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

2499
  """
2500
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2501

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

    
2505
  result["HYPERVISOR"] = instance.hypervisor
2506
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2507
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2508
  result["INSTANCE_SECONDARY_NODES"] = \
2509
      ("%s" % " ".join(instance.secondary_nodes))
2510

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

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

    
2542
  # HV/BE params
2543
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2544
    for key, value in source.items():
2545
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2546

    
2547
  return result
2548

    
2549

    
2550
def DiagnoseExtStorage(top_dirs=None):
2551
  """Compute the validity for all ExtStorage Providers.
2552

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

2568
  """
2569
  if top_dirs is None:
2570
    top_dirs = pathutils.ES_SEARCH_PATH
2571

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

    
2592
  return result
2593

    
2594

    
2595
def BlockdevGrow(disk, amount, dryrun, backingstore):
2596
  """Grow a stack of block devices.
2597

2598
  This function is called recursively, with the childrens being the
2599
  first ones to resize.
2600

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

2615
  """
2616
  r_dev = _RecursiveFindBD(disk)
2617
  if r_dev is None:
2618
    _Fail("Cannot find block device %s", disk)
2619

    
2620
  try:
2621
    r_dev.Grow(amount, dryrun, backingstore)
2622
  except errors.BlockDeviceError, err:
2623
    _Fail("Failed to grow block device: %s", err, exc=True)
2624

    
2625

    
2626
def BlockdevSnapshot(disk):
2627
  """Create a snapshot copy of a block device.
2628

2629
  This function is called recursively, and the snapshot is actually created
2630
  just for the leaf lvm backend device.
2631

2632
  @type disk: L{objects.Disk}
2633
  @param disk: the disk to be snapshotted
2634
  @rtype: string
2635
  @return: snapshot disk ID as (vg, lv)
2636

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

    
2655

    
2656
def BlockdevSetInfo(disk, info):
2657
  """Sets 'metadata' information on block devices.
2658

2659
  This function sets 'info' metadata on block devices. Initial
2660
  information is set at device creation; this function should be used
2661
  for example after renames.
2662

2663
  @type disk: L{objects.Disk}
2664
  @param disk: the disk to be grown
2665
  @type info: string
2666
  @param info: new 'info' metadata
2667
  @rtype: (status, result)
2668
  @return: a tuple with the status of the operation (True/False), and
2669
      the errors message if status is False
2670

2671
  """
2672
  r_dev = _RecursiveFindBD(disk)
2673
  if r_dev is None:
2674
    _Fail("Cannot find block device %s", disk)
2675

    
2676
  try:
2677
    r_dev.SetInfo(info)
2678
  except errors.BlockDeviceError, err:
2679
    _Fail("Failed to set information on block device: %s", err, exc=True)
2680

    
2681

    
2682
def FinalizeExport(instance, snap_disks):
2683
  """Write out the export configuration information.
2684

2685
  @type instance: L{objects.Instance}
2686
  @param instance: the instance which we export, used for
2687
      saving configuration
2688
  @type snap_disks: list of L{objects.Disk}
2689
  @param snap_disks: list of snapshot block devices, which
2690
      will be used to get the actual name of the dump file
2691

2692
  @rtype: None
2693

2694
  """
2695
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
2696
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
2697

    
2698
  config = objects.SerializableConfigParser()
2699

    
2700
  config.add_section(constants.INISECT_EXP)
2701
  config.set(constants.INISECT_EXP, "version", "0")
2702
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2703
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2704
  config.set(constants.INISECT_EXP, "os", instance.os)
2705
  config.set(constants.INISECT_EXP, "compression", "none")
2706

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

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

    
2736
  disk_total = 0
2737
  for disk_count, disk in enumerate(snap_disks):
2738
    if disk:
2739
      disk_total += 1
2740
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2741
                 ("%s" % disk.iv_name))
2742
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2743
                 ("%s" % disk.physical_id[1]))
2744
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2745
                 ("%d" % disk.size))
2746

    
2747
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2748

    
2749
  # New-style hypervisor/backend parameters
2750

    
2751
  config.add_section(constants.INISECT_HYP)
2752
  for name, value in instance.hvparams.items():
2753
    if name not in constants.HVC_GLOBALS:
2754
      config.set(constants.INISECT_HYP, name, str(value))
2755

    
2756
  config.add_section(constants.INISECT_BEP)
2757
  for name, value in instance.beparams.items():
2758
    config.set(constants.INISECT_BEP, name, str(value))
2759

    
2760
  config.add_section(constants.INISECT_OSP)
2761
  for name, value in instance.osparams.items():
2762
    config.set(constants.INISECT_OSP, name, str(value))
2763

    
2764
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2765
                  data=config.Dumps())
2766
  shutil.rmtree(finaldestdir, ignore_errors=True)
2767
  shutil.move(destdir, finaldestdir)
2768

    
2769

    
2770
def ExportInfo(dest):
2771
  """Get export configuration information.
2772

2773
  @type dest: str
2774
  @param dest: directory containing the export
2775

2776
  @rtype: L{objects.SerializableConfigParser}
2777
  @return: a serializable config file containing the
2778
      export info
2779

2780
  """
2781
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2782

    
2783
  config = objects.SerializableConfigParser()
2784
  config.read(cff)
2785

    
2786
  if (not config.has_section(constants.INISECT_EXP) or
2787
      not config.has_section(constants.INISECT_INS)):
2788
    _Fail("Export info file doesn't have the required fields")
2789

    
2790
  return config.Dumps()
2791

    
2792

    
2793
def ListExports():
2794
  """Return a list of exports currently available on this machine.
2795

2796
  @rtype: list
2797
  @return: list of the exports
2798

2799
  """
2800
  if os.path.isdir(pathutils.EXPORT_DIR):
2801
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
2802
  else:
2803
    _Fail("No exports directory")
2804

    
2805

    
2806
def RemoveExport(export):
2807
  """Remove an existing export from the node.
2808

2809
  @type export: str
2810
  @param export: the name of the export to remove
2811
  @rtype: None
2812

2813
  """
2814
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
2815

    
2816
  try:
2817
    shutil.rmtree(target)
2818
  except EnvironmentError, err:
2819
    _Fail("Error while removing the export: %s", err, exc=True)
2820

    
2821

    
2822
def BlockdevRename(devlist):
2823
  """Rename a list of block devices.
2824

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

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

    
2862

    
2863
def _TransformFileStorageDir(fs_dir):
2864
  """Checks whether given file_storage_dir is valid.
2865

2866
  Checks wheter the given fs_dir is within the cluster-wide default
2867
  file_storage_dir or the shared_file_storage_dir, which are stored in
2868
  SimpleStore. Only paths under those directories are allowed.
2869

2870
  @type fs_dir: str
2871
  @param fs_dir: the path to check
2872

2873
  @return: the normalized path if valid, None otherwise
2874

2875
  """
2876
  if not (constants.ENABLE_FILE_STORAGE or
2877
          constants.ENABLE_SHARED_FILE_STORAGE):
2878
    _Fail("File storage disabled at configure time")
2879

    
2880
  bdev.CheckFileStoragePath(fs_dir)
2881

    
2882
  return os.path.normpath(fs_dir)
2883

    
2884

    
2885
def CreateFileStorageDir(file_storage_dir):
2886
  """Create file storage directory.
2887

2888
  @type file_storage_dir: str
2889
  @param file_storage_dir: directory to create
2890

2891
  @rtype: tuple
2892
  @return: tuple with first element a boolean indicating wheter dir
2893
      creation was successful or not
2894

2895
  """
2896
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2897
  if os.path.exists(file_storage_dir):
2898
    if not os.path.isdir(file_storage_dir):
2899
      _Fail("Specified storage dir '%s' is not a directory",
2900
            file_storage_dir)
2901
  else:
2902
    try:
2903
      os.makedirs(file_storage_dir, 0750)
2904
    except OSError, err:
2905
      _Fail("Cannot create file storage directory '%s': %s",
2906
            file_storage_dir, err, exc=True)
2907

    
2908

    
2909
def RemoveFileStorageDir(file_storage_dir):
2910
  """Remove file storage directory.
2911

2912
  Remove it only if it's empty. If not log an error and return.
2913

2914
  @type file_storage_dir: str
2915
  @param file_storage_dir: the directory we should cleanup
2916
  @rtype: tuple (success,)
2917
  @return: tuple of one element, C{success}, denoting
2918
      whether the operation was successful
2919

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

    
2933

    
2934
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2935
  """Rename the file storage directory.
2936

2937
  @type old_file_storage_dir: str
2938
  @param old_file_storage_dir: the current path
2939
  @type new_file_storage_dir: str
2940
  @param new_file_storage_dir: the name we should rename to
2941
  @rtype: tuple (success,)
2942
  @return: tuple of one element, C{success}, denoting
2943
      whether the operation was successful
2944

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

    
2963

    
2964
def _EnsureJobQueueFile(file_name):
2965
  """Checks whether the given filename is in the queue directory.
2966

2967
  @type file_name: str
2968
  @param file_name: the file name we should check
2969
  @rtype: None
2970
  @raises RPCFail: if the file is not valid
2971

2972
  """
2973
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
2974
    _Fail("Passed job queue file '%s' does not belong to"
2975
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
2976

    
2977

    
2978
def JobQueueUpdate(file_name, content):
2979
  """Updates a file in the queue directory.
2980

2981
  This is just a wrapper over L{utils.io.WriteFile}, with proper
2982
  checking.
2983

2984
  @type file_name: str
2985
  @param file_name: the job file name
2986
  @type content: str
2987
  @param content: the new job contents
2988
  @rtype: boolean
2989
  @return: the success of the operation
2990

2991
  """
2992
  file_name = vcluster.LocalizeVirtualPath(file_name)
2993

    
2994
  _EnsureJobQueueFile(file_name)
2995
  getents = runtime.GetEnts()
2996

    
2997
  # Write and replace the file atomically
2998
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
2999
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3000

    
3001

    
3002
def JobQueueRename(old, new):
3003
  """Renames a job queue file.
3004

3005
  This is just a wrapper over os.rename with proper checking.
3006

3007
  @type old: str
3008
  @param old: the old (actual) file name
3009
  @type new: str
3010
  @param new: the desired file name
3011
  @rtype: tuple
3012
  @return: the success of the operation and payload
3013

3014
  """
3015
  old = vcluster.LocalizeVirtualPath(old)
3016
  new = vcluster.LocalizeVirtualPath(new)
3017

    
3018
  _EnsureJobQueueFile(old)
3019
  _EnsureJobQueueFile(new)
3020

    
3021
  getents = runtime.GetEnts()
3022

    
3023
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3024
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3025

    
3026

    
3027
def BlockdevClose(instance_name, disks):
3028
  """Closes the given block devices.
3029

3030
  This means they will be switched to secondary mode (in case of
3031
  DRBD).
3032

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

3043
  """
3044
  bdevs = []
3045
  for cf in disks:
3046
    rd = _RecursiveFindBD(cf)
3047
    if rd is None:
3048
      _Fail("Can't find device %s", cf)
3049
    bdevs.append(rd)
3050

    
3051
  msg = []
3052
  for rd in bdevs:
3053
    try:
3054
      rd.Close()
3055
    except errors.BlockDeviceError, err:
3056
      msg.append(str(err))
3057
  if msg:
3058
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3059
  else:
3060
    if instance_name:
3061
      _RemoveBlockDevLinks(instance_name, disks)
3062

    
3063

    
3064
def ValidateHVParams(hvname, hvparams):
3065
  """Validates the given hypervisor parameters.
3066

3067
  @type hvname: string
3068
  @param hvname: the hypervisor name
3069
  @type hvparams: dict
3070
  @param hvparams: the hypervisor parameters to be validated
3071
  @rtype: None
3072

3073
  """
3074
  try:
3075
    hv_type = hypervisor.GetHypervisor(hvname)
3076
    hv_type.ValidateParameters(hvparams)
3077
  except errors.HypervisorError, err:
3078
    _Fail(str(err), log=False)
3079

    
3080

    
3081
def _CheckOSPList(os_obj, parameters):
3082
  """Check whether a list of parameters is supported by the OS.
3083

3084
  @type os_obj: L{objects.OS}
3085
  @param os_obj: OS object to check
3086
  @type parameters: list
3087
  @param parameters: the list of parameters to check
3088

3089
  """
3090
  supported = [v[0] for v in os_obj.supported_parameters]
3091
  delta = frozenset(parameters).difference(supported)
3092
  if delta:
3093
    _Fail("The following parameters are not supported"
3094
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3095

    
3096

    
3097
def ValidateOS(required, osname, checks, osparams):
3098
  """Validate the given OS' parameters.
3099

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

3113
  """
3114
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3115
    _Fail("Unknown checks required for OS %s: %s", osname,
3116
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3117

    
3118
  name_only = objects.OS.GetName(osname)
3119
  status, tbv = _TryOSFromDisk(name_only, None)
3120

    
3121
  if not status:
3122
    if required:
3123
      _Fail(tbv)
3124
    else:
3125
      return False
3126

    
3127
  if max(tbv.api_versions) < constants.OS_API_V20:
3128
    return True
3129

    
3130
  if constants.OS_VALIDATE_PARAMETERS in checks:
3131
    _CheckOSPList(tbv, osparams.keys())
3132

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

    
3142
  return True
3143

    
3144

    
3145
def DemoteFromMC():
3146
  """Demotes the current node from master candidate role.
3147

3148
  """
3149
  # try to ensure we're not the master by mistake
3150
  master, myself = ssconf.GetMasterAndMyself()
3151
  if master == myself:
3152
    _Fail("ssconf status shows I'm the master node, will not demote")
3153

    
3154
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3155
  if not result.failed:
3156
    _Fail("The master daemon is running, will not demote")
3157

    
3158
  try:
3159
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3160
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3161
  except EnvironmentError, err:
3162
    if err.errno != errno.ENOENT:
3163
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3164

    
3165
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3166

    
3167

    
3168
def _GetX509Filenames(cryptodir, name):
3169
  """Returns the full paths for the private key and certificate.
3170

3171
  """
3172
  return (utils.PathJoin(cryptodir, name),
3173
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3174
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3175

    
3176

    
3177
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3178
  """Creates a new X509 certificate for SSL/TLS.
3179

3180
  @type validity: int
3181
  @param validity: Validity in seconds
3182
  @rtype: tuple; (string, string)
3183
  @return: Certificate name and public part
3184

3185
  """
3186
  (key_pem, cert_pem) = \
3187
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3188
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3189

    
3190
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3191
                              prefix="x509-%s-" % utils.TimestampForFilename())
3192
  try:
3193
    name = os.path.basename(cert_dir)
3194
    assert len(name) > 5
3195

    
3196
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3197

    
3198
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3199
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3200

    
3201
    # Never return private key as it shouldn't leave the node
3202
    return (name, cert_pem)
3203
  except Exception:
3204
    shutil.rmtree(cert_dir, ignore_errors=True)
3205
    raise
3206

    
3207

    
3208
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3209
  """Removes a X509 certificate.
3210

3211
  @type name: string
3212
  @param name: Certificate name
3213

3214
  """
3215
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3216

    
3217
  utils.RemoveFile(key_file)
3218
  utils.RemoveFile(cert_file)
3219

    
3220
  try:
3221
    os.rmdir(cert_dir)
3222
  except EnvironmentError, err:
3223
    _Fail("Cannot remove certificate directory '%s': %s",
3224
          cert_dir, err)
3225

    
3226

    
3227
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3228
  """Returns the command for the requested input/output.
3229

3230
  @type instance: L{objects.Instance}
3231
  @param instance: The instance object
3232
  @param mode: Import/export mode
3233
  @param ieio: Input/output type
3234
  @param ieargs: Input/output arguments
3235

3236
  """
3237
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3238

    
3239
  env = None
3240
  prefix = None
3241
  suffix = None
3242
  exp_size = None
3243

    
3244
  if ieio == constants.IEIO_FILE:
3245
    (filename, ) = ieargs
3246

    
3247
    if not utils.IsNormAbsPath(filename):
3248
      _Fail("Path '%s' is not normalized or absolute", filename)
3249

    
3250
    real_filename = os.path.realpath(filename)
3251
    directory = os.path.dirname(real_filename)
3252

    
3253
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3254
      _Fail("File '%s' is not under exports directory '%s': %s",
3255
            filename, pathutils.EXPORT_DIR, real_filename)
3256

    
3257
    # Create directory
3258
    utils.Makedirs(directory, mode=0750)
3259

    
3260
    quoted_filename = utils.ShellQuote(filename)
3261

    
3262
    if mode == constants.IEM_IMPORT:
3263
      suffix = "> %s" % quoted_filename
3264
    elif mode == constants.IEM_EXPORT:
3265
      suffix = "< %s" % quoted_filename
3266

    
3267
      # Retrieve file size
3268
      try:
3269
        st = os.stat(filename)
3270
      except EnvironmentError, err:
3271
        logging.error("Can't stat(2) %s: %s", filename, err)
3272
      else:
3273
        exp_size = utils.BytesToMebibyte(st.st_size)
3274

    
3275
  elif ieio == constants.IEIO_RAW_DISK:
3276
    (disk, ) = ieargs
3277

    
3278
    real_disk = _OpenRealBD(disk)
3279

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

    
3292
    elif mode == constants.IEM_EXPORT:
3293
      # the block size on the read dd is 1MiB to match our units
3294
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3295
                                   real_disk.dev_path,
3296
                                   str(1024 * 1024), # 1 MB
3297
                                   str(disk.size))
3298
      exp_size = disk.size
3299

    
3300
  elif ieio == constants.IEIO_SCRIPT:
3301
    (disk, disk_index, ) = ieargs
3302

    
3303
    assert isinstance(disk_index, (int, long))
3304

    
3305
    real_disk = _OpenRealBD(disk)
3306

    
3307
    inst_os = OSFromDisk(instance.os)
3308
    env = OSEnvironment(instance, inst_os)
3309

    
3310
    if mode == constants.IEM_IMPORT:
3311
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3312
      env["IMPORT_INDEX"] = str(disk_index)
3313
      script = inst_os.import_script
3314

    
3315
    elif mode == constants.IEM_EXPORT:
3316
      env["EXPORT_DEVICE"] = real_disk.dev_path
3317
      env["EXPORT_INDEX"] = str(disk_index)
3318
      script = inst_os.export_script
3319

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

    
3323
    if mode == constants.IEM_IMPORT:
3324
      suffix = "| %s" % script_cmd
3325

    
3326
    elif mode == constants.IEM_EXPORT:
3327
      prefix = "%s |" % script_cmd
3328

    
3329
    # Let script predict size
3330
    exp_size = constants.IE_CUSTOM_SIZE
3331

    
3332
  else:
3333
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3334

    
3335
  return (env, prefix, suffix, exp_size)
3336

    
3337

    
3338
def _CreateImportExportStatusDir(prefix):
3339
  """Creates status directory for import/export.
3340

3341
  """
3342
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3343
                          prefix=("%s-%s-" %
3344
                                  (prefix, utils.TimestampForFilename())))
3345

    
3346

    
3347
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3348
                            ieio, ieioargs):
3349
  """Starts an import or export daemon.
3350

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

3366
  """
3367
  if mode == constants.IEM_IMPORT:
3368
    prefix = "import"
3369

    
3370
    if not (host is None and port is None):
3371
      _Fail("Can not specify host or port on import")
3372

    
3373
  elif mode == constants.IEM_EXPORT:
3374
    prefix = "export"
3375

    
3376
    if host is None or port is None:
3377
      _Fail("Host and port must be specified for an export")
3378

    
3379
  else:
3380
    _Fail("Invalid mode %r", mode)
3381

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

    
3385
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3386
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3387

    
3388
  if opts.key_name is None:
3389
    # Use server.pem
3390
    key_path = pathutils.NODED_CERT_FILE
3391
    cert_path = pathutils.NODED_CERT_FILE
3392
    assert opts.ca_pem is None
3393
  else:
3394
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3395
                                                 opts.key_name)
3396
    assert opts.ca_pem is not None
3397

    
3398
  for i in [key_path, cert_path]:
3399
    if not os.path.exists(i):
3400
      _Fail("File '%s' does not exist" % i)
3401

    
3402
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3403
  try:
3404
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3405
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3406
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3407

    
3408
    if opts.ca_pem is None:
3409
      # Use server.pem
3410
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3411
    else:
3412
      ca = opts.ca_pem
3413

    
3414
    # Write CA file
3415
    utils.WriteFile(ca_file, data=ca, mode=0400)
3416

    
3417
    cmd = [
3418
      pathutils.IMPORT_EXPORT_DAEMON,
3419
      status_file, mode,
3420
      "--key=%s" % key_path,
3421
      "--cert=%s" % cert_path,
3422
      "--ca=%s" % ca_file,
3423
      ]
3424

    
3425
    if host:
3426
      cmd.append("--host=%s" % host)
3427

    
3428
    if port:
3429
      cmd.append("--port=%s" % port)
3430

    
3431
    if opts.ipv6:
3432
      cmd.append("--ipv6")
3433
    else:
3434
      cmd.append("--ipv4")
3435

    
3436
    if opts.compress:
3437
      cmd.append("--compress=%s" % opts.compress)
3438

    
3439
    if opts.magic:
3440
      cmd.append("--magic=%s" % opts.magic)
3441

    
3442
    if exp_size is not None:
3443
      cmd.append("--expected-size=%s" % exp_size)
3444

    
3445
    if cmd_prefix:
3446
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3447

    
3448
    if cmd_suffix:
3449
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3450

    
3451
    if mode == constants.IEM_EXPORT:
3452
      # Retry connection a few times when connecting to remote peer
3453
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3454
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3455
    elif opts.connect_timeout is not None:
3456
      assert mode == constants.IEM_IMPORT
3457
      # Overall timeout for establishing connection while listening
3458
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3459

    
3460
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3461

    
3462
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3463
    # support for receiving a file descriptor for output
3464
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3465
                      output=logfile)
3466

    
3467
    # The import/export name is simply the status directory name
3468
    return os.path.basename(status_dir)
3469

    
3470
  except Exception:
3471
    shutil.rmtree(status_dir, ignore_errors=True)
3472
    raise
3473

    
3474

    
3475
def GetImportExportStatus(names):
3476
  """Returns import/export daemon status.
3477

3478
  @type names: sequence
3479
  @param names: List of names
3480
  @rtype: List of dicts
3481
  @return: Returns a list of the state of each named import/export or None if a
3482
           status couldn't be read
3483

3484
  """
3485
  result = []
3486

    
3487
  for name in names:
3488
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3489
                                 _IES_STATUS_FILE)
3490

    
3491
    try:
3492
      data = utils.ReadFile(status_file)
3493
    except EnvironmentError, err:
3494
      if err.errno != errno.ENOENT:
3495
        raise
3496
      data = None
3497

    
3498
    if not data:
3499
      result.append(None)
3500
      continue
3501

    
3502
    result.append(serializer.LoadJson(data))
3503

    
3504
  return result
3505

    
3506

    
3507
def AbortImportExport(name):
3508
  """Sends SIGTERM to a running import/export daemon.
3509

3510
  """
3511
  logging.info("Abort import/export %s", name)
3512

    
3513
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3514
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3515

    
3516
  if pid:
3517
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3518
                 name, pid)
3519
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3520

    
3521

    
3522
def CleanupImportExport(name):
3523
  """Cleanup after an import or export.
3524

3525
  If the import/export daemon is still running it's killed. Afterwards the
3526
  whole status directory is removed.
3527

3528
  """
3529
  logging.info("Finalizing import/export %s", name)
3530

    
3531
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3532

    
3533
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3534

    
3535
  if pid:
3536
    logging.info("Import/export %s is still running with PID %s",
3537
                 name, pid)
3538
    utils.KillProcess(pid, waitpid=False)
3539

    
3540
  shutil.rmtree(status_dir, ignore_errors=True)
3541

    
3542

    
3543
def _FindDisks(nodes_ip, disks):
3544
  """Sets the physical ID on disks and returns the block devices.
3545

3546
  """
3547
  # set the correct physical ID
3548
  my_name = netutils.Hostname.GetSysName()
3549
  for cf in disks:
3550
    cf.SetPhysicalID(my_name, nodes_ip)
3551

    
3552
  bdevs = []
3553

    
3554
  for cf in disks:
3555
    rd = _RecursiveFindBD(cf)
3556
    if rd is None:
3557
      _Fail("Can't find device %s", cf)
3558
    bdevs.append(rd)
3559
  return bdevs
3560

    
3561

    
3562
def DrbdDisconnectNet(nodes_ip, disks):
3563
  """Disconnects the network on a list of drbd devices.
3564

3565
  """
3566
  bdevs = _FindDisks(nodes_ip, disks)
3567

    
3568
  # disconnect disks
3569
  for rd in bdevs:
3570
    try:
3571
      rd.DisconnectNet()
3572
    except errors.BlockDeviceError, err:
3573
      _Fail("Can't change network configuration to standalone mode: %s",
3574
            err, exc=True)
3575

    
3576

    
3577
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3578
  """Attaches the network on a list of drbd devices.
3579

3580
  """
3581
  bdevs = _FindDisks(nodes_ip, disks)
3582

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

    
3597
  # wait until the disks are connected; we need to retry the re-attach
3598
  # if the device becomes standalone, as this might happen if the one
3599
  # node disconnects and reconnects in a different mode before the
3600
  # other node reconnects; in this case, one or both of the nodes will
3601
  # decide it has wrong configuration and switch to standalone
3602

    
3603
  def _Attach():
3604
    all_connected = True
3605

    
3606
    for rd in bdevs:
3607
      stats = rd.GetProcStatus()
3608

    
3609
      all_connected = (all_connected and
3610
                       (stats.is_connected or stats.is_in_resync))
3611

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

    
3621
    if not all_connected:
3622
      raise utils.RetryAgain()
3623

    
3624
  try:
3625
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3626
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3627
  except utils.RetryTimeout:
3628
    _Fail("Timeout in disk reconnecting")
3629

    
3630
  if multimaster:
3631
    # change to primary mode
3632
    for rd in bdevs:
3633
      try:
3634
        rd.Open()
3635
      except errors.BlockDeviceError, err:
3636
        _Fail("Can't change to primary mode: %s", err)
3637

    
3638

    
3639
def DrbdWaitSync(nodes_ip, disks):
3640
  """Wait until DRBDs have synchronized.
3641

3642
  """
3643
  def _helper(rd):
3644
    stats = rd.GetProcStatus()
3645
    if not (stats.is_connected or stats.is_in_resync):
3646
      raise utils.RetryAgain()
3647
    return stats
3648

    
3649
  bdevs = _FindDisks(nodes_ip, disks)
3650

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

    
3666
  return (alldone, min_resync)
3667

    
3668

    
3669
def GetDrbdUsermodeHelper():
3670
  """Returns DRBD usermode helper currently configured.
3671

3672
  """
3673
  try:
3674
    return drbd.BaseDRBD.GetUsermodeHelper()
3675
  except errors.BlockDeviceError, err:
3676
    _Fail(str(err))
3677

    
3678

    
3679
def PowercycleNode(hypervisor_type):
3680
  """Hard-powercycle the node.
3681

3682
  Because we need to return first, and schedule the powercycle in the
3683
  background, we won't be able to report failures nicely.
3684

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

    
3702

    
3703
def _VerifyRestrictedCmdName(cmd):
3704
  """Verifies a restricted command name.
3705

3706
  @type cmd: string
3707
  @param cmd: Command name
3708
  @rtype: tuple; (boolean, string or None)
3709
  @return: The tuple's first element is the status; if C{False}, the second
3710
    element is an error message string, otherwise it's C{None}
3711

3712
  """
3713
  if not cmd.strip():
3714
    return (False, "Missing command name")
3715

    
3716
  if os.path.basename(cmd) != cmd:
3717
    return (False, "Invalid command name")
3718

    
3719
  if not constants.EXT_PLUGIN_MASK.match(cmd):
3720
    return (False, "Command name contains forbidden characters")
3721

    
3722
  return (True, None)
3723

    
3724

    
3725
def _CommonRestrictedCmdCheck(path, owner):
3726
  """Common checks for restricted command file system directories and files.
3727

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

3735
  """
3736
  if owner is None:
3737
    # Default to root as owner
3738
    owner = (0, 0)
3739

    
3740
  try:
3741
    st = os.stat(path)
3742
  except EnvironmentError, err:
3743
    return (False, "Can't stat(2) '%s': %s" % (path, err))
3744

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

    
3748
  if (st.st_uid, st.st_gid) != owner:
3749
    (owner_uid, owner_gid) = owner
3750
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
3751

    
3752
  return (True, st)
3753

    
3754

    
3755
def _VerifyRestrictedCmdDirectory(path, _owner=None):
3756
  """Verifies restricted command directory.
3757

3758
  @type path: string
3759
  @param path: Path to check
3760
  @rtype: tuple; (boolean, string or None)
3761
  @return: The tuple's first element is the status; if C{False}, the second
3762
    element is an error message string, otherwise it's C{None}
3763

3764
  """
3765
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
3766

    
3767
  if not status:
3768
    return (False, value)
3769

    
3770
  if not stat.S_ISDIR(value.st_mode):
3771
    return (False, "Path '%s' is not a directory" % path)
3772

    
3773
  return (True, None)
3774

    
3775

    
3776
def _VerifyRestrictedCmd(path, cmd, _owner=None):
3777
  """Verifies a whole restricted command and returns its executable filename.
3778

3779
  @type path: string
3780
  @param path: Directory containing restricted commands
3781
  @type cmd: string
3782
  @param cmd: Command name
3783
  @rtype: tuple; (boolean, string)
3784
  @return: The tuple's first element is the status; if C{False}, the second
3785
    element is an error message string, otherwise the second element is the
3786
    absolute path to the executable
3787

3788
  """
3789
  executable = utils.PathJoin(path, cmd)
3790

    
3791
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
3792

    
3793
  if not status:
3794
    return (False, msg)
3795

    
3796
  if not utils.IsExecutable(executable):
3797
    return (False, "access(2) thinks '%s' can't be executed" % executable)
3798

    
3799
  return (True, executable)
3800

    
3801

    
3802
def _PrepareRestrictedCmd(path, cmd,
3803
                          _verify_dir=_VerifyRestrictedCmdDirectory,
3804
                          _verify_name=_VerifyRestrictedCmdName,
3805
                          _verify_cmd=_VerifyRestrictedCmd):
3806
  """Performs a number of tests on a restricted command.
3807

3808
  @type path: string
3809
  @param path: Directory containing restricted commands
3810
  @type cmd: string
3811
  @param cmd: Command name
3812
  @return: Same as L{_VerifyRestrictedCmd}
3813

3814
  """
3815
  # Verify the directory first
3816
  (status, msg) = _verify_dir(path)
3817
  if status:
3818
    # Check command if everything was alright
3819
    (status, msg) = _verify_name(cmd)
3820

    
3821
  if not status:
3822
    return (False, msg)
3823

    
3824
  # Check actual executable
3825
  return _verify_cmd(path, cmd)
3826

    
3827

    
3828
def RunRestrictedCmd(cmd,
3829
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
3830
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
3831
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
3832
                     _sleep_fn=time.sleep,
3833
                     _prepare_fn=_PrepareRestrictedCmd,
3834
                     _runcmd_fn=utils.RunCmd,
3835
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
3836
  """Executes a restricted command after performing strict tests.
3837

3838
  @type cmd: string
3839
  @param cmd: Command name
3840
  @rtype: string
3841
  @return: Command output
3842
  @raise RPCFail: In case of an error
3843

3844
  """
3845
  logging.info("Preparing to run restricted command '%s'", cmd)
3846

    
3847
  if not _enabled:
3848
    _Fail("Restricted commands disabled at configure time")
3849

    
3850
  lock = None
3851
  try:
3852
    cmdresult = None
3853
    try:
3854
      lock = utils.FileLock.Open(_lock_file)
3855
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
3856

    
3857
      (status, value) = _prepare_fn(_path, cmd)
3858

    
3859
      if status:
3860
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
3861
                               postfork_fn=lambda _: lock.Unlock())
3862
      else:
3863
        logging.error(value)
3864
    except Exception: # pylint: disable=W0703
3865
      # Keep original error in log
3866
      logging.exception("Caught exception")
3867

    
3868
    if cmdresult is None:
3869
      logging.info("Sleeping for %0.1f seconds before returning",
3870
                   _RCMD_INVALID_DELAY)
3871
      _sleep_fn(_RCMD_INVALID_DELAY)
3872

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

    
3886

    
3887
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
3888
  """Creates or removes the watcher pause file.
3889

3890
  @type until: None or number
3891
  @param until: Unix timestamp saying until when the watcher shouldn't run
3892

3893
  """
3894
  if until is None:
3895
    logging.info("Received request to no longer pause watcher")
3896
    utils.RemoveFile(_filename)
3897
  else:
3898
    logging.info("Received request to pause watcher until %s", until)
3899

    
3900
    if not ht.TNumber(until):
3901
      _Fail("Duration must be numeric")
3902

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

    
3905

    
3906
class HooksRunner(object):
3907
  """Hook runner.
3908

3909
  This class is instantiated on the node side (ganeti-noded) and not
3910
  on the master side.
3911

3912
  """
3913
  def __init__(self, hooks_base_dir=None):
3914
    """Constructor for hooks runner.
3915

3916
    @type hooks_base_dir: str or None
3917
    @param hooks_base_dir: if not None, this overrides the
3918
        L{pathutils.HOOKS_BASE_DIR} (useful for unittests)
3919

3920
    """
3921
    if hooks_base_dir is None:
3922
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
3923
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3924
    # constant
3925
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
3926

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

3930
    """
3931
    assert len(node_list) == 1
3932
    node = node_list[0]
3933
    _, myself = ssconf.GetMasterAndMyself()
3934
    assert node == myself
3935

    
3936
    results = self.RunHooks(hpath, phase, env)
3937

    
3938
    # Return values in the form expected by HooksMaster
3939
    return {node: (None, False, results)}
3940

    
3941
  def RunHooks(self, hpath, phase, env):
3942
    """Run the scripts in the hooks directory.
3943

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

3959
    @raise errors.ProgrammerError: for invalid input
3960
        parameters
3961

3962
    """
3963
    if phase == constants.HOOKS_PHASE_PRE:
3964
      suffix = "pre"
3965
    elif phase == constants.HOOKS_PHASE_POST:
3966
      suffix = "post"
3967
    else:
3968
      _Fail("Unknown hooks phase '%s'", phase)
3969

    
3970
    subdir = "%s-%s.d" % (hpath, suffix)
3971
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3972

    
3973
    results = []
3974

    
3975
    if not os.path.isdir(dir_name):
3976
      # for non-existing/non-dirs, we simply exit instead of logging a
3977
      # warning at every operation
3978
      return results
3979

    
3980
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3981

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

    
3997
    return results
3998

    
3999

    
4000
class IAllocatorRunner(object):
4001
  """IAllocator runner.
4002

4003
  This class is instantiated on the node side (ganeti-noded) and not on
4004
  the master side.
4005

4006
  """
4007
  @staticmethod
4008
  def Run(name, idata):
4009
    """Run an iallocator script.
4010

4011
    @type name: str
4012
    @param name: the iallocator script name
4013
    @type idata: str
4014
    @param idata: the allocator input data
4015

4016
    @rtype: tuple
4017
    @return: two element tuple of:
4018
       - status
4019
       - either error message or stdout of allocator (for success)
4020

4021
    """
4022
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
4023
                                  os.path.isfile)
4024
    if alloc_script is None:
4025
      _Fail("iallocator module '%s' not found in the search path", name)
4026

    
4027
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
4028
    try:
4029
      os.write(fd, idata)
4030
      os.close(fd)
4031
      result = utils.RunCmd([alloc_script, fin_name])
4032
      if result.failed:
4033
        _Fail("iallocator module '%s' failed: %s, output '%s'",
4034
              name, result.fail_reason, result.output)
4035
    finally:
4036
      os.unlink(fin_name)
4037

    
4038
    return result.stdout
4039

    
4040

    
4041
class DevCacheManager(object):
4042
  """Simple class for managing a cache of block device information.
4043

4044
  """
4045
  _DEV_PREFIX = "/dev/"
4046
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4047

    
4048
  @classmethod
4049
  def _ConvertPath(cls, dev_path):
4050
    """Converts a /dev/name path to the cache file name.
4051

4052
    This replaces slashes with underscores and strips the /dev
4053
    prefix. It then returns the full path to the cache file.
4054

4055
    @type dev_path: str
4056
    @param dev_path: the C{/dev/} path name
4057
    @rtype: str
4058
    @return: the converted path name
4059

4060
    """
4061
    if dev_path.startswith(cls._DEV_PREFIX):
4062
      dev_path = dev_path[len(cls._DEV_PREFIX):]
4063
    dev_path = dev_path.replace("/", "_")
4064
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4065
    return fpath
4066

    
4067
  @classmethod
4068
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4069
    """Updates the cache information for a given device.
4070

4071
    @type dev_path: str
4072
    @param dev_path: the pathname of the device
4073
    @type owner: str
4074
    @param owner: the owner (instance name) of the device
4075
    @type on_primary: bool
4076
    @param on_primary: whether this is the primary
4077
        node nor not
4078
    @type iv_name: str
4079
    @param iv_name: the instance-visible name of the
4080
        device, as in objects.Disk.iv_name
4081

4082
    @rtype: None
4083

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

    
4101
  @classmethod
4102
  def RemoveCache(cls, dev_path):
4103
    """Remove data for a dev_path.
4104

4105
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
4106
    path name and logging.
4107

4108
    @type dev_path: str
4109
    @param dev_path: the pathname of the device
4110

4111
    @rtype: None
4112

4113
    """
4114
    if dev_path is None:
4115
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
4116
      return
4117
    fpath = cls._ConvertPath(dev_path)
4118
    try:
4119
      utils.RemoveFile(fpath)
4120
    except EnvironmentError, err:
4121
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)