Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 11c97d7c

History | View | Annotate | Download (128.4 kB)

1
#
2
#
3

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

    
21

    
22
"""Functions used by the node daemon
23

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

29
"""
30

    
31
# pylint: disable=E1103
32

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

    
37

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

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

    
69

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

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

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

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

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

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

    
104

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

108
  Its argument is the error message.
109

110
  """
111

    
112

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

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

121
  """
122
  return utils.PathJoin(pathutils.INSTANCE_REASON_DIR, instance_name)
123

    
124

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

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

131
  @type instance_name: string
132
  @param instance_name: The name of the instance
133
  @rtype: None
134

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

    
140

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

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

149
  @type msg: string
150
  @param msg: the text of the exception
151
  @raise RPCFail
152

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

    
163

    
164
def _GetConfig():
165
  """Simple wrapper to return a SimpleStore.
166

167
  @rtype: L{ssconf.SimpleStore}
168
  @return: a SimpleStore instance
169

170
  """
171
  return ssconf.SimpleStore()
172

    
173

    
174
def _GetSshRunner(cluster_name):
175
  """Simple wrapper to return an SshRunner.
176

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

183
  """
184
  return ssh.SshRunner(cluster_name)
185

    
186

    
187
def _Decompress(data):
188
  """Unpacks data compressed by the RPC client.
189

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

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

    
206

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

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

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

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

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

    
236

    
237
def _BuildUploadFileList():
238
  """Build the list of allowed upload files.
239

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

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

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

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

    
263
  return frozenset(allowed_files)
264

    
265

    
266
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
267

    
268

    
269
def JobQueuePurge():
270
  """Removes job queue files and archived jobs.
271

272
  @rtype: tuple
273
  @return: True, None
274

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

    
279

    
280
def GetMasterInfo():
281
  """Returns master information.
282

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

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

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

    
304

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

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

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

    
324
      env_fn = compat.partial(env_builder_fn, *args, **kwargs)
325

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

    
336
      return result
337
    return wrapper
338
  return decorator
339

    
340

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

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

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

    
361
  return env
362

    
363

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

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

378
  """
379
  env = _BuildMasterIpEnv(master_params)
380

    
381
  if use_external_mip_script:
382
    setup_script = pathutils.EXTERNAL_MASTER_SETUP_SCRIPT
383
  else:
384
    setup_script = pathutils.DEFAULT_MASTER_SETUP_SCRIPT
385

    
386
  result = utils.RunCmd([setup_script, action], env=env, reset_env=True)
387

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

    
392

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

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

405
  """
406
  _RunMasterSetupScript(master_params, _MASTER_START,
407
                        use_external_mip_script)
408

    
409

    
410
def StartMasterDaemons(no_voting):
411
  """Activate local node as master node.
412

413
  The function will start the master daemons (ganeti-masterd and ganeti-rapi).
414

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

420
  """
421

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

    
427
  env = {
428
    "EXTRA_MASTERD_ARGS": masterd_args,
429
    }
430

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

    
437

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

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

450
  """
451
  _RunMasterSetupScript(master_params, _MASTER_STOP,
452
                        use_external_mip_script)
453

    
454

    
455
def StopMasterDaemons():
456
  """Stop the master daemons on this node.
457

458
  Stop the master daemons (ganeti-masterd and ganeti-rapi) on this node.
459

460
  @rtype: None
461

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

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

    
472

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

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

481
  """
482
  if old_netmask == netmask:
483
    return
484

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

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

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

    
503

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

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

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

    
525

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

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

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

536
  @param modify_ssh_setup: boolean
537

538
  """
539
  _CleanDirectory(pathutils.DATA_DIR)
540
  _CleanDirectory(pathutils.CRYPTO_KEYS_DIR)
541
  JobQueuePurge()
542

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

    
547
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
548

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

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

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

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

    
571

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

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

    
585
  return {
586
    "name": name,
587
    "vg_free": vg_free,
588
    "vg_size": vg_size,
589
    }
590

    
591

    
592
def _GetHvInfo(name):
593
  """Retrieves node information from a hypervisor.
594

595
  The information returned depends on the hypervisor. Common items:
596

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

604
  """
605
  return hypervisor.GetHypervisor(name).GetNodeInfo()
606

    
607

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

611
  @rtype: None or dict
612

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

    
619

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

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

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

    
638
  return (bootid, vg_info, hv_info)
639

    
640

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

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

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

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

    
657

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

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

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

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

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

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

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

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

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

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

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

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

    
726
    # Use a random order
727
    random.shuffle(nodes)
728

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

    
736
    result[constants.NV_NODELIST] = val
737

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
876
  return result
877

    
878

    
879
def GetBlockDevSizes(devices):
880
  """Return the size of the given block devices
881

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

889
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
890

891
  """
892
  DEV_PREFIX = "/dev/"
893
  blockdevs = {}
894

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

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

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

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

    
916

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

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

928
        {'xenvg/test1': ('20.06', True, True)}
929

930
      in case of errors, a string is returned with the error
931
      details.
932

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

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

    
960
  return lvs
961

    
962

    
963
def ListVolumeGroups():
964
  """List the volume groups and their size.
965

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

970
  """
971
  return utils.ListVolumeGroups()
972

    
973

    
974
def NodeVolumes():
975
  """List all volumes on this node.
976

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

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

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

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

    
1000
  def parse_dev(dev):
1001
    return dev.split("(")[0]
1002

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

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

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

    
1019

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

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

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

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

    
1035

    
1036
def GetInstanceList(hypervisor_list):
1037
  """Provides a list of instances.
1038

1039
  @type hypervisor_list: list
1040
  @param hypervisor_list: the list of hypervisors to query information
1041

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

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

    
1057
  return results
1058

    
1059

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

1063
  @type instance: string
1064
  @param instance: the instance name
1065
  @type hname: string
1066
  @param hname: the hypervisor type of the instance
1067

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

1075
  """
1076
  output = {}
1077

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

    
1085
  return output
1086

    
1087

    
1088
def GetInstanceMigratable(instance):
1089
  """Gives whether an instance can be migrated.
1090

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

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

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

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

    
1111

    
1112
def GetAllInstancesInfo(hypervisor_list):
1113
  """Gather data about all instances.
1114

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

1119
  @type hypervisor_list: list
1120
  @param hypervisor_list: list of hypervisors to query for instance data
1121

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

1129
  """
1130
  output = {}
1131

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

    
1152
  return output
1153

    
1154

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

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

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

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

    
1182

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

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

1194
  """
1195
  inst_os = OSFromDisk(instance.os)
1196

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

    
1201
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1202

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

    
1214

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

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

1227
  """
1228
  inst_os = OSFromDisk(instance.os)
1229

    
1230
  rename_env = OSEnvironment(instance, inst_os, debug)
1231
  rename_env["OLD_INSTANCE_NAME"] = old_name
1232

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

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

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

    
1247

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

1251
  """
1252
  if _dir is None:
1253
    _dir = pathutils.DISK_LINKS_DIR
1254

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

    
1259

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

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

1266

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

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

    
1285
  return link_name
1286

    
1287

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

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

    
1300

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

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

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

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

    
1326
    block_devices.append((disk, link_name))
1327

    
1328
  return block_devices
1329

    
1330

    
1331
def StartInstance(instance, startup_paused, reason, store_reason=True):
1332
  """Start an instance.
1333

1334
  @type instance: L{objects.Instance}
1335
  @param instance: the instance object
1336
  @type startup_paused: bool
1337
  @param instance: pause instance at startup?
1338
  @type reason: list of reasons
1339
  @param reason: the reason trail for this startup
1340
  @type store_reason: boolean
1341
  @param store_reason: whether to store the shutdown reason trail on file
1342
  @rtype: None
1343

1344
  """
1345
  running_instances = GetInstanceList([instance.hypervisor])
1346

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

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

    
1363

    
1364
def InstanceShutdown(instance, timeout, reason, store_reason=True):
1365
  """Shut an instance down.
1366

1367
  @note: this functions uses polling with a hardcoded timeout.
1368

1369
  @type instance: L{objects.Instance}
1370
  @param instance: the instance object
1371
  @type timeout: integer
1372
  @param timeout: maximum timeout for soft shutdown
1373
  @type reason: list of reasons
1374
  @param reason: the reason trail for this shutdown
1375
  @type store_reason: boolean
1376
  @param store_reason: whether to store the shutdown reason trail on file
1377
  @rtype: None
1378

1379
  """
1380
  hv_name = instance.hypervisor
1381
  hyper = hypervisor.GetHypervisor(hv_name)
1382
  iname = instance.name
1383

    
1384
  if instance.name not in hyper.ListInstances():
1385
    logging.info("Instance %s not running, doing nothing", iname)
1386
    return
1387

    
1388
  class _TryShutdown:
1389
    def __init__(self):
1390
      self.tried_once = False
1391

    
1392
    def __call__(self):
1393
      if iname not in hyper.ListInstances():
1394
        return
1395

    
1396
      try:
1397
        hyper.StopInstance(instance, retry=self.tried_once)
1398
        if store_reason:
1399
          _StoreInstReasonTrail(instance.name, reason)
1400
      except errors.HypervisorError, err:
1401
        if iname not in hyper.ListInstances():
1402
          # if the instance is no longer existing, consider this a
1403
          # success and go to cleanup
1404
          return
1405

    
1406
        _Fail("Failed to stop instance %s: %s", iname, err)
1407

    
1408
      self.tried_once = True
1409

    
1410
      raise utils.RetryAgain()
1411

    
1412
  try:
1413
    utils.Retry(_TryShutdown(), 5, timeout)
1414
  except utils.RetryTimeout:
1415
    # the shutdown did not succeed
1416
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1417

    
1418
    try:
1419
      hyper.StopInstance(instance, force=True)
1420
    except errors.HypervisorError, err:
1421
      if iname in hyper.ListInstances():
1422
        # only raise an error if the instance still exists, otherwise
1423
        # the error could simply be "instance ... unknown"!
1424
        _Fail("Failed to force stop instance %s: %s", iname, err)
1425

    
1426
    time.sleep(1)
1427

    
1428
    if iname in hyper.ListInstances():
1429
      _Fail("Could not shutdown instance %s even by destroy", iname)
1430

    
1431
  try:
1432
    hyper.CleanupInstance(instance.name)
1433
  except errors.HypervisorError, err:
1434
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1435

    
1436
  _RemoveBlockDevLinks(iname, instance.disks)
1437

    
1438

    
1439
def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1440
  """Reboot an instance.
1441

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

1461
  """
1462
  running_instances = GetInstanceList([instance.hypervisor])
1463

    
1464
  if instance.name not in running_instances:
1465
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1466

    
1467
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1468
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1469
    try:
1470
      hyper.RebootInstance(instance)
1471
    except errors.HypervisorError, err:
1472
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1473
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1474
    try:
1475
      InstanceShutdown(instance, shutdown_timeout, reason, store_reason=False)
1476
      result = StartInstance(instance, False, reason, store_reason=False)
1477
      _StoreInstReasonTrail(instance.name, reason)
1478
      return result
1479
    except errors.HypervisorError, err:
1480
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1481
  else:
1482
    _Fail("Invalid reboot_type received: %s", reboot_type)
1483

    
1484

    
1485
def InstanceBalloonMemory(instance, memory):
1486
  """Resize an instance's memory.
1487

1488
  @type instance: L{objects.Instance}
1489
  @param instance: the instance object
1490
  @type memory: int
1491
  @param memory: new memory amount in MB
1492
  @rtype: None
1493

1494
  """
1495
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1496
  running = hyper.ListInstances()
1497
  if instance.name not in running:
1498
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1499
    return
1500
  try:
1501
    hyper.BalloonInstanceMemory(instance, memory)
1502
  except errors.HypervisorError, err:
1503
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1504

    
1505

    
1506
def MigrationInfo(instance):
1507
  """Gather information about an instance to be migrated.
1508

1509
  @type instance: L{objects.Instance}
1510
  @param instance: the instance definition
1511

1512
  """
1513
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1514
  try:
1515
    info = hyper.MigrationInfo(instance)
1516
  except errors.HypervisorError, err:
1517
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1518
  return info
1519

    
1520

    
1521
def AcceptInstance(instance, info, target):
1522
  """Prepare the node to accept an instance.
1523

1524
  @type instance: L{objects.Instance}
1525
  @param instance: the instance definition
1526
  @type info: string/data (opaque)
1527
  @param info: migration information, from the source node
1528
  @type target: string
1529
  @param target: target host (usually ip), on this node
1530

1531
  """
1532
  # TODO: why is this required only for DTS_EXT_MIRROR?
1533
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1534
    # Create the symlinks, as the disks are not active
1535
    # in any way
1536
    try:
1537
      _GatherAndLinkBlockDevs(instance)
1538
    except errors.BlockDeviceError, err:
1539
      _Fail("Block device error: %s", err, exc=True)
1540

    
1541
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1542
  try:
1543
    hyper.AcceptInstance(instance, info, target)
1544
  except errors.HypervisorError, err:
1545
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1546
      _RemoveBlockDevLinks(instance.name, instance.disks)
1547
    _Fail("Failed to accept instance: %s", err, exc=True)
1548

    
1549

    
1550
def FinalizeMigrationDst(instance, info, success):
1551
  """Finalize any preparation to accept an instance.
1552

1553
  @type instance: L{objects.Instance}
1554
  @param instance: the instance definition
1555
  @type info: string/data (opaque)
1556
  @param info: migration information, from the source node
1557
  @type success: boolean
1558
  @param success: whether the migration was a success or a failure
1559

1560
  """
1561
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1562
  try:
1563
    hyper.FinalizeMigrationDst(instance, info, success)
1564
  except errors.HypervisorError, err:
1565
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1566

    
1567

    
1568
def MigrateInstance(instance, target, live):
1569
  """Migrates an instance to another node.
1570

1571
  @type instance: L{objects.Instance}
1572
  @param instance: the instance definition
1573
  @type target: string
1574
  @param target: the target node name
1575
  @type live: boolean
1576
  @param live: whether the migration should be done live or not (the
1577
      interpretation of this parameter is left to the hypervisor)
1578
  @raise RPCFail: if migration fails for some reason
1579

1580
  """
1581
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1582

    
1583
  try:
1584
    hyper.MigrateInstance(instance, target, live)
1585
  except errors.HypervisorError, err:
1586
    _Fail("Failed to migrate instance: %s", err, exc=True)
1587

    
1588

    
1589
def FinalizeMigrationSource(instance, success, live):
1590
  """Finalize the instance migration on the source node.
1591

1592
  @type instance: L{objects.Instance}
1593
  @param instance: the instance definition of the migrated instance
1594
  @type success: bool
1595
  @param success: whether the migration succeeded or not
1596
  @type live: bool
1597
  @param live: whether the user requested a live migration or not
1598
  @raise RPCFail: If the execution fails for some reason
1599

1600
  """
1601
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1602

    
1603
  try:
1604
    hyper.FinalizeMigrationSource(instance, success, live)
1605
  except Exception, err:  # pylint: disable=W0703
1606
    _Fail("Failed to finalize the migration on the source node: %s", err,
1607
          exc=True)
1608

    
1609

    
1610
def GetMigrationStatus(instance):
1611
  """Get the migration status
1612

1613
  @type instance: L{objects.Instance}
1614
  @param instance: the instance that is being migrated
1615
  @rtype: L{objects.MigrationStatus}
1616
  @return: the status of the current migration (one of
1617
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1618
           progress info that can be retrieved from the hypervisor
1619
  @raise RPCFail: If the migration status cannot be retrieved
1620

1621
  """
1622
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1623
  try:
1624
    return hyper.GetMigrationStatus(instance)
1625
  except Exception, err:  # pylint: disable=W0703
1626
    _Fail("Failed to get migration status: %s", err, exc=True)
1627

    
1628

    
1629
def HotplugDevice(instance, action, dev_type, device, extra, seq):
1630
  """Hotplug a device
1631

1632
  Hotplug is currently supported only for KVM Hypervisor.
1633
  @type instance: L{objects.Instance}
1634
  @param instance: the instance to which we hotplug a device
1635
  @type action: string
1636
  @param action: the hotplug action to perform
1637
  @type dev_type: string
1638
  @param dev_type: the device type to hotplug
1639
  @type device: either L{objects.NIC} or L{objects.Disk}
1640
  @param device: the device object to hotplug
1641
  @type extra: string
1642
  @param extra: extra info used by hotplug code (e.g. disk link)
1643
  @type seq: int
1644
  @param seq: the index of the device from master perspective
1645
  @raise RPCFail: in case instance does not have KVM hypervisor
1646

1647
  """
1648
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1649
  try:
1650
    hyper.VerifyHotplugSupport(instance, action, dev_type)
1651
  except errors.HotplugError, err:
1652
    _Fail("Hotplug is not supported: %s", err)
1653

    
1654
  if action == constants.HOTPLUG_ACTION_ADD:
1655
    fn = hyper.HotAddDevice
1656
  elif action == constants.HOTPLUG_ACTION_REMOVE:
1657
    fn = hyper.HotDelDevice
1658
  elif action == constants.HOTPLUG_ACTION_MODIFY:
1659
    fn = hyper.HotModDevice
1660
  else:
1661
    assert action in constants.HOTPLUG_ALL_ACTIONS
1662
  # This will raise an exception if hotplug is no supported for this case
1663
  return fn(instance, dev_type, device, extra, seq)
1664

    
1665

    
1666
def HotplugSupported(instance):
1667
  """Checks if hotplug is generally supported.
1668

1669
  """
1670
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1671
  try:
1672
    hyper.HotplugSupported(instance)
1673
  except errors.HotplugError, err:
1674
    _Fail("Hotplug is not supported: %s", err)
1675

    
1676

    
1677
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
1678
  """Creates a block device for an instance.
1679

1680
  @type disk: L{objects.Disk}
1681
  @param disk: the object describing the disk we should create
1682
  @type size: int
1683
  @param size: the size of the physical underlying device, in MiB
1684
  @type owner: str
1685
  @param owner: the name of the instance for which disk is created,
1686
      used for device cache data
1687
  @type on_primary: boolean
1688
  @param on_primary:  indicates if it is the primary node or not
1689
  @type info: string
1690
  @param info: string that will be sent to the physical device
1691
      creation, used for example to set (LVM) tags on LVs
1692
  @type excl_stor: boolean
1693
  @param excl_stor: Whether exclusive_storage is active
1694

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

1699
  """
1700
  # TODO: remove the obsolete "size" argument
1701
  # pylint: disable=W0613
1702
  clist = []
1703
  if disk.children:
1704
    for child in disk.children:
1705
      try:
1706
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1707
      except errors.BlockDeviceError, err:
1708
        _Fail("Can't assemble device %s: %s", child, err)
1709
      if on_primary or disk.AssembleOnSecondary():
1710
        # we need the children open in case the device itself has to
1711
        # be assembled
1712
        try:
1713
          # pylint: disable=E1103
1714
          crdev.Open()
1715
        except errors.BlockDeviceError, err:
1716
          _Fail("Can't make child '%s' read-write: %s", child, err)
1717
      clist.append(crdev)
1718

    
1719
  try:
1720
    device = bdev.Create(disk, clist, excl_stor)
1721
  except errors.BlockDeviceError, err:
1722
    _Fail("Can't create block device: %s", err)
1723

    
1724
  if on_primary or disk.AssembleOnSecondary():
1725
    try:
1726
      device.Assemble()
1727
    except errors.BlockDeviceError, err:
1728
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1729
    if on_primary or disk.OpenOnSecondary():
1730
      try:
1731
        device.Open(force=True)
1732
      except errors.BlockDeviceError, err:
1733
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1734
    DevCacheManager.UpdateCache(device.dev_path, owner,
1735
                                on_primary, disk.iv_name)
1736

    
1737
  device.SetInfo(info)
1738

    
1739
  return device.unique_id
1740

    
1741

    
1742
def _WipeDevice(path, offset, size):
1743
  """This function actually wipes the device.
1744

1745
  @param path: The path to the device to wipe
1746
  @param offset: The offset in MiB in the file
1747
  @param size: The size in MiB to write
1748

1749
  """
1750
  # Internal sizes are always in Mebibytes; if the following "dd" command
1751
  # should use a different block size the offset and size given to this
1752
  # function must be adjusted accordingly before being passed to "dd".
1753
  block_size = 1024 * 1024
1754

    
1755
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1756
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
1757
         "count=%d" % size]
1758
  result = utils.RunCmd(cmd)
1759

    
1760
  if result.failed:
1761
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1762
          result.fail_reason, result.output)
1763

    
1764

    
1765
def BlockdevWipe(disk, offset, size):
1766
  """Wipes a block device.
1767

1768
  @type disk: L{objects.Disk}
1769
  @param disk: the disk object we want to wipe
1770
  @type offset: int
1771
  @param offset: The offset in MiB in the file
1772
  @type size: int
1773
  @param size: The size in MiB to write
1774

1775
  """
1776
  try:
1777
    rdev = _RecursiveFindBD(disk)
1778
  except errors.BlockDeviceError:
1779
    rdev = None
1780

    
1781
  if not rdev:
1782
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1783

    
1784
  # Do cross verify some of the parameters
1785
  if offset < 0:
1786
    _Fail("Negative offset")
1787
  if size < 0:
1788
    _Fail("Negative size")
1789
  if offset > rdev.size:
1790
    _Fail("Offset is bigger than device size")
1791
  if (offset + size) > rdev.size:
1792
    _Fail("The provided offset and size to wipe is bigger than device size")
1793

    
1794
  _WipeDevice(rdev.dev_path, offset, size)
1795

    
1796

    
1797
def BlockdevPauseResumeSync(disks, pause):
1798
  """Pause or resume the sync of the block device.
1799

1800
  @type disks: list of L{objects.Disk}
1801
  @param disks: the disks object we want to pause/resume
1802
  @type pause: bool
1803
  @param pause: Wheater to pause or resume
1804

1805
  """
1806
  success = []
1807
  for disk in disks:
1808
    try:
1809
      rdev = _RecursiveFindBD(disk)
1810
    except errors.BlockDeviceError:
1811
      rdev = None
1812

    
1813
    if not rdev:
1814
      success.append((False, ("Cannot change sync for device %s:"
1815
                              " device not found" % disk.iv_name)))
1816
      continue
1817

    
1818
    result = rdev.PauseResumeSync(pause)
1819

    
1820
    if result:
1821
      success.append((result, None))
1822
    else:
1823
      if pause:
1824
        msg = "Pause"
1825
      else:
1826
        msg = "Resume"
1827
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1828

    
1829
  return success
1830

    
1831

    
1832
def BlockdevRemove(disk):
1833
  """Remove a block device.
1834

1835
  @note: This is intended to be called recursively.
1836

1837
  @type disk: L{objects.Disk}
1838
  @param disk: the disk object we should remove
1839
  @rtype: boolean
1840
  @return: the success of the operation
1841

1842
  """
1843
  msgs = []
1844
  try:
1845
    rdev = _RecursiveFindBD(disk)
1846
  except errors.BlockDeviceError, err:
1847
    # probably can't attach
1848
    logging.info("Can't attach to device %s in remove", disk)
1849
    rdev = None
1850
  if rdev is not None:
1851
    r_path = rdev.dev_path
1852
    def _TryRemove():
1853
      try:
1854
        rdev.Remove()
1855
        return []
1856
      except errors.BlockDeviceError, err:
1857
        return [str(err)]
1858

    
1859
    msgs.extend(utils.SimpleRetry([], _TryRemove,
1860
                                  constants.DISK_REMOVE_RETRY_INTERVAL,
1861
                                  constants.DISK_REMOVE_RETRY_TIMEOUT))
1862
    if not msgs:
1863
      DevCacheManager.RemoveCache(r_path)
1864

    
1865
  if disk.children:
1866
    for child in disk.children:
1867
      try:
1868
        BlockdevRemove(child)
1869
      except RPCFail, err:
1870
        msgs.append(str(err))
1871

    
1872
  if msgs:
1873
    _Fail("; ".join(msgs))
1874

    
1875

    
1876
def _RecursiveAssembleBD(disk, owner, as_primary):
1877
  """Activate a block device for an instance.
1878

1879
  This is run on the primary and secondary nodes for an instance.
1880

1881
  @note: this function is called recursively.
1882

1883
  @type disk: L{objects.Disk}
1884
  @param disk: the disk we try to assemble
1885
  @type owner: str
1886
  @param owner: the name of the instance which owns the disk
1887
  @type as_primary: boolean
1888
  @param as_primary: if we should make the block device
1889
      read/write
1890

1891
  @return: the assembled device or None (in case no device
1892
      was assembled)
1893
  @raise errors.BlockDeviceError: in case there is an error
1894
      during the activation of the children or the device
1895
      itself
1896

1897
  """
1898
  children = []
1899
  if disk.children:
1900
    mcn = disk.ChildrenNeeded()
1901
    if mcn == -1:
1902
      mcn = 0 # max number of Nones allowed
1903
    else:
1904
      mcn = len(disk.children) - mcn # max number of Nones
1905
    for chld_disk in disk.children:
1906
      try:
1907
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1908
      except errors.BlockDeviceError, err:
1909
        if children.count(None) >= mcn:
1910
          raise
1911
        cdev = None
1912
        logging.error("Error in child activation (but continuing): %s",
1913
                      str(err))
1914
      children.append(cdev)
1915

    
1916
  if as_primary or disk.AssembleOnSecondary():
1917
    r_dev = bdev.Assemble(disk, children)
1918
    result = r_dev
1919
    if as_primary or disk.OpenOnSecondary():
1920
      r_dev.Open()
1921
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1922
                                as_primary, disk.iv_name)
1923

    
1924
  else:
1925
    result = True
1926
  return result
1927

    
1928

    
1929
def BlockdevAssemble(disk, owner, as_primary, idx):
1930
  """Activate a block device for an instance.
1931

1932
  This is a wrapper over _RecursiveAssembleBD.
1933

1934
  @rtype: str or boolean
1935
  @return: a C{/dev/...} path for primary nodes, and
1936
      C{True} for secondary nodes
1937

1938
  """
1939
  try:
1940
    device = _RecursiveAssembleBD(disk, owner, as_primary)
1941
    if isinstance(device, bdev.BlockDev):
1942
      dev_path = device.dev_path
1943
      link_name = None
1944
      if as_primary:
1945
        link_name = _SymlinkBlockDev(owner, dev_path, idx)
1946
    elif device:
1947
      return device, device
1948
  except errors.BlockDeviceError, err:
1949
    _Fail("Error while assembling disk: %s", err, exc=True)
1950
  except OSError, err:
1951
    _Fail("Error while symlinking disk: %s", err, exc=True)
1952

    
1953
  return dev_path, link_name
1954

    
1955

    
1956
def BlockdevShutdown(disk):
1957
  """Shut down a block device.
1958

1959
  First, if the device is assembled (Attach() is successful), then
1960
  the device is shutdown. Then the children of the device are
1961
  shutdown.
1962

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

1967
  @type disk: L{objects.Disk}
1968
  @param disk: the description of the disk we should
1969
      shutdown
1970
  @rtype: None
1971

1972
  """
1973
  msgs = []
1974
  r_dev = _RecursiveFindBD(disk)
1975
  if r_dev is not None:
1976
    r_path = r_dev.dev_path
1977
    try:
1978
      r_dev.Shutdown()
1979
      DevCacheManager.RemoveCache(r_path)
1980
    except errors.BlockDeviceError, err:
1981
      msgs.append(str(err))
1982

    
1983
  if disk.children:
1984
    for child in disk.children:
1985
      try:
1986
        BlockdevShutdown(child)
1987
      except RPCFail, err:
1988
        msgs.append(str(err))
1989

    
1990
  if msgs:
1991
    _Fail("; ".join(msgs))
1992

    
1993

    
1994
def BlockdevAddchildren(parent_cdev, new_cdevs):
1995
  """Extend a mirrored block device.
1996

1997
  @type parent_cdev: L{objects.Disk}
1998
  @param parent_cdev: the disk to which we should add children
1999
  @type new_cdevs: list of L{objects.Disk}
2000
  @param new_cdevs: the list of children which we should add
2001
  @rtype: None
2002

2003
  """
2004
  parent_bdev = _RecursiveFindBD(parent_cdev)
2005
  if parent_bdev is None:
2006
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
2007
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
2008
  if new_bdevs.count(None) > 0:
2009
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
2010
  parent_bdev.AddChildren(new_bdevs)
2011

    
2012

    
2013
def BlockdevRemovechildren(parent_cdev, new_cdevs):
2014
  """Shrink a mirrored block device.
2015

2016
  @type parent_cdev: L{objects.Disk}
2017
  @param parent_cdev: the disk from which we should remove children
2018
  @type new_cdevs: list of L{objects.Disk}
2019
  @param new_cdevs: the list of children which we should remove
2020
  @rtype: None
2021

2022
  """
2023
  parent_bdev = _RecursiveFindBD(parent_cdev)
2024
  if parent_bdev is None:
2025
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
2026
  devs = []
2027
  for disk in new_cdevs:
2028
    rpath = disk.StaticDevPath()
2029
    if rpath is None:
2030
      bd = _RecursiveFindBD(disk)
2031
      if bd is None:
2032
        _Fail("Can't find device %s while removing children", disk)
2033
      else:
2034
        devs.append(bd.dev_path)
2035
    else:
2036
      if not utils.IsNormAbsPath(rpath):
2037
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
2038
      devs.append(rpath)
2039
  parent_bdev.RemoveChildren(devs)
2040

    
2041

    
2042
def BlockdevGetmirrorstatus(disks):
2043
  """Get the mirroring status of a list of devices.
2044

2045
  @type disks: list of L{objects.Disk}
2046
  @param disks: the list of disks which we should query
2047
  @rtype: disk
2048
  @return: List of L{objects.BlockDevStatus}, one for each disk
2049
  @raise errors.BlockDeviceError: if any of the disks cannot be
2050
      found
2051

2052
  """
2053
  stats = []
2054
  for dsk in disks:
2055
    rbd = _RecursiveFindBD(dsk)
2056
    if rbd is None:
2057
      _Fail("Can't find device %s", dsk)
2058

    
2059
    stats.append(rbd.CombinedSyncStatus())
2060

    
2061
  return stats
2062

    
2063

    
2064
def BlockdevGetmirrorstatusMulti(disks):
2065
  """Get the mirroring status of a list of devices.
2066

2067
  @type disks: list of L{objects.Disk}
2068
  @param disks: the list of disks which we should query
2069
  @rtype: disk
2070
  @return: List of tuples, (bool, status), one for each disk; bool denotes
2071
    success/failure, status is L{objects.BlockDevStatus} on success, string
2072
    otherwise
2073

2074
  """
2075
  result = []
2076
  for disk in disks:
2077
    try:
2078
      rbd = _RecursiveFindBD(disk)
2079
      if rbd is None:
2080
        result.append((False, "Can't find device %s" % disk))
2081
        continue
2082

    
2083
      status = rbd.CombinedSyncStatus()
2084
    except errors.BlockDeviceError, err:
2085
      logging.exception("Error while getting disk status")
2086
      result.append((False, str(err)))
2087
    else:
2088
      result.append((True, status))
2089

    
2090
  assert len(disks) == len(result)
2091

    
2092
  return result
2093

    
2094

    
2095
def _RecursiveFindBD(disk):
2096
  """Check if a device is activated.
2097

2098
  If so, return information about the real device.
2099

2100
  @type disk: L{objects.Disk}
2101
  @param disk: the disk object we need to find
2102

2103
  @return: None if the device can't be found,
2104
      otherwise the device instance
2105

2106
  """
2107
  children = []
2108
  if disk.children:
2109
    for chdisk in disk.children:
2110
      children.append(_RecursiveFindBD(chdisk))
2111

    
2112
  return bdev.FindDevice(disk, children)
2113

    
2114

    
2115
def _OpenRealBD(disk):
2116
  """Opens the underlying block device of a disk.
2117

2118
  @type disk: L{objects.Disk}
2119
  @param disk: the disk object we want to open
2120

2121
  """
2122
  real_disk = _RecursiveFindBD(disk)
2123
  if real_disk is None:
2124
    _Fail("Block device '%s' is not set up", disk)
2125

    
2126
  real_disk.Open()
2127

    
2128
  return real_disk
2129

    
2130

    
2131
def BlockdevFind(disk):
2132
  """Check if a device is activated.
2133

2134
  If it is, return information about the real device.
2135

2136
  @type disk: L{objects.Disk}
2137
  @param disk: the disk to find
2138
  @rtype: None or objects.BlockDevStatus
2139
  @return: None if the disk cannot be found, otherwise a the current
2140
           information
2141

2142
  """
2143
  try:
2144
    rbd = _RecursiveFindBD(disk)
2145
  except errors.BlockDeviceError, err:
2146
    _Fail("Failed to find device: %s", err, exc=True)
2147

    
2148
  if rbd is None:
2149
    return None
2150

    
2151
  return rbd.GetSyncStatus()
2152

    
2153

    
2154
def BlockdevGetsize(disks):
2155
  """Computes the size of the given disks.
2156

2157
  If a disk is not found, returns None instead.
2158

2159
  @type disks: list of L{objects.Disk}
2160
  @param disks: the list of disk to compute the size for
2161
  @rtype: list
2162
  @return: list with elements None if the disk cannot be found,
2163
      otherwise the size
2164

2165
  """
2166
  result = []
2167
  for cf in disks:
2168
    try:
2169
      rbd = _RecursiveFindBD(cf)
2170
    except errors.BlockDeviceError:
2171
      result.append(None)
2172
      continue
2173
    if rbd is None:
2174
      result.append(None)
2175
    else:
2176
      result.append(rbd.GetActualSize())
2177
  return result
2178

    
2179

    
2180
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2181
  """Export a block device to a remote node.
2182

2183
  @type disk: L{objects.Disk}
2184
  @param disk: the description of the disk to export
2185
  @type dest_node: str
2186
  @param dest_node: the destination node to export to
2187
  @type dest_path: str
2188
  @param dest_path: the destination path on the target node
2189
  @type cluster_name: str
2190
  @param cluster_name: the cluster name, needed for SSH hostalias
2191
  @rtype: None
2192

2193
  """
2194
  real_disk = _OpenRealBD(disk)
2195

    
2196
  # the block size on the read dd is 1MiB to match our units
2197
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2198
                               "dd if=%s bs=1048576 count=%s",
2199
                               real_disk.dev_path, str(disk.size))
2200

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

    
2210
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2211
                                                   constants.SSH_LOGIN_USER,
2212
                                                   destcmd)
2213

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

    
2217
  result = utils.RunCmd(["bash", "-c", command])
2218

    
2219
  if result.failed:
2220
    _Fail("Disk copy command '%s' returned error: %s"
2221
          " output: %s", command, result.fail_reason, result.output)
2222

    
2223

    
2224
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2225
  """Write a file to the filesystem.
2226

2227
  This allows the master to overwrite(!) a file. It will only perform
2228
  the operation if the file belongs to a list of configuration files.
2229

2230
  @type file_name: str
2231
  @param file_name: the target file name
2232
  @type data: str
2233
  @param data: the new contents of the file
2234
  @type mode: int
2235
  @param mode: the mode to give the file (can be None)
2236
  @type uid: string
2237
  @param uid: the owner of the file
2238
  @type gid: string
2239
  @param gid: the group of the file
2240
  @type atime: float
2241
  @param atime: the atime to set on the file (can be None)
2242
  @type mtime: float
2243
  @param mtime: the mtime to set on the file (can be None)
2244
  @rtype: None
2245

2246
  """
2247
  file_name = vcluster.LocalizeVirtualPath(file_name)
2248

    
2249
  if not os.path.isabs(file_name):
2250
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2251

    
2252
  if file_name not in _ALLOWED_UPLOAD_FILES:
2253
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2254
          file_name)
2255

    
2256
  raw_data = _Decompress(data)
2257

    
2258
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2259
    _Fail("Invalid username/groupname type")
2260

    
2261
  getents = runtime.GetEnts()
2262
  uid = getents.LookupUser(uid)
2263
  gid = getents.LookupGroup(gid)
2264

    
2265
  utils.SafeWriteFile(file_name, None,
2266
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2267
                      atime=atime, mtime=mtime)
2268

    
2269

    
2270
def RunOob(oob_program, command, node, timeout):
2271
  """Executes oob_program with given command on given node.
2272

2273
  @param oob_program: The path to the executable oob_program
2274
  @param command: The command to invoke on oob_program
2275
  @param node: The node given as an argument to the program
2276
  @param timeout: Timeout after which we kill the oob program
2277

2278
  @return: stdout
2279
  @raise RPCFail: If execution fails for some reason
2280

2281
  """
2282
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2283

    
2284
  if result.failed:
2285
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2286
          result.fail_reason, result.output)
2287

    
2288
  return result.stdout
2289

    
2290

    
2291
def _OSOndiskAPIVersion(os_dir):
2292
  """Compute and return the API version of a given OS.
2293

2294
  This function will try to read the API version of the OS residing in
2295
  the 'os_dir' directory.
2296

2297
  @type os_dir: str
2298
  @param os_dir: the directory in which we should look for the OS
2299
  @rtype: tuple
2300
  @return: tuple (status, data) with status denoting the validity and
2301
      data holding either the vaid versions or an error message
2302

2303
  """
2304
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2305

    
2306
  try:
2307
    st = os.stat(api_file)
2308
  except EnvironmentError, err:
2309
    return False, ("Required file '%s' not found under path %s: %s" %
2310
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2311

    
2312
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2313
    return False, ("File '%s' in %s is not a regular file" %
2314
                   (constants.OS_API_FILE, os_dir))
2315

    
2316
  try:
2317
    api_versions = utils.ReadFile(api_file).splitlines()
2318
  except EnvironmentError, err:
2319
    return False, ("Error while reading the API version file at %s: %s" %
2320
                   (api_file, utils.ErrnoOrStr(err)))
2321

    
2322
  try:
2323
    api_versions = [int(version.strip()) for version in api_versions]
2324
  except (TypeError, ValueError), err:
2325
    return False, ("API version(s) can't be converted to integer: %s" %
2326
                   str(err))
2327

    
2328
  return True, api_versions
2329

    
2330

    
2331
def DiagnoseOS(top_dirs=None):
2332
  """Compute the validity for all OSes.
2333

2334
  @type top_dirs: list
2335
  @param top_dirs: the list of directories in which to
2336
      search (if not given defaults to
2337
      L{pathutils.OS_SEARCH_PATH})
2338
  @rtype: list of L{objects.OS}
2339
  @return: a list of tuples (name, path, status, diagnose, variants,
2340
      parameters, api_version) for all (potential) OSes under all
2341
      search paths, where:
2342
          - name is the (potential) OS name
2343
          - path is the full path to the OS
2344
          - status True/False is the validity of the OS
2345
          - diagnose is the error message for an invalid OS, otherwise empty
2346
          - variants is a list of supported OS variants, if any
2347
          - parameters is a list of (name, help) parameters, if any
2348
          - api_version is a list of support OS API versions
2349

2350
  """
2351
  if top_dirs is None:
2352
    top_dirs = pathutils.OS_SEARCH_PATH
2353

    
2354
  result = []
2355
  for dir_name in top_dirs:
2356
    if os.path.isdir(dir_name):
2357
      try:
2358
        f_names = utils.ListVisibleFiles(dir_name)
2359
      except EnvironmentError, err:
2360
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2361
        break
2362
      for name in f_names:
2363
        os_path = utils.PathJoin(dir_name, name)
2364
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2365
        if status:
2366
          diagnose = ""
2367
          variants = os_inst.supported_variants
2368
          parameters = os_inst.supported_parameters
2369
          api_versions = os_inst.api_versions
2370
        else:
2371
          diagnose = os_inst
2372
          variants = parameters = api_versions = []
2373
        result.append((name, os_path, status, diagnose, variants,
2374
                       parameters, api_versions))
2375

    
2376
  return result
2377

    
2378

    
2379
def _TryOSFromDisk(name, base_dir=None):
2380
  """Create an OS instance from disk.
2381

2382
  This function will return an OS instance if the given name is a
2383
  valid OS name.
2384

2385
  @type base_dir: string
2386
  @keyword base_dir: Base directory containing OS installations.
2387
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2388
  @rtype: tuple
2389
  @return: success and either the OS instance if we find a valid one,
2390
      or error message
2391

2392
  """
2393
  if base_dir is None:
2394
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2395
  else:
2396
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2397

    
2398
  if os_dir is None:
2399
    return False, "Directory for OS %s not found in search path" % name
2400

    
2401
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2402
  if not status:
2403
    # push the error up
2404
    return status, api_versions
2405

    
2406
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2407
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2408
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2409

    
2410
  # OS Files dictionary, we will populate it with the absolute path
2411
  # names; if the value is True, then it is a required file, otherwise
2412
  # an optional one
2413
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2414

    
2415
  if max(api_versions) >= constants.OS_API_V15:
2416
    os_files[constants.OS_VARIANTS_FILE] = False
2417

    
2418
  if max(api_versions) >= constants.OS_API_V20:
2419
    os_files[constants.OS_PARAMETERS_FILE] = True
2420
  else:
2421
    del os_files[constants.OS_SCRIPT_VERIFY]
2422

    
2423
  for (filename, required) in os_files.items():
2424
    os_files[filename] = utils.PathJoin(os_dir, filename)
2425

    
2426
    try:
2427
      st = os.stat(os_files[filename])
2428
    except EnvironmentError, err:
2429
      if err.errno == errno.ENOENT and not required:
2430
        del os_files[filename]
2431
        continue
2432
      return False, ("File '%s' under path '%s' is missing (%s)" %
2433
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2434

    
2435
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2436
      return False, ("File '%s' under path '%s' is not a regular file" %
2437
                     (filename, os_dir))
2438

    
2439
    if filename in constants.OS_SCRIPTS:
2440
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2441
        return False, ("File '%s' under path '%s' is not executable" %
2442
                       (filename, os_dir))
2443

    
2444
  variants = []
2445
  if constants.OS_VARIANTS_FILE in os_files:
2446
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2447
    try:
2448
      variants = \
2449
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2450
    except EnvironmentError, err:
2451
      # we accept missing files, but not other errors
2452
      if err.errno != errno.ENOENT:
2453
        return False, ("Error while reading the OS variants file at %s: %s" %
2454
                       (variants_file, utils.ErrnoOrStr(err)))
2455

    
2456
  parameters = []
2457
  if constants.OS_PARAMETERS_FILE in os_files:
2458
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2459
    try:
2460
      parameters = utils.ReadFile(parameters_file).splitlines()
2461
    except EnvironmentError, err:
2462
      return False, ("Error while reading the OS parameters file at %s: %s" %
2463
                     (parameters_file, utils.ErrnoOrStr(err)))
2464
    parameters = [v.split(None, 1) for v in parameters]
2465

    
2466
  os_obj = objects.OS(name=name, path=os_dir,
2467
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2468
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2469
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2470
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2471
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2472
                                                 None),
2473
                      supported_variants=variants,
2474
                      supported_parameters=parameters,
2475
                      api_versions=api_versions)
2476
  return True, os_obj
2477

    
2478

    
2479
def OSFromDisk(name, base_dir=None):
2480
  """Create an OS instance from disk.
2481

2482
  This function will return an OS instance if the given name is a
2483
  valid OS name. Otherwise, it will raise an appropriate
2484
  L{RPCFail} exception, detailing why this is not a valid OS.
2485

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

2489
  @type base_dir: string
2490
  @keyword base_dir: Base directory containing OS installations.
2491
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2492
  @rtype: L{objects.OS}
2493
  @return: the OS instance if we find a valid one
2494
  @raise RPCFail: if we don't find a valid OS
2495

2496
  """
2497
  name_only = objects.OS.GetName(name)
2498
  status, payload = _TryOSFromDisk(name_only, base_dir)
2499

    
2500
  if not status:
2501
    _Fail(payload)
2502

    
2503
  return payload
2504

    
2505

    
2506
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2507
  """Calculate the basic environment for an os script.
2508

2509
  @type os_name: str
2510
  @param os_name: full operating system name (including variant)
2511
  @type inst_os: L{objects.OS}
2512
  @param inst_os: operating system for which the environment is being built
2513
  @type os_params: dict
2514
  @param os_params: the OS parameters
2515
  @type debug: integer
2516
  @param debug: debug level (0 or 1, for OS Api 10)
2517
  @rtype: dict
2518
  @return: dict of environment variables
2519
  @raise errors.BlockDeviceError: if the block device
2520
      cannot be found
2521

2522
  """
2523
  result = {}
2524
  api_version = \
2525
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2526
  result["OS_API_VERSION"] = "%d" % api_version
2527
  result["OS_NAME"] = inst_os.name
2528
  result["DEBUG_LEVEL"] = "%d" % debug
2529

    
2530
  # OS variants
2531
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2532
    variant = objects.OS.GetVariant(os_name)
2533
    if not variant:
2534
      variant = inst_os.supported_variants[0]
2535
  else:
2536
    variant = ""
2537
  result["OS_VARIANT"] = variant
2538

    
2539
  # OS params
2540
  for pname, pvalue in os_params.items():
2541
    result["OSP_%s" % pname.upper()] = pvalue
2542

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

    
2548
  return result
2549

    
2550

    
2551
def OSEnvironment(instance, inst_os, debug=0):
2552
  """Calculate the environment for an os script.
2553

2554
  @type instance: L{objects.Instance}
2555
  @param instance: target instance for the os script run
2556
  @type inst_os: L{objects.OS}
2557
  @param inst_os: operating system for which the environment is being built
2558
  @type debug: integer
2559
  @param debug: debug level (0 or 1, for OS Api 10)
2560
  @rtype: dict
2561
  @return: dict of environment variables
2562
  @raise errors.BlockDeviceError: if the block device
2563
      cannot be found
2564

2565
  """
2566
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2567

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

    
2571
  result["HYPERVISOR"] = instance.hypervisor
2572
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2573
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2574
  result["INSTANCE_SECONDARY_NODES"] = \
2575
      ("%s" % " ".join(instance.secondary_nodes))
2576

    
2577
  # Disks
2578
  for idx, disk in enumerate(instance.disks):
2579
    real_disk = _OpenRealBD(disk)
2580
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2581
    result["DISK_%d_ACCESS" % idx] = disk.mode
2582
    result["DISK_%d_UUID" % idx] = disk.uuid
2583
    if disk.name:
2584
      result["DISK_%d_NAME" % idx] = disk.name
2585
    if constants.HV_DISK_TYPE in instance.hvparams:
2586
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2587
        instance.hvparams[constants.HV_DISK_TYPE]
2588
    if disk.dev_type in constants.LDS_BLOCK:
2589
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2590
    elif disk.dev_type == constants.LD_FILE:
2591
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2592
        "file:%s" % disk.physical_id[0]
2593

    
2594
  # NICs
2595
  for idx, nic in enumerate(instance.nics):
2596
    result["NIC_%d_MAC" % idx] = nic.mac
2597
    result["NIC_%d_UUID" % idx] = nic.uuid
2598
    if nic.name:
2599
      result["NIC_%d_NAME" % idx] = nic.name
2600
    if nic.ip:
2601
      result["NIC_%d_IP" % idx] = nic.ip
2602
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2603
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2604
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2605
    if nic.nicparams[constants.NIC_LINK]:
2606
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2607
    if nic.netinfo:
2608
      nobj = objects.Network.FromDict(nic.netinfo)
2609
      result.update(nobj.HooksDict("NIC_%d_" % idx))
2610
    if constants.HV_NIC_TYPE in instance.hvparams:
2611
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2612
        instance.hvparams[constants.HV_NIC_TYPE]
2613

    
2614
  # HV/BE params
2615
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2616
    for key, value in source.items():
2617
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2618

    
2619
  return result
2620

    
2621

    
2622
def DiagnoseExtStorage(top_dirs=None):
2623
  """Compute the validity for all ExtStorage Providers.
2624

2625
  @type top_dirs: list
2626
  @param top_dirs: the list of directories in which to
2627
      search (if not given defaults to
2628
      L{pathutils.ES_SEARCH_PATH})
2629
  @rtype: list of L{objects.ExtStorage}
2630
  @return: a list of tuples (name, path, status, diagnose, parameters)
2631
      for all (potential) ExtStorage Providers under all
2632
      search paths, where:
2633
          - name is the (potential) ExtStorage Provider
2634
          - path is the full path to the ExtStorage Provider
2635
          - status True/False is the validity of the ExtStorage Provider
2636
          - diagnose is the error message for an invalid ExtStorage Provider,
2637
            otherwise empty
2638
          - parameters is a list of (name, help) parameters, if any
2639

2640
  """
2641
  if top_dirs is None:
2642
    top_dirs = pathutils.ES_SEARCH_PATH
2643

    
2644
  result = []
2645
  for dir_name in top_dirs:
2646
    if os.path.isdir(dir_name):
2647
      try:
2648
        f_names = utils.ListVisibleFiles(dir_name)
2649
      except EnvironmentError, err:
2650
        logging.exception("Can't list the ExtStorage directory %s: %s",
2651
                          dir_name, err)
2652
        break
2653
      for name in f_names:
2654
        es_path = utils.PathJoin(dir_name, name)
2655
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2656
        if status:
2657
          diagnose = ""
2658
          parameters = es_inst.supported_parameters
2659
        else:
2660
          diagnose = es_inst
2661
          parameters = []
2662
        result.append((name, es_path, status, diagnose, parameters))
2663

    
2664
  return result
2665

    
2666

    
2667
def BlockdevGrow(disk, amount, dryrun, backingstore):
2668
  """Grow a stack of block devices.
2669

2670
  This function is called recursively, with the childrens being the
2671
  first ones to resize.
2672

2673
  @type disk: L{objects.Disk}
2674
  @param disk: the disk to be grown
2675
  @type amount: integer
2676
  @param amount: the amount (in mebibytes) to grow with
2677
  @type dryrun: boolean
2678
  @param dryrun: whether to execute the operation in simulation mode
2679
      only, without actually increasing the size
2680
  @param backingstore: whether to execute the operation on backing storage
2681
      only, or on "logical" storage only; e.g. DRBD is logical storage,
2682
      whereas LVM, file, RBD are backing storage
2683
  @rtype: (status, result)
2684
  @return: a tuple with the status of the operation (True/False), and
2685
      the errors message if status is False
2686

2687
  """
2688
  r_dev = _RecursiveFindBD(disk)
2689
  if r_dev is None:
2690
    _Fail("Cannot find block device %s", disk)
2691

    
2692
  try:
2693
    r_dev.Grow(amount, dryrun, backingstore)
2694
  except errors.BlockDeviceError, err:
2695
    _Fail("Failed to grow block device: %s", err, exc=True)
2696

    
2697

    
2698
def BlockdevSnapshot(disk, snapshot_name=None):
2699
  """Create a snapshot copy of a block device.
2700

2701
  This function is called recursively, and the snapshot is actually created
2702
  just for the leaf lvm backend device.
2703

2704
  @type disk: L{objects.Disk}
2705
  @param disk: the disk to be snapshotted
2706
  @rtype: string
2707
  @return: snapshot disk ID as (vg, lv)
2708

2709
  """
2710
  if disk.dev_type == constants.LD_DRBD8:
2711
    if not disk.children:
2712
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2713
            disk.unique_id)
2714
    return BlockdevSnapshot(disk.children[0])
2715
  elif disk.dev_type == constants.LD_LV and not snapshot_name:
2716
    r_dev = _RecursiveFindBD(disk)
2717
    if r_dev is not None:
2718
      # FIXME: choose a saner value for the snapshot size
2719
      # let's stay on the safe side and ask for the full size, for now
2720
      return r_dev.Snapshot(disk.size)
2721
    else:
2722
      _Fail("Cannot find block device %s", disk)
2723
  elif disk.dev_type == constants.DT_EXT:
2724
    r_dev = _RecursiveFindBD(disk)
2725
    if r_dev is not None:
2726
      r_dev.Snapshot(snapshot_name)
2727
    else:
2728
      _Fail("Cannot find block device %s", disk)
2729
  else:
2730
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2731
          disk.unique_id, disk.dev_type)
2732

    
2733

    
2734
def BlockdevSetInfo(disk, info):
2735
  """Sets 'metadata' information on block devices.
2736

2737
  This function sets 'info' metadata on block devices. Initial
2738
  information is set at device creation; this function should be used
2739
  for example after renames.
2740

2741
  @type disk: L{objects.Disk}
2742
  @param disk: the disk to be grown
2743
  @type info: string
2744
  @param info: new 'info' metadata
2745
  @rtype: (status, result)
2746
  @return: a tuple with the status of the operation (True/False), and
2747
      the errors message if status is False
2748

2749
  """
2750
  r_dev = _RecursiveFindBD(disk)
2751
  if r_dev is None:
2752
    _Fail("Cannot find block device %s", disk)
2753

    
2754
  try:
2755
    r_dev.SetInfo(info)
2756
  except errors.BlockDeviceError, err:
2757
    _Fail("Failed to set information on block device: %s", err, exc=True)
2758

    
2759

    
2760
def FinalizeExport(instance, snap_disks):
2761
  """Write out the export configuration information.
2762

2763
  @type instance: L{objects.Instance}
2764
  @param instance: the instance which we export, used for
2765
      saving configuration
2766
  @type snap_disks: list of L{objects.Disk}
2767
  @param snap_disks: list of snapshot block devices, which
2768
      will be used to get the actual name of the dump file
2769

2770
  @rtype: None
2771

2772
  """
2773
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
2774
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
2775

    
2776
  config = objects.SerializableConfigParser()
2777

    
2778
  config.add_section(constants.INISECT_EXP)
2779
  config.set(constants.INISECT_EXP, "version", "0")
2780
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2781
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2782
  config.set(constants.INISECT_EXP, "os", instance.os)
2783
  config.set(constants.INISECT_EXP, "compression", "none")
2784

    
2785
  config.add_section(constants.INISECT_INS)
2786
  config.set(constants.INISECT_INS, "name", instance.name)
2787
  config.set(constants.INISECT_INS, "maxmem", "%d" %
2788
             instance.beparams[constants.BE_MAXMEM])
2789
  config.set(constants.INISECT_INS, "minmem", "%d" %
2790
             instance.beparams[constants.BE_MINMEM])
2791
  # "memory" is deprecated, but useful for exporting to old ganeti versions
2792
  config.set(constants.INISECT_INS, "memory", "%d" %
2793
             instance.beparams[constants.BE_MAXMEM])
2794
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2795
             instance.beparams[constants.BE_VCPUS])
2796
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2797
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2798
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2799

    
2800
  nic_total = 0
2801
  for nic_count, nic in enumerate(instance.nics):
2802
    nic_total += 1
2803
    config.set(constants.INISECT_INS, "nic%d_mac" %
2804
               nic_count, "%s" % nic.mac)
2805
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2806
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
2807
               "%s" % nic.network)
2808
    for param in constants.NICS_PARAMETER_TYPES:
2809
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2810
                 "%s" % nic.nicparams.get(param, None))
2811
  # TODO: redundant: on load can read nics until it doesn't exist
2812
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2813

    
2814
  disk_total = 0
2815
  for disk_count, disk in enumerate(snap_disks):
2816
    if disk:
2817
      disk_total += 1
2818
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2819
                 ("%s" % disk.iv_name))
2820
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2821
                 ("%s" % disk.physical_id[1]))
2822
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2823
                 ("%d" % disk.size))
2824

    
2825
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2826

    
2827
  # New-style hypervisor/backend parameters
2828

    
2829
  config.add_section(constants.INISECT_HYP)
2830
  for name, value in instance.hvparams.items():
2831
    if name not in constants.HVC_GLOBALS:
2832
      config.set(constants.INISECT_HYP, name, str(value))
2833

    
2834
  config.add_section(constants.INISECT_BEP)
2835
  for name, value in instance.beparams.items():
2836
    config.set(constants.INISECT_BEP, name, str(value))
2837

    
2838
  config.add_section(constants.INISECT_OSP)
2839
  for name, value in instance.osparams.items():
2840
    config.set(constants.INISECT_OSP, name, str(value))
2841

    
2842
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2843
                  data=config.Dumps())
2844
  shutil.rmtree(finaldestdir, ignore_errors=True)
2845
  shutil.move(destdir, finaldestdir)
2846

    
2847

    
2848
def ExportInfo(dest):
2849
  """Get export configuration information.
2850

2851
  @type dest: str
2852
  @param dest: directory containing the export
2853

2854
  @rtype: L{objects.SerializableConfigParser}
2855
  @return: a serializable config file containing the
2856
      export info
2857

2858
  """
2859
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2860

    
2861
  config = objects.SerializableConfigParser()
2862
  config.read(cff)
2863

    
2864
  if (not config.has_section(constants.INISECT_EXP) or
2865
      not config.has_section(constants.INISECT_INS)):
2866
    _Fail("Export info file doesn't have the required fields")
2867

    
2868
  return config.Dumps()
2869

    
2870

    
2871
def ListExports():
2872
  """Return a list of exports currently available on this machine.
2873

2874
  @rtype: list
2875
  @return: list of the exports
2876

2877
  """
2878
  if os.path.isdir(pathutils.EXPORT_DIR):
2879
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
2880
  else:
2881
    _Fail("No exports directory")
2882

    
2883

    
2884
def RemoveExport(export):
2885
  """Remove an existing export from the node.
2886

2887
  @type export: str
2888
  @param export: the name of the export to remove
2889
  @rtype: None
2890

2891
  """
2892
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
2893

    
2894
  try:
2895
    shutil.rmtree(target)
2896
  except EnvironmentError, err:
2897
    _Fail("Error while removing the export: %s", err, exc=True)
2898

    
2899

    
2900
def BlockdevRename(devlist):
2901
  """Rename a list of block devices.
2902

2903
  @type devlist: list of tuples
2904
  @param devlist: list of tuples of the form  (disk,
2905
      new_logical_id, new_physical_id); disk is an
2906
      L{objects.Disk} object describing the current disk,
2907
      and new logical_id/physical_id is the name we
2908
      rename it to
2909
  @rtype: boolean
2910
  @return: True if all renames succeeded, False otherwise
2911

2912
  """
2913
  msgs = []
2914
  result = True
2915
  for disk, unique_id in devlist:
2916
    dev = _RecursiveFindBD(disk)
2917
    if dev is None:
2918
      msgs.append("Can't find device %s in rename" % str(disk))
2919
      result = False
2920
      continue
2921
    try:
2922
      old_rpath = dev.dev_path
2923
      dev.Rename(unique_id)
2924
      new_rpath = dev.dev_path
2925
      if old_rpath != new_rpath:
2926
        DevCacheManager.RemoveCache(old_rpath)
2927
        # FIXME: we should add the new cache information here, like:
2928
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2929
        # but we don't have the owner here - maybe parse from existing
2930
        # cache? for now, we only lose lvm data when we rename, which
2931
        # is less critical than DRBD or MD
2932
    except errors.BlockDeviceError, err:
2933
      msgs.append("Can't rename device '%s' to '%s': %s" %
2934
                  (dev, unique_id, err))
2935
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2936
      result = False
2937
  if not result:
2938
    _Fail("; ".join(msgs))
2939

    
2940

    
2941
def _TransformFileStorageDir(fs_dir):
2942
  """Checks whether given file_storage_dir is valid.
2943

2944
  Checks wheter the given fs_dir is within the cluster-wide default
2945
  file_storage_dir or the shared_file_storage_dir, which are stored in
2946
  SimpleStore. Only paths under those directories are allowed.
2947

2948
  @type fs_dir: str
2949
  @param fs_dir: the path to check
2950

2951
  @return: the normalized path if valid, None otherwise
2952

2953
  """
2954
  if not (constants.ENABLE_FILE_STORAGE or
2955
          constants.ENABLE_SHARED_FILE_STORAGE):
2956
    _Fail("File storage disabled at configure time")
2957

    
2958
  bdev.CheckFileStoragePath(fs_dir)
2959

    
2960
  return os.path.normpath(fs_dir)
2961

    
2962

    
2963
def CreateFileStorageDir(file_storage_dir):
2964
  """Create file storage directory.
2965

2966
  @type file_storage_dir: str
2967
  @param file_storage_dir: directory to create
2968

2969
  @rtype: tuple
2970
  @return: tuple with first element a boolean indicating wheter dir
2971
      creation was successful or not
2972

2973
  """
2974
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2975
  if os.path.exists(file_storage_dir):
2976
    if not os.path.isdir(file_storage_dir):
2977
      _Fail("Specified storage dir '%s' is not a directory",
2978
            file_storage_dir)
2979
  else:
2980
    try:
2981
      os.makedirs(file_storage_dir, 0750)
2982
    except OSError, err:
2983
      _Fail("Cannot create file storage directory '%s': %s",
2984
            file_storage_dir, err, exc=True)
2985

    
2986

    
2987
def RemoveFileStorageDir(file_storage_dir):
2988
  """Remove file storage directory.
2989

2990
  Remove it only if it's empty. If not log an error and return.
2991

2992
  @type file_storage_dir: str
2993
  @param file_storage_dir: the directory we should cleanup
2994
  @rtype: tuple (success,)
2995
  @return: tuple of one element, C{success}, denoting
2996
      whether the operation was successful
2997

2998
  """
2999
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3000
  if os.path.exists(file_storage_dir):
3001
    if not os.path.isdir(file_storage_dir):
3002
      _Fail("Specified Storage directory '%s' is not a directory",
3003
            file_storage_dir)
3004
    # deletes dir only if empty, otherwise we want to fail the rpc call
3005
    try:
3006
      os.rmdir(file_storage_dir)
3007
    except OSError, err:
3008
      _Fail("Cannot remove file storage directory '%s': %s",
3009
            file_storage_dir, err)
3010

    
3011

    
3012
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
3013
  """Rename the file storage directory.
3014

3015
  @type old_file_storage_dir: str
3016
  @param old_file_storage_dir: the current path
3017
  @type new_file_storage_dir: str
3018
  @param new_file_storage_dir: the name we should rename to
3019
  @rtype: tuple (success,)
3020
  @return: tuple of one element, C{success}, denoting
3021
      whether the operation was successful
3022

3023
  """
3024
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
3025
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
3026
  if not os.path.exists(new_file_storage_dir):
3027
    if os.path.isdir(old_file_storage_dir):
3028
      try:
3029
        os.rename(old_file_storage_dir, new_file_storage_dir)
3030
      except OSError, err:
3031
        _Fail("Cannot rename '%s' to '%s': %s",
3032
              old_file_storage_dir, new_file_storage_dir, err)
3033
    else:
3034
      _Fail("Specified storage dir '%s' is not a directory",
3035
            old_file_storage_dir)
3036
  else:
3037
    if os.path.exists(old_file_storage_dir):
3038
      _Fail("Cannot rename '%s' to '%s': both locations exist",
3039
            old_file_storage_dir, new_file_storage_dir)
3040

    
3041

    
3042
def _EnsureJobQueueFile(file_name):
3043
  """Checks whether the given filename is in the queue directory.
3044

3045
  @type file_name: str
3046
  @param file_name: the file name we should check
3047
  @rtype: None
3048
  @raises RPCFail: if the file is not valid
3049

3050
  """
3051
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
3052
    _Fail("Passed job queue file '%s' does not belong to"
3053
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
3054

    
3055

    
3056
def JobQueueUpdate(file_name, content):
3057
  """Updates a file in the queue directory.
3058

3059
  This is just a wrapper over L{utils.io.WriteFile}, with proper
3060
  checking.
3061

3062
  @type file_name: str
3063
  @param file_name: the job file name
3064
  @type content: str
3065
  @param content: the new job contents
3066
  @rtype: boolean
3067
  @return: the success of the operation
3068

3069
  """
3070
  file_name = vcluster.LocalizeVirtualPath(file_name)
3071

    
3072
  _EnsureJobQueueFile(file_name)
3073
  getents = runtime.GetEnts()
3074

    
3075
  # Write and replace the file atomically
3076
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3077
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3078

    
3079

    
3080
def JobQueueRename(old, new):
3081
  """Renames a job queue file.
3082

3083
  This is just a wrapper over os.rename with proper checking.
3084

3085
  @type old: str
3086
  @param old: the old (actual) file name
3087
  @type new: str
3088
  @param new: the desired file name
3089
  @rtype: tuple
3090
  @return: the success of the operation and payload
3091

3092
  """
3093
  old = vcluster.LocalizeVirtualPath(old)
3094
  new = vcluster.LocalizeVirtualPath(new)
3095

    
3096
  _EnsureJobQueueFile(old)
3097
  _EnsureJobQueueFile(new)
3098

    
3099
  getents = runtime.GetEnts()
3100

    
3101
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3102
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3103

    
3104

    
3105
def BlockdevClose(instance_name, disks):
3106
  """Closes the given block devices.
3107

3108
  This means they will be switched to secondary mode (in case of
3109
  DRBD).
3110

3111
  @param instance_name: if the argument is not empty, the symlinks
3112
      of this instance will be removed
3113
  @type disks: list of L{objects.Disk}
3114
  @param disks: the list of disks to be closed
3115
  @rtype: tuple (success, message)
3116
  @return: a tuple of success and message, where success
3117
      indicates the succes of the operation, and message
3118
      which will contain the error details in case we
3119
      failed
3120

3121
  """
3122
  bdevs = []
3123
  for cf in disks:
3124
    rd = _RecursiveFindBD(cf)
3125
    if rd is None:
3126
      _Fail("Can't find device %s", cf)
3127
    bdevs.append(rd)
3128

    
3129
  msg = []
3130
  for rd in bdevs:
3131
    try:
3132
      rd.Close()
3133
    except errors.BlockDeviceError, err:
3134
      msg.append(str(err))
3135
  if msg:
3136
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3137
  else:
3138
    if instance_name:
3139
      _RemoveBlockDevLinks(instance_name, disks)
3140

    
3141

    
3142
def ValidateHVParams(hvname, hvparams):
3143
  """Validates the given hypervisor parameters.
3144

3145
  @type hvname: string
3146
  @param hvname: the hypervisor name
3147
  @type hvparams: dict
3148
  @param hvparams: the hypervisor parameters to be validated
3149
  @rtype: None
3150

3151
  """
3152
  try:
3153
    hv_type = hypervisor.GetHypervisor(hvname)
3154
    hv_type.ValidateParameters(hvparams)
3155
  except errors.HypervisorError, err:
3156
    _Fail(str(err), log=False)
3157

    
3158

    
3159
def _CheckOSPList(os_obj, parameters):
3160
  """Check whether a list of parameters is supported by the OS.
3161

3162
  @type os_obj: L{objects.OS}
3163
  @param os_obj: OS object to check
3164
  @type parameters: list
3165
  @param parameters: the list of parameters to check
3166

3167
  """
3168
  supported = [v[0] for v in os_obj.supported_parameters]
3169
  delta = frozenset(parameters).difference(supported)
3170
  if delta:
3171
    _Fail("The following parameters are not supported"
3172
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3173

    
3174

    
3175
def ValidateOS(required, osname, checks, osparams):
3176
  """Validate the given OS' parameters.
3177

3178
  @type required: boolean
3179
  @param required: whether absence of the OS should translate into
3180
      failure or not
3181
  @type osname: string
3182
  @param osname: the OS to be validated
3183
  @type checks: list
3184
  @param checks: list of the checks to run (currently only 'parameters')
3185
  @type osparams: dict
3186
  @param osparams: dictionary with OS parameters
3187
  @rtype: boolean
3188
  @return: True if the validation passed, or False if the OS was not
3189
      found and L{required} was false
3190

3191
  """
3192
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3193
    _Fail("Unknown checks required for OS %s: %s", osname,
3194
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3195

    
3196
  name_only = objects.OS.GetName(osname)
3197
  status, tbv = _TryOSFromDisk(name_only, None)
3198

    
3199
  if not status:
3200
    if required:
3201
      _Fail(tbv)
3202
    else:
3203
      return False
3204

    
3205
  if max(tbv.api_versions) < constants.OS_API_V20:
3206
    return True
3207

    
3208
  if constants.OS_VALIDATE_PARAMETERS in checks:
3209
    _CheckOSPList(tbv, osparams.keys())
3210

    
3211
  validate_env = OSCoreEnv(osname, tbv, osparams)
3212
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3213
                        cwd=tbv.path, reset_env=True)
3214
  if result.failed:
3215
    logging.error("os validate command '%s' returned error: %s output: %s",
3216
                  result.cmd, result.fail_reason, result.output)
3217
    _Fail("OS validation script failed (%s), output: %s",
3218
          result.fail_reason, result.output, log=False)
3219

    
3220
  return True
3221

    
3222

    
3223
def DemoteFromMC():
3224
  """Demotes the current node from master candidate role.
3225

3226
  """
3227
  # try to ensure we're not the master by mistake
3228
  master, myself = ssconf.GetMasterAndMyself()
3229
  if master == myself:
3230
    _Fail("ssconf status shows I'm the master node, will not demote")
3231

    
3232
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3233
  if not result.failed:
3234
    _Fail("The master daemon is running, will not demote")
3235

    
3236
  try:
3237
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3238
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3239
  except EnvironmentError, err:
3240
    if err.errno != errno.ENOENT:
3241
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3242

    
3243
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3244

    
3245

    
3246
def _GetX509Filenames(cryptodir, name):
3247
  """Returns the full paths for the private key and certificate.
3248

3249
  """
3250
  return (utils.PathJoin(cryptodir, name),
3251
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3252
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3253

    
3254

    
3255
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3256
  """Creates a new X509 certificate for SSL/TLS.
3257

3258
  @type validity: int
3259
  @param validity: Validity in seconds
3260
  @rtype: tuple; (string, string)
3261
  @return: Certificate name and public part
3262

3263
  """
3264
  (key_pem, cert_pem) = \
3265
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3266
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3267

    
3268
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3269
                              prefix="x509-%s-" % utils.TimestampForFilename())
3270
  try:
3271
    name = os.path.basename(cert_dir)
3272
    assert len(name) > 5
3273

    
3274
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3275

    
3276
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3277
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3278

    
3279
    # Never return private key as it shouldn't leave the node
3280
    return (name, cert_pem)
3281
  except Exception:
3282
    shutil.rmtree(cert_dir, ignore_errors=True)
3283
    raise
3284

    
3285

    
3286
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3287
  """Removes a X509 certificate.
3288

3289
  @type name: string
3290
  @param name: Certificate name
3291

3292
  """
3293
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3294

    
3295
  utils.RemoveFile(key_file)
3296
  utils.RemoveFile(cert_file)
3297

    
3298
  try:
3299
    os.rmdir(cert_dir)
3300
  except EnvironmentError, err:
3301
    _Fail("Cannot remove certificate directory '%s': %s",
3302
          cert_dir, err)
3303

    
3304

    
3305
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3306
  """Returns the command for the requested input/output.
3307

3308
  @type instance: L{objects.Instance}
3309
  @param instance: The instance object
3310
  @param mode: Import/export mode
3311
  @param ieio: Input/output type
3312
  @param ieargs: Input/output arguments
3313

3314
  """
3315
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3316

    
3317
  env = None
3318
  prefix = None
3319
  suffix = None
3320
  exp_size = None
3321

    
3322
  if ieio == constants.IEIO_FILE:
3323
    (filename, ) = ieargs
3324

    
3325
    if not utils.IsNormAbsPath(filename):
3326
      _Fail("Path '%s' is not normalized or absolute", filename)
3327

    
3328
    real_filename = os.path.realpath(filename)
3329
    directory = os.path.dirname(real_filename)
3330

    
3331
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3332
      _Fail("File '%s' is not under exports directory '%s': %s",
3333
            filename, pathutils.EXPORT_DIR, real_filename)
3334

    
3335
    # Create directory
3336
    utils.Makedirs(directory, mode=0750)
3337

    
3338
    quoted_filename = utils.ShellQuote(filename)
3339

    
3340
    if mode == constants.IEM_IMPORT:
3341
      suffix = "> %s" % quoted_filename
3342
    elif mode == constants.IEM_EXPORT:
3343
      suffix = "< %s" % quoted_filename
3344

    
3345
      # Retrieve file size
3346
      try:
3347
        st = os.stat(filename)
3348
      except EnvironmentError, err:
3349
        logging.error("Can't stat(2) %s: %s", filename, err)
3350
      else:
3351
        exp_size = utils.BytesToMebibyte(st.st_size)
3352

    
3353
  elif ieio == constants.IEIO_RAW_DISK:
3354
    (disk, ) = ieargs
3355

    
3356
    real_disk = _OpenRealBD(disk)
3357

    
3358
    if mode == constants.IEM_IMPORT:
3359
      # we set here a smaller block size as, due to transport buffering, more
3360
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3361
      # is not already there or we pass a wrong path; we use notrunc to no
3362
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3363
      # much memory; this means that at best, we flush every 64k, which will
3364
      # not be very fast
3365
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3366
                                    " bs=%s oflag=dsync"),
3367
                                    real_disk.dev_path,
3368
                                    str(64 * 1024))
3369

    
3370
    elif mode == constants.IEM_EXPORT:
3371
      # the block size on the read dd is 1MiB to match our units
3372
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3373
                                   real_disk.dev_path,
3374
                                   str(1024 * 1024), # 1 MB
3375
                                   str(disk.size))
3376
      exp_size = disk.size
3377

    
3378
  elif ieio == constants.IEIO_SCRIPT:
3379
    (disk, disk_index, ) = ieargs
3380

    
3381
    assert isinstance(disk_index, (int, long))
3382

    
3383
    real_disk = _OpenRealBD(disk)
3384

    
3385
    inst_os = OSFromDisk(instance.os)
3386
    env = OSEnvironment(instance, inst_os)
3387

    
3388
    if mode == constants.IEM_IMPORT:
3389
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3390
      env["IMPORT_INDEX"] = str(disk_index)
3391
      script = inst_os.import_script
3392

    
3393
    elif mode == constants.IEM_EXPORT:
3394
      env["EXPORT_DEVICE"] = real_disk.dev_path
3395
      env["EXPORT_INDEX"] = str(disk_index)
3396
      script = inst_os.export_script
3397

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

    
3401
    if mode == constants.IEM_IMPORT:
3402
      suffix = "| %s" % script_cmd
3403

    
3404
    elif mode == constants.IEM_EXPORT:
3405
      prefix = "%s |" % script_cmd
3406

    
3407
    # Let script predict size
3408
    exp_size = constants.IE_CUSTOM_SIZE
3409

    
3410
  else:
3411
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3412

    
3413
  return (env, prefix, suffix, exp_size)
3414

    
3415

    
3416
def _CreateImportExportStatusDir(prefix):
3417
  """Creates status directory for import/export.
3418

3419
  """
3420
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3421
                          prefix=("%s-%s-" %
3422
                                  (prefix, utils.TimestampForFilename())))
3423

    
3424

    
3425
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3426
                            ieio, ieioargs):
3427
  """Starts an import or export daemon.
3428

3429
  @param mode: Import/output mode
3430
  @type opts: L{objects.ImportExportOptions}
3431
  @param opts: Daemon options
3432
  @type host: string
3433
  @param host: Remote host for export (None for import)
3434
  @type port: int
3435
  @param port: Remote port for export (None for import)
3436
  @type instance: L{objects.Instance}
3437
  @param instance: Instance object
3438
  @type component: string
3439
  @param component: which part of the instance is transferred now,
3440
      e.g. 'disk/0'
3441
  @param ieio: Input/output type
3442
  @param ieioargs: Input/output arguments
3443

3444
  """
3445
  if mode == constants.IEM_IMPORT:
3446
    prefix = "import"
3447

    
3448
    if not (host is None and port is None):
3449
      _Fail("Can not specify host or port on import")
3450

    
3451
  elif mode == constants.IEM_EXPORT:
3452
    prefix = "export"
3453

    
3454
    if host is None or port is None:
3455
      _Fail("Host and port must be specified for an export")
3456

    
3457
  else:
3458
    _Fail("Invalid mode %r", mode)
3459

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

    
3463
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3464
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3465

    
3466
  if opts.key_name is None:
3467
    # Use server.pem
3468
    key_path = pathutils.NODED_CERT_FILE
3469
    cert_path = pathutils.NODED_CERT_FILE
3470
    assert opts.ca_pem is None
3471
  else:
3472
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3473
                                                 opts.key_name)
3474
    assert opts.ca_pem is not None
3475

    
3476
  for i in [key_path, cert_path]:
3477
    if not os.path.exists(i):
3478
      _Fail("File '%s' does not exist" % i)
3479

    
3480
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3481
  try:
3482
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3483
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3484
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3485

    
3486
    if opts.ca_pem is None:
3487
      # Use server.pem
3488
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3489
    else:
3490
      ca = opts.ca_pem
3491

    
3492
    # Write CA file
3493
    utils.WriteFile(ca_file, data=ca, mode=0400)
3494

    
3495
    cmd = [
3496
      pathutils.IMPORT_EXPORT_DAEMON,
3497
      status_file, mode,
3498
      "--key=%s" % key_path,
3499
      "--cert=%s" % cert_path,
3500
      "--ca=%s" % ca_file,
3501
      ]
3502

    
3503
    if host:
3504
      cmd.append("--host=%s" % host)
3505

    
3506
    if port:
3507
      cmd.append("--port=%s" % port)
3508

    
3509
    if opts.ipv6:
3510
      cmd.append("--ipv6")
3511
    else:
3512
      cmd.append("--ipv4")
3513

    
3514
    if opts.compress:
3515
      cmd.append("--compress=%s" % opts.compress)
3516

    
3517
    if opts.magic:
3518
      cmd.append("--magic=%s" % opts.magic)
3519

    
3520
    if exp_size is not None:
3521
      cmd.append("--expected-size=%s" % exp_size)
3522

    
3523
    if cmd_prefix:
3524
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3525

    
3526
    if cmd_suffix:
3527
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3528

    
3529
    if mode == constants.IEM_EXPORT:
3530
      # Retry connection a few times when connecting to remote peer
3531
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3532
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3533
    elif opts.connect_timeout is not None:
3534
      assert mode == constants.IEM_IMPORT
3535
      # Overall timeout for establishing connection while listening
3536
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3537

    
3538
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3539

    
3540
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3541
    # support for receiving a file descriptor for output
3542
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3543
                      output=logfile)
3544

    
3545
    # The import/export name is simply the status directory name
3546
    return os.path.basename(status_dir)
3547

    
3548
  except Exception:
3549
    shutil.rmtree(status_dir, ignore_errors=True)
3550
    raise
3551

    
3552

    
3553
def GetImportExportStatus(names):
3554
  """Returns import/export daemon status.
3555

3556
  @type names: sequence
3557
  @param names: List of names
3558
  @rtype: List of dicts
3559
  @return: Returns a list of the state of each named import/export or None if a
3560
           status couldn't be read
3561

3562
  """
3563
  result = []
3564

    
3565
  for name in names:
3566
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3567
                                 _IES_STATUS_FILE)
3568

    
3569
    try:
3570
      data = utils.ReadFile(status_file)
3571
    except EnvironmentError, err:
3572
      if err.errno != errno.ENOENT:
3573
        raise
3574
      data = None
3575

    
3576
    if not data:
3577
      result.append(None)
3578
      continue
3579

    
3580
    result.append(serializer.LoadJson(data))
3581

    
3582
  return result
3583

    
3584

    
3585
def AbortImportExport(name):
3586
  """Sends SIGTERM to a running import/export daemon.
3587

3588
  """
3589
  logging.info("Abort import/export %s", name)
3590

    
3591
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3592
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3593

    
3594
  if pid:
3595
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3596
                 name, pid)
3597
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3598

    
3599

    
3600
def CleanupImportExport(name):
3601
  """Cleanup after an import or export.
3602

3603
  If the import/export daemon is still running it's killed. Afterwards the
3604
  whole status directory is removed.
3605

3606
  """
3607
  logging.info("Finalizing import/export %s", name)
3608

    
3609
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3610

    
3611
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3612

    
3613
  if pid:
3614
    logging.info("Import/export %s is still running with PID %s",
3615
                 name, pid)
3616
    utils.KillProcess(pid, waitpid=False)
3617

    
3618
  shutil.rmtree(status_dir, ignore_errors=True)
3619

    
3620

    
3621
def _FindDisks(nodes_ip, disks):
3622
  """Sets the physical ID on disks and returns the block devices.
3623

3624
  """
3625
  # set the correct physical ID
3626
  my_name = netutils.Hostname.GetSysName()
3627
  for cf in disks:
3628
    cf.SetPhysicalID(my_name, nodes_ip)
3629

    
3630
  bdevs = []
3631

    
3632
  for cf in disks:
3633
    rd = _RecursiveFindBD(cf)
3634
    if rd is None:
3635
      _Fail("Can't find device %s", cf)
3636
    bdevs.append(rd)
3637
  return bdevs
3638

    
3639

    
3640
def DrbdDisconnectNet(nodes_ip, disks):
3641
  """Disconnects the network on a list of drbd devices.
3642

3643
  """
3644
  bdevs = _FindDisks(nodes_ip, disks)
3645

    
3646
  # disconnect disks
3647
  for rd in bdevs:
3648
    try:
3649
      rd.DisconnectNet()
3650
    except errors.BlockDeviceError, err:
3651
      _Fail("Can't change network configuration to standalone mode: %s",
3652
            err, exc=True)
3653

    
3654

    
3655
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3656
  """Attaches the network on a list of drbd devices.
3657

3658
  """
3659
  bdevs = _FindDisks(nodes_ip, disks)
3660

    
3661
  if multimaster:
3662
    for idx, rd in enumerate(bdevs):
3663
      try:
3664
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3665
      except EnvironmentError, err:
3666
        _Fail("Can't create symlink: %s", err)
3667
  # reconnect disks, switch to new master configuration and if
3668
  # needed primary mode
3669
  for rd in bdevs:
3670
    try:
3671
      rd.AttachNet(multimaster)
3672
    except errors.BlockDeviceError, err:
3673
      _Fail("Can't change network configuration: %s", err)
3674

    
3675
  # wait until the disks are connected; we need to retry the re-attach
3676
  # if the device becomes standalone, as this might happen if the one
3677
  # node disconnects and reconnects in a different mode before the
3678
  # other node reconnects; in this case, one or both of the nodes will
3679
  # decide it has wrong configuration and switch to standalone
3680

    
3681
  def _Attach():
3682
    all_connected = True
3683

    
3684
    for rd in bdevs:
3685
      stats = rd.GetProcStatus()
3686

    
3687
      if multimaster:
3688
        # In the multimaster case we have to wait explicitly until
3689
        # the resource is Connected and UpToDate/UpToDate, because
3690
        # we promote *both nodes* to primary directly afterwards.
3691
        # Being in resync is not enough, since there is a race during which we
3692
        # may promote a node with an Outdated disk to primary, effectively
3693
        # tearing down the connection.
3694
        all_connected = (all_connected and
3695
                         stats.is_connected and
3696
                         stats.is_disk_uptodate and
3697
                         stats.peer_disk_uptodate)
3698
      else:
3699
        all_connected = (all_connected and
3700
                         (stats.is_connected or stats.is_in_resync))
3701

    
3702
      if stats.is_standalone:
3703
        # peer had different config info and this node became
3704
        # standalone, even though this should not happen with the
3705
        # new staged way of changing disk configs
3706
        try:
3707
          rd.AttachNet(multimaster)
3708
        except errors.BlockDeviceError, err:
3709
          _Fail("Can't change network configuration: %s", err)
3710

    
3711
    if not all_connected:
3712
      raise utils.RetryAgain()
3713

    
3714
  try:
3715
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3716
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3717
  except utils.RetryTimeout:
3718
    _Fail("Timeout in disk reconnecting")
3719

    
3720
  if multimaster:
3721
    # change to primary mode
3722
    for rd in bdevs:
3723
      try:
3724
        rd.Open()
3725
      except errors.BlockDeviceError, err:
3726
        _Fail("Can't change to primary mode: %s", err)
3727

    
3728

    
3729
def DrbdWaitSync(nodes_ip, disks):
3730
  """Wait until DRBDs have synchronized.
3731

3732
  """
3733
  def _helper(rd):
3734
    stats = rd.GetProcStatus()
3735
    if not (stats.is_connected or stats.is_in_resync):
3736
      raise utils.RetryAgain()
3737
    return stats
3738

    
3739
  bdevs = _FindDisks(nodes_ip, disks)
3740

    
3741
  min_resync = 100
3742
  alldone = True
3743
  for rd in bdevs:
3744
    try:
3745
      # poll each second for 15 seconds
3746
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3747
    except utils.RetryTimeout:
3748
      stats = rd.GetProcStatus()
3749
      # last check
3750
      if not (stats.is_connected or stats.is_in_resync):
3751
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3752
    alldone = alldone and (not stats.is_in_resync)
3753
    if stats.sync_percent is not None:
3754
      min_resync = min(min_resync, stats.sync_percent)
3755

    
3756
  return (alldone, min_resync)
3757

    
3758

    
3759
def GetDrbdUsermodeHelper():
3760
  """Returns DRBD usermode helper currently configured.
3761

3762
  """
3763
  try:
3764
    return bdev.BaseDRBD.GetUsermodeHelper()
3765
  except errors.BlockDeviceError, err:
3766
    _Fail(str(err))
3767

    
3768

    
3769
def PowercycleNode(hypervisor_type):
3770
  """Hard-powercycle the node.
3771

3772
  Because we need to return first, and schedule the powercycle in the
3773
  background, we won't be able to report failures nicely.
3774

3775
  """
3776
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3777
  try:
3778
    pid = os.fork()
3779
  except OSError:
3780
    # if we can't fork, we'll pretend that we're in the child process
3781
    pid = 0
3782
  if pid > 0:
3783
    return "Reboot scheduled in 5 seconds"
3784
  # ensure the child is running on ram
3785
  try:
3786
    utils.Mlockall()
3787
  except Exception: # pylint: disable=W0703
3788
    pass
3789
  time.sleep(5)
3790
  hyper.PowercycleNode()
3791

    
3792

    
3793
def _VerifyRestrictedCmdName(cmd):
3794
  """Verifies a restricted command name.
3795

3796
  @type cmd: string
3797
  @param cmd: Command name
3798
  @rtype: tuple; (boolean, string or None)
3799
  @return: The tuple's first element is the status; if C{False}, the second
3800
    element is an error message string, otherwise it's C{None}
3801

3802
  """
3803
  if not cmd.strip():
3804
    return (False, "Missing command name")
3805

    
3806
  if os.path.basename(cmd) != cmd:
3807
    return (False, "Invalid command name")
3808

    
3809
  if not constants.EXT_PLUGIN_MASK.match(cmd):
3810
    return (False, "Command name contains forbidden characters")
3811

    
3812
  return (True, None)
3813

    
3814

    
3815
def _CommonRestrictedCmdCheck(path, owner):
3816
  """Common checks for restricted command file system directories and files.
3817

3818
  @type path: string
3819
  @param path: Path to check
3820
  @param owner: C{None} or tuple containing UID and GID
3821
  @rtype: tuple; (boolean, string or C{os.stat} result)
3822
  @return: The tuple's first element is the status; if C{False}, the second
3823
    element is an error message string, otherwise it's the result of C{os.stat}
3824

3825
  """
3826
  if owner is None:
3827
    # Default to root as owner
3828
    owner = (0, 0)
3829

    
3830
  try:
3831
    st = os.stat(path)
3832
  except EnvironmentError, err:
3833
    return (False, "Can't stat(2) '%s': %s" % (path, err))
3834

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

    
3838
  if (st.st_uid, st.st_gid) != owner:
3839
    (owner_uid, owner_gid) = owner
3840
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
3841

    
3842
  return (True, st)
3843

    
3844

    
3845
def _VerifyRestrictedCmdDirectory(path, _owner=None):
3846
  """Verifies restricted command directory.
3847

3848
  @type path: string
3849
  @param path: Path to check
3850
  @rtype: tuple; (boolean, string or None)
3851
  @return: The tuple's first element is the status; if C{False}, the second
3852
    element is an error message string, otherwise it's C{None}
3853

3854
  """
3855
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
3856

    
3857
  if not status:
3858
    return (False, value)
3859

    
3860
  if not stat.S_ISDIR(value.st_mode):
3861
    return (False, "Path '%s' is not a directory" % path)
3862

    
3863
  return (True, None)
3864

    
3865

    
3866
def _VerifyRestrictedCmd(path, cmd, _owner=None):
3867
  """Verifies a whole restricted command and returns its executable filename.
3868

3869
  @type path: string
3870
  @param path: Directory containing restricted commands
3871
  @type cmd: string
3872
  @param cmd: Command name
3873
  @rtype: tuple; (boolean, string)
3874
  @return: The tuple's first element is the status; if C{False}, the second
3875
    element is an error message string, otherwise the second element is the
3876
    absolute path to the executable
3877

3878
  """
3879
  executable = utils.PathJoin(path, cmd)
3880

    
3881
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
3882

    
3883
  if not status:
3884
    return (False, msg)
3885

    
3886
  if not utils.IsExecutable(executable):
3887
    return (False, "access(2) thinks '%s' can't be executed" % executable)
3888

    
3889
  return (True, executable)
3890

    
3891

    
3892
def _PrepareRestrictedCmd(path, cmd,
3893
                          _verify_dir=_VerifyRestrictedCmdDirectory,
3894
                          _verify_name=_VerifyRestrictedCmdName,
3895
                          _verify_cmd=_VerifyRestrictedCmd):
3896
  """Performs a number of tests on a restricted command.
3897

3898
  @type path: string
3899
  @param path: Directory containing restricted commands
3900
  @type cmd: string
3901
  @param cmd: Command name
3902
  @return: Same as L{_VerifyRestrictedCmd}
3903

3904
  """
3905
  # Verify the directory first
3906
  (status, msg) = _verify_dir(path)
3907
  if status:
3908
    # Check command if everything was alright
3909
    (status, msg) = _verify_name(cmd)
3910

    
3911
  if not status:
3912
    return (False, msg)
3913

    
3914
  # Check actual executable
3915
  return _verify_cmd(path, cmd)
3916

    
3917

    
3918
def RunRestrictedCmd(cmd,
3919
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
3920
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
3921
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
3922
                     _sleep_fn=time.sleep,
3923
                     _prepare_fn=_PrepareRestrictedCmd,
3924
                     _runcmd_fn=utils.RunCmd,
3925
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
3926
  """Executes a restricted command after performing strict tests.
3927

3928
  @type cmd: string
3929
  @param cmd: Command name
3930
  @rtype: string
3931
  @return: Command output
3932
  @raise RPCFail: In case of an error
3933

3934
  """
3935
  logging.info("Preparing to run restricted command '%s'", cmd)
3936

    
3937
  if not _enabled:
3938
    _Fail("Restricted commands disabled at configure time")
3939

    
3940
  lock = None
3941
  try:
3942
    cmdresult = None
3943
    try:
3944
      lock = utils.FileLock.Open(_lock_file)
3945
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
3946

    
3947
      (status, value) = _prepare_fn(_path, cmd)
3948

    
3949
      if status:
3950
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
3951
                               postfork_fn=lambda _: lock.Unlock())
3952
      else:
3953
        logging.error(value)
3954
    except Exception: # pylint: disable=W0703
3955
      # Keep original error in log
3956
      logging.exception("Caught exception")
3957

    
3958
    if cmdresult is None:
3959
      logging.info("Sleeping for %0.1f seconds before returning",
3960
                   _RCMD_INVALID_DELAY)
3961
      _sleep_fn(_RCMD_INVALID_DELAY)
3962

    
3963
      # Do not include original error message in returned error
3964
      _Fail("Executing command '%s' failed" % cmd)
3965
    elif cmdresult.failed or cmdresult.fail_reason:
3966
      _Fail("Restricted command '%s' failed: %s; output: %s",
3967
            cmd, cmdresult.fail_reason, cmdresult.output)
3968
    else:
3969
      return cmdresult.output
3970
  finally:
3971
    if lock is not None:
3972
      # Release lock at last
3973
      lock.Close()
3974
      lock = None
3975

    
3976

    
3977
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
3978
  """Creates or removes the watcher pause file.
3979

3980
  @type until: None or number
3981
  @param until: Unix timestamp saying until when the watcher shouldn't run
3982

3983
  """
3984
  if until is None:
3985
    logging.info("Received request to no longer pause watcher")
3986
    utils.RemoveFile(_filename)
3987
  else:
3988
    logging.info("Received request to pause watcher until %s", until)
3989

    
3990
    if not ht.TNumber(until):
3991
      _Fail("Duration must be numeric")
3992

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

    
3995

    
3996
class HooksRunner(object):
3997
  """Hook runner.
3998

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

4002
  """
4003
  def __init__(self, hooks_base_dir=None):
4004
    """Constructor for hooks runner.
4005

4006
    @type hooks_base_dir: str or None
4007
    @param hooks_base_dir: if not None, this overrides the
4008
        L{pathutils.HOOKS_BASE_DIR} (useful for unittests)
4009

4010
    """
4011
    if hooks_base_dir is None:
4012
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
4013
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
4014
    # constant
4015
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
4016

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

4020
    """
4021
    assert len(node_list) == 1
4022
    node = node_list[0]
4023
    _, myself = ssconf.GetMasterAndMyself()
4024
    assert node == myself
4025

    
4026
    results = self.RunHooks(hpath, phase, env)
4027

    
4028
    # Return values in the form expected by HooksMaster
4029
    return {node: (None, False, results)}
4030

    
4031
  def RunHooks(self, hpath, phase, env):
4032
    """Run the scripts in the hooks directory.
4033

4034
    @type hpath: str
4035
    @param hpath: the path to the hooks directory which
4036
        holds the scripts
4037
    @type phase: str
4038
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
4039
        L{constants.HOOKS_PHASE_POST}
4040
    @type env: dict
4041
    @param env: dictionary with the environment for the hook
4042
    @rtype: list
4043
    @return: list of 3-element tuples:
4044
      - script path
4045
      - script result, either L{constants.HKR_SUCCESS} or
4046
        L{constants.HKR_FAIL}
4047
      - output of the script
4048

4049
    @raise errors.ProgrammerError: for invalid input
4050
        parameters
4051

4052
    """
4053
    if phase == constants.HOOKS_PHASE_PRE:
4054
      suffix = "pre"
4055
    elif phase == constants.HOOKS_PHASE_POST:
4056
      suffix = "post"
4057
    else:
4058
      _Fail("Unknown hooks phase '%s'", phase)
4059

    
4060
    subdir = "%s-%s.d" % (hpath, suffix)
4061
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
4062

    
4063
    results = []
4064

    
4065
    if not os.path.isdir(dir_name):
4066
      # for non-existing/non-dirs, we simply exit instead of logging a
4067
      # warning at every operation
4068
      return results
4069

    
4070
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
4071

    
4072
    for (relname, relstatus, runresult) in runparts_results:
4073
      if relstatus == constants.RUNPARTS_SKIP:
4074
        rrval = constants.HKR_SKIP
4075
        output = ""
4076
      elif relstatus == constants.RUNPARTS_ERR:
4077
        rrval = constants.HKR_FAIL
4078
        output = "Hook script execution error: %s" % runresult
4079
      elif relstatus == constants.RUNPARTS_RUN:
4080
        if runresult.failed:
4081
          rrval = constants.HKR_FAIL
4082
        else:
4083
          rrval = constants.HKR_SUCCESS
4084
        output = utils.SafeEncode(runresult.output.strip())
4085
      results.append(("%s/%s" % (subdir, relname), rrval, output))
4086

    
4087
    return results
4088

    
4089

    
4090
class IAllocatorRunner(object):
4091
  """IAllocator runner.
4092

4093
  This class is instantiated on the node side (ganeti-noded) and not on
4094
  the master side.
4095

4096
  """
4097
  @staticmethod
4098
  def Run(name, idata):
4099
    """Run an iallocator script.
4100

4101
    @type name: str
4102
    @param name: the iallocator script name
4103
    @type idata: str
4104
    @param idata: the allocator input data
4105

4106
    @rtype: tuple
4107
    @return: two element tuple of:
4108
       - status
4109
       - either error message or stdout of allocator (for success)
4110

4111
    """
4112
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
4113
                                  os.path.isfile)
4114
    if alloc_script is None:
4115
      _Fail("iallocator module '%s' not found in the search path", name)
4116

    
4117
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
4118
    try:
4119
      os.write(fd, idata)
4120
      os.close(fd)
4121
      result = utils.RunCmd([alloc_script, fin_name])
4122
      if result.failed:
4123
        _Fail("iallocator module '%s' failed: %s, output '%s'",
4124
              name, result.fail_reason, result.output)
4125
    finally:
4126
      os.unlink(fin_name)
4127

    
4128
    return result.stdout
4129

    
4130

    
4131
class DevCacheManager(object):
4132
  """Simple class for managing a cache of block device information.
4133

4134
  """
4135
  _DEV_PREFIX = "/dev/"
4136
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4137

    
4138
  @classmethod
4139
  def _ConvertPath(cls, dev_path):
4140
    """Converts a /dev/name path to the cache file name.
4141

4142
    This replaces slashes with underscores and strips the /dev
4143
    prefix. It then returns the full path to the cache file.
4144

4145
    @type dev_path: str
4146
    @param dev_path: the C{/dev/} path name
4147
    @rtype: str
4148
    @return: the converted path name
4149

4150
    """
4151
    if dev_path.startswith(cls._DEV_PREFIX):
4152
      dev_path = dev_path[len(cls._DEV_PREFIX):]
4153
    dev_path = dev_path.replace("/", "_")
4154
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4155
    return fpath
4156

    
4157
  @classmethod
4158
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4159
    """Updates the cache information for a given device.
4160

4161
    @type dev_path: str
4162
    @param dev_path: the pathname of the device
4163
    @type owner: str
4164
    @param owner: the owner (instance name) of the device
4165
    @type on_primary: bool
4166
    @param on_primary: whether this is the primary
4167
        node nor not
4168
    @type iv_name: str
4169
    @param iv_name: the instance-visible name of the
4170
        device, as in objects.Disk.iv_name
4171

4172
    @rtype: None
4173

4174
    """
4175
    if dev_path is None:
4176
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
4177
      return
4178
    fpath = cls._ConvertPath(dev_path)
4179
    if on_primary:
4180
      state = "primary"
4181
    else:
4182
      state = "secondary"
4183
    if iv_name is None:
4184
      iv_name = "not_visible"
4185
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4186
    try:
4187
      utils.WriteFile(fpath, data=fdata)
4188
    except EnvironmentError, err:
4189
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4190

    
4191
  @classmethod
4192
  def RemoveCache(cls, dev_path):
4193
    """Remove data for a dev_path.
4194

4195
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
4196
    path name and logging.
4197

4198
    @type dev_path: str
4199
    @param dev_path: the pathname of the device
4200

4201
    @rtype: None
4202

4203
    """
4204
    if dev_path is None:
4205
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
4206
      return
4207
    fpath = cls._ConvertPath(dev_path)
4208
    try:
4209
      utils.RemoveFile(fpath)
4210
    except EnvironmentError, err:
4211
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)