Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 52a8a6ae

History | View | Annotate | Download (136.1 kB)

1
#
2
#
3

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

    
21

    
22
"""Functions used by the node daemon
23

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

29
"""
30

    
31
# pylint: disable=E1103
32

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

    
37

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

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

    
73

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

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

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

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

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

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

    
108

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

112
  Its argument is the error message.
113

114
  """
115

    
116

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

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

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

    
128

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

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

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

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

    
144

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

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

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

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

    
167

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

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

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

    
177

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

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

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

    
190

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

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

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

    
210

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

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

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

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

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

    
240

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

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

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

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

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

    
267
  return frozenset(allowed_files)
268

    
269

    
270
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
271

    
272

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

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

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

    
283

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

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

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

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

    
308

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

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

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

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

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

    
340
      return result
341
    return wrapper
342
  return decorator
343

    
344

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

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

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

    
365
  return env
366

    
367

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

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

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

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

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

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

    
396

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

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

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

    
413

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

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

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

424
  """
425

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

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

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

    
441

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

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

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

    
458

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

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

464
  @rtype: None
465

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

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

    
476

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

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

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

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

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

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

    
507

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

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

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

    
529

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

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

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

540
  @param modify_ssh_setup: boolean
541

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

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

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

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

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

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

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

    
575

    
576
def _GetLvmVgSpaceInfo(name, params):
577
  """Wrapper around C{_GetVgInfo} which checks the storage parameters.
578

579
  @type name: string
580
  @param name: name of the volume group
581
  @type params: list
582
  @param params: list of storage parameters, which in this case should be
583
    containing only one for exclusive storage
584

585
  """
586
  if params is None:
587
    raise errors.ProgrammerError("No storage parameter for LVM vg storage"
588
                                 " reporting is provided.")
589
  if not isinstance(params, list):
590
    raise errors.ProgrammerError("The storage parameters are not of type"
591
                                 " list: '%s'" % params)
592
  if not len(params) == 1:
593
    raise errors.ProgrammerError("Received more than one storage parameter:"
594
                                 " '%s'" % params)
595
  excl_stor = bool(params[0])
596
  return _GetVgInfo(name, excl_stor)
597

    
598

    
599
def _GetVgInfo(name, excl_stor):
600
  """Retrieves information about a LVM volume group.
601

602
  """
603
  # TODO: GetVGInfo supports returning information for multiple VGs at once
604
  vginfo = bdev.LogicalVolume.GetVGInfo([name], excl_stor)
605
  if vginfo:
606
    vg_free = int(round(vginfo[0][0], 0))
607
    vg_size = int(round(vginfo[0][1], 0))
608
  else:
609
    vg_free = None
610
    vg_size = None
611

    
612
  return {
613
    "type": constants.ST_LVM_VG,
614
    "name": name,
615
    "storage_free": vg_free,
616
    "storage_size": vg_size,
617
    }
618

    
619

    
620
def _GetVgSpindlesInfo(name, excl_stor):
621
  """Retrieves information about spindles in an LVM volume group.
622

623
  @type name: string
624
  @param name: VG name
625
  @type excl_stor: bool
626
  @param excl_stor: exclusive storage
627
  @rtype: dict
628
  @return: dictionary whose keys are "name", "vg_free", "vg_size" for VG name,
629
      free spindles, total spindles respectively
630

631
  """
632
  if excl_stor:
633
    (vg_free, vg_size) = bdev.LogicalVolume.GetVgSpindlesInfo(name)
634
  else:
635
    vg_free = 0
636
    vg_size = 0
637
  return {
638
    "type": constants.ST_LVM_PV,
639
    "name": name,
640
    "storage_free": vg_free,
641
    "storage_size": vg_size,
642
    }
643

    
644

    
645
def _GetHvInfo(name, hvparams, get_hv_fn=hypervisor.GetHypervisor):
646
  """Retrieves node information from a hypervisor.
647

648
  The information returned depends on the hypervisor. Common items:
649

650
    - vg_size is the size of the configured volume group in MiB
651
    - vg_free is the free size of the volume group in MiB
652
    - memory_dom0 is the memory allocated for domain0 in MiB
653
    - memory_free is the currently available (free) ram in MiB
654
    - memory_total is the total number of ram in MiB
655
    - hv_version: the hypervisor version, if available
656

657
  @type hvparams: dict of string
658
  @param hvparams: the hypervisor's hvparams
659

660
  """
661
  return get_hv_fn(name).GetNodeInfo(hvparams=hvparams)
662

    
663

    
664
def _GetHvInfoAll(hv_specs, get_hv_fn=hypervisor.GetHypervisor):
665
  """Retrieves node information for all hypervisors.
666

667
  See C{_GetHvInfo} for information on the output.
668

669
  @type hv_specs: list of pairs (string, dict of strings)
670
  @param hv_specs: list of pairs of a hypervisor's name and its hvparams
671

672
  """
673
  if hv_specs is None:
674
    return None
675

    
676
  result = []
677
  for hvname, hvparams in hv_specs:
678
    result.append(_GetHvInfo(hvname, hvparams, get_hv_fn))
679
  return result
680

    
681

    
682
def _GetNamedNodeInfo(names, fn):
683
  """Calls C{fn} for all names in C{names} and returns a dictionary.
684

685
  @rtype: None or dict
686

687
  """
688
  if names is None:
689
    return None
690
  else:
691
    return map(fn, names)
692

    
693

    
694
def GetNodeInfo(storage_units, hv_specs):
695
  """Gives back a hash with different information about the node.
696

697
  @type storage_units: list of tuples (string, string, list)
698
  @param storage_units: List of tuples (storage unit, identifier, parameters) to
699
    ask for disk space information. In case of lvm-vg, the identifier is
700
    the VG name. The parameters can contain additional, storage-type-specific
701
    parameters, for example exclusive storage for lvm storage.
702
  @type hv_specs: list of pairs (string, dict of strings)
703
  @param hv_specs: list of pairs of a hypervisor's name and its hvparams
704
  @rtype: tuple; (string, None/dict, None/dict)
705
  @return: Tuple containing boot ID, volume group information and hypervisor
706
    information
707

708
  """
709
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
710
  storage_info = _GetNamedNodeInfo(
711
    storage_units,
712
    (lambda (storage_type, storage_key, storage_params):
713
        _ApplyStorageInfoFunction(storage_type, storage_key, storage_params)))
714
  hv_info = _GetHvInfoAll(hv_specs)
715
  return (bootid, storage_info, hv_info)
716

    
717

    
718
# pylint: disable=W0613
719
def _GetFileStorageSpaceInfo(path, *args):
720
  """Wrapper around filestorage.GetSpaceInfo.
721

722
  The purpose of this wrapper is to call filestorage.GetFileStorageSpaceInfo
723
  and ignore the *args parameter to not leak it into the filestorage
724
  module's code.
725

726
  @see: C{filestorage.GetFileStorageSpaceInfo} for description of the
727
    parameters.
728

729
  """
730
  return filestorage.GetFileStorageSpaceInfo(path)
731

    
732

    
733
# FIXME: implement storage reporting for all missing storage types.
734
_STORAGE_TYPE_INFO_FN = {
735
  constants.ST_BLOCK: None,
736
  constants.ST_DISKLESS: None,
737
  constants.ST_EXT: None,
738
  constants.ST_FILE: _GetFileStorageSpaceInfo,
739
  constants.ST_LVM_PV: _GetVgSpindlesInfo,
740
  constants.ST_LVM_VG: _GetLvmVgSpaceInfo,
741
  constants.ST_RADOS: None,
742
}
743

    
744

    
745
def _ApplyStorageInfoFunction(storage_type, storage_key, *args):
746
  """Looks up and applies the correct function to calculate free and total
747
  storage for the given storage type.
748

749
  @type storage_type: string
750
  @param storage_type: the storage type for which the storage shall be reported.
751
  @type storage_key: string
752
  @param storage_key: identifier of a storage unit, e.g. the volume group name
753
    of an LVM storage unit
754
  @type args: any
755
  @param args: various parameters that can be used for storage reporting. These
756
    parameters and their semantics vary from storage type to storage type and
757
    are just propagated in this function.
758
  @return: the results of the application of the storage space function (see
759
    _STORAGE_TYPE_INFO_FN) if storage space reporting is implemented for that
760
    storage type
761
  @raises NotImplementedError: for storage types who don't support space
762
    reporting yet
763
  """
764
  fn = _STORAGE_TYPE_INFO_FN[storage_type]
765
  if fn is not None:
766
    return fn(storage_key, *args)
767
  else:
768
    raise NotImplementedError
769

    
770

    
771
def _CheckExclusivePvs(pvi_list):
772
  """Check that PVs are not shared among LVs
773

774
  @type pvi_list: list of L{objects.LvmPvInfo} objects
775
  @param pvi_list: information about the PVs
776

777
  @rtype: list of tuples (string, list of strings)
778
  @return: offending volumes, as tuples: (pv_name, [lv1_name, lv2_name...])
779

780
  """
781
  res = []
782
  for pvi in pvi_list:
783
    if len(pvi.lv_list) > 1:
784
      res.append((pvi.name, pvi.lv_list))
785
  return res
786

    
787

    
788
def _VerifyHypervisors(what, vm_capable, result, all_hvparams,
789
                       get_hv_fn=hypervisor.GetHypervisor):
790
  """Verifies the hypervisor. Appends the results to the 'results' list.
791

792
  @type what: C{dict}
793
  @param what: a dictionary of things to check
794
  @type vm_capable: boolean
795
  @param vm_capable: whether or not this node is vm capable
796
  @type result: dict
797
  @param result: dictionary of verification results; results of the
798
    verifications in this function will be added here
799
  @type all_hvparams: dict of dict of string
800
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
801
  @type get_hv_fn: function
802
  @param get_hv_fn: function to retrieve the hypervisor, to improve testability
803

804
  """
805
  if not vm_capable:
806
    return
807

    
808
  if constants.NV_HYPERVISOR in what:
809
    result[constants.NV_HYPERVISOR] = {}
810
    for hv_name in what[constants.NV_HYPERVISOR]:
811
      hvparams = all_hvparams[hv_name]
812
      try:
813
        val = get_hv_fn(hv_name).Verify(hvparams=hvparams)
814
      except errors.HypervisorError, err:
815
        val = "Error while checking hypervisor: %s" % str(err)
816
      result[constants.NV_HYPERVISOR][hv_name] = val
817

    
818

    
819
def _VerifyHvparams(what, vm_capable, result,
820
                    get_hv_fn=hypervisor.GetHypervisor):
821
  """Verifies the hvparams. Appends the results to the 'results' list.
822

823
  @type what: C{dict}
824
  @param what: a dictionary of things to check
825
  @type vm_capable: boolean
826
  @param vm_capable: whether or not this node is vm capable
827
  @type result: dict
828
  @param result: dictionary of verification results; results of the
829
    verifications in this function will be added here
830
  @type get_hv_fn: function
831
  @param get_hv_fn: function to retrieve the hypervisor, to improve testability
832

833
  """
834
  if not vm_capable:
835
    return
836

    
837
  if constants.NV_HVPARAMS in what:
838
    result[constants.NV_HVPARAMS] = []
839
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
840
      try:
841
        logging.info("Validating hv %s, %s", hv_name, hvparms)
842
        get_hv_fn(hv_name).ValidateParameters(hvparms)
843
      except errors.HypervisorError, err:
844
        result[constants.NV_HVPARAMS].append((source, hv_name, str(err)))
845

    
846

    
847
def _VerifyInstanceList(what, vm_capable, result, all_hvparams):
848
  """Verifies the instance list.
849

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

860
  """
861
  if constants.NV_INSTANCELIST in what and vm_capable:
862
    # GetInstanceList can fail
863
    try:
864
      val = GetInstanceList(what[constants.NV_INSTANCELIST],
865
                            all_hvparams=all_hvparams)
866
    except RPCFail, err:
867
      val = str(err)
868
    result[constants.NV_INSTANCELIST] = val
869

    
870

    
871
def _VerifyNodeInfo(what, vm_capable, result, all_hvparams):
872
  """Verifies the node info.
873

874
  @type what: C{dict}
875
  @param what: a dictionary of things to check
876
  @type vm_capable: boolean
877
  @param vm_capable: whether or not this node is vm capable
878
  @type result: dict
879
  @param result: dictionary of verification results; results of the
880
    verifications in this function will be added here
881
  @type all_hvparams: dict of dict of string
882
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
883

884
  """
885
  if constants.NV_HVINFO in what and vm_capable:
886
    hvname = what[constants.NV_HVINFO]
887
    hyper = hypervisor.GetHypervisor(hvname)
888
    hvparams = all_hvparams[hvname]
889
    result[constants.NV_HVINFO] = hyper.GetNodeInfo(hvparams=hvparams)
890

    
891

    
892
def VerifyNode(what, cluster_name, all_hvparams):
893
  """Verify the status of the local node.
894

895
  Based on the input L{what} parameter, various checks are done on the
896
  local node.
897

898
  If the I{filelist} key is present, this list of
899
  files is checksummed and the file/checksum pairs are returned.
900

901
  If the I{nodelist} key is present, we check that we have
902
  connectivity via ssh with the target nodes (and check the hostname
903
  report).
904

905
  If the I{node-net-test} key is present, we check that we have
906
  connectivity to the given nodes via both primary IP and, if
907
  applicable, secondary IPs.
908

909
  @type what: C{dict}
910
  @param what: a dictionary of things to check:
911
      - filelist: list of files for which to compute checksums
912
      - nodelist: list of nodes we should check ssh communication with
913
      - node-net-test: list of nodes we should check node daemon port
914
        connectivity with
915
      - hypervisor: list with hypervisors to run the verify for
916
  @type cluster_name: string
917
  @param cluster_name: the cluster's name
918
  @type all_hvparams: dict of dict of strings
919
  @param all_hvparams: a dictionary mapping hypervisor names to hvparams
920
  @rtype: dict
921
  @return: a dictionary with the same keys as the input dict, and
922
      values representing the result of the checks
923

924
  """
925
  result = {}
926
  my_name = netutils.Hostname.GetSysName()
927
  port = netutils.GetDaemonPort(constants.NODED)
928
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
929

    
930
  _VerifyHypervisors(what, vm_capable, result, all_hvparams)
931
  _VerifyHvparams(what, vm_capable, result)
932

    
933
  if constants.NV_FILELIST in what:
934
    fingerprints = utils.FingerprintFiles(map(vcluster.LocalizeVirtualPath,
935
                                              what[constants.NV_FILELIST]))
936
    result[constants.NV_FILELIST] = \
937
      dict((vcluster.MakeVirtualPath(key), value)
938
           for (key, value) in fingerprints.items())
939

    
940
  if constants.NV_NODELIST in what:
941
    (nodes, bynode) = what[constants.NV_NODELIST]
942

    
943
    # Add nodes from other groups (different for each node)
944
    try:
945
      nodes.extend(bynode[my_name])
946
    except KeyError:
947
      pass
948

    
949
    # Use a random order
950
    random.shuffle(nodes)
951

    
952
    # Try to contact all nodes
953
    val = {}
954
    for node in nodes:
955
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
956
      if not success:
957
        val[node] = message
958

    
959
    result[constants.NV_NODELIST] = val
960

    
961
  if constants.NV_NODENETTEST in what:
962
    result[constants.NV_NODENETTEST] = tmp = {}
963
    my_pip = my_sip = None
964
    for name, pip, sip in what[constants.NV_NODENETTEST]:
965
      if name == my_name:
966
        my_pip = pip
967
        my_sip = sip
968
        break
969
    if not my_pip:
970
      tmp[my_name] = ("Can't find my own primary/secondary IP"
971
                      " in the node list")
972
    else:
973
      for name, pip, sip in what[constants.NV_NODENETTEST]:
974
        fail = []
975
        if not netutils.TcpPing(pip, port, source=my_pip):
976
          fail.append("primary")
977
        if sip != pip:
978
          if not netutils.TcpPing(sip, port, source=my_sip):
979
            fail.append("secondary")
980
        if fail:
981
          tmp[name] = ("failure using the %s interface(s)" %
982
                       " and ".join(fail))
983

    
984
  if constants.NV_MASTERIP in what:
985
    # FIXME: add checks on incoming data structures (here and in the
986
    # rest of the function)
987
    master_name, master_ip = what[constants.NV_MASTERIP]
988
    if master_name == my_name:
989
      source = constants.IP4_ADDRESS_LOCALHOST
990
    else:
991
      source = None
992
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
993
                                                     source=source)
994

    
995
  if constants.NV_USERSCRIPTS in what:
996
    result[constants.NV_USERSCRIPTS] = \
997
      [script for script in what[constants.NV_USERSCRIPTS]
998
       if not utils.IsExecutable(script)]
999

    
1000
  if constants.NV_OOB_PATHS in what:
1001
    result[constants.NV_OOB_PATHS] = tmp = []
1002
    for path in what[constants.NV_OOB_PATHS]:
1003
      try:
1004
        st = os.stat(path)
1005
      except OSError, err:
1006
        tmp.append("error stating out of band helper: %s" % err)
1007
      else:
1008
        if stat.S_ISREG(st.st_mode):
1009
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
1010
            tmp.append(None)
1011
          else:
1012
            tmp.append("out of band helper %s is not executable" % path)
1013
        else:
1014
          tmp.append("out of band helper %s is not a file" % path)
1015

    
1016
  if constants.NV_LVLIST in what and vm_capable:
1017
    try:
1018
      val = GetVolumeList(utils.ListVolumeGroups().keys())
1019
    except RPCFail, err:
1020
      val = str(err)
1021
    result[constants.NV_LVLIST] = val
1022

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

    
1025
  if constants.NV_VGLIST in what and vm_capable:
1026
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
1027

    
1028
  if constants.NV_PVLIST in what and vm_capable:
1029
    check_exclusive_pvs = constants.NV_EXCLUSIVEPVS in what
1030
    val = bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
1031
                                       filter_allocatable=False,
1032
                                       include_lvs=check_exclusive_pvs)
1033
    if check_exclusive_pvs:
1034
      result[constants.NV_EXCLUSIVEPVS] = _CheckExclusivePvs(val)
1035
      for pvi in val:
1036
        # Avoid sending useless data on the wire
1037
        pvi.lv_list = []
1038
    result[constants.NV_PVLIST] = map(objects.LvmPvInfo.ToDict, val)
1039

    
1040
  if constants.NV_VERSION in what:
1041
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
1042
                                    constants.RELEASE_VERSION)
1043

    
1044
  _VerifyNodeInfo(what, vm_capable, result, all_hvparams)
1045

    
1046
  if constants.NV_DRBDVERSION in what and vm_capable:
1047
    try:
1048
      drbd_version = DRBD8.GetProcInfo().GetVersionString()
1049
    except errors.BlockDeviceError, err:
1050
      logging.warning("Can't get DRBD version", exc_info=True)
1051
      drbd_version = str(err)
1052
    result[constants.NV_DRBDVERSION] = drbd_version
1053

    
1054
  if constants.NV_DRBDLIST in what and vm_capable:
1055
    try:
1056
      used_minors = drbd.DRBD8.GetUsedDevs()
1057
    except errors.BlockDeviceError, err:
1058
      logging.warning("Can't get used minors list", exc_info=True)
1059
      used_minors = str(err)
1060
    result[constants.NV_DRBDLIST] = used_minors
1061

    
1062
  if constants.NV_DRBDHELPER in what and vm_capable:
1063
    status = True
1064
    try:
1065
      payload = drbd.DRBD8.GetUsermodeHelper()
1066
    except errors.BlockDeviceError, err:
1067
      logging.error("Can't get DRBD usermode helper: %s", str(err))
1068
      status = False
1069
      payload = str(err)
1070
    result[constants.NV_DRBDHELPER] = (status, payload)
1071

    
1072
  if constants.NV_NODESETUP in what:
1073
    result[constants.NV_NODESETUP] = tmpr = []
1074
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
1075
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
1076
                  " under /sys, missing required directories /sys/block"
1077
                  " and /sys/class/net")
1078
    if (not os.path.isdir("/proc/sys") or
1079
        not os.path.isfile("/proc/sysrq-trigger")):
1080
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
1081
                  " under /proc, missing required directory /proc/sys and"
1082
                  " the file /proc/sysrq-trigger")
1083

    
1084
  if constants.NV_TIME in what:
1085
    result[constants.NV_TIME] = utils.SplitTime(time.time())
1086

    
1087
  if constants.NV_OSLIST in what and vm_capable:
1088
    result[constants.NV_OSLIST] = DiagnoseOS()
1089

    
1090
  if constants.NV_BRIDGES in what and vm_capable:
1091
    result[constants.NV_BRIDGES] = [bridge
1092
                                    for bridge in what[constants.NV_BRIDGES]
1093
                                    if not utils.BridgeExists(bridge)]
1094

    
1095
  if what.get(constants.NV_FILE_STORAGE_PATHS) == my_name:
1096
    result[constants.NV_FILE_STORAGE_PATHS] = \
1097
      bdev.ComputeWrongFileStoragePaths()
1098

    
1099
  return result
1100

    
1101

    
1102
def GetBlockDevSizes(devices):
1103
  """Return the size of the given block devices
1104

1105
  @type devices: list
1106
  @param devices: list of block device nodes to query
1107
  @rtype: dict
1108
  @return:
1109
    dictionary of all block devices under /dev (key). The value is their
1110
    size in MiB.
1111

1112
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
1113

1114
  """
1115
  DEV_PREFIX = "/dev/"
1116
  blockdevs = {}
1117

    
1118
  for devpath in devices:
1119
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
1120
      continue
1121

    
1122
    try:
1123
      st = os.stat(devpath)
1124
    except EnvironmentError, err:
1125
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
1126
      continue
1127

    
1128
    if stat.S_ISBLK(st.st_mode):
1129
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
1130
      if result.failed:
1131
        # We don't want to fail, just do not list this device as available
1132
        logging.warning("Cannot get size for block device %s", devpath)
1133
        continue
1134

    
1135
      size = int(result.stdout) / (1024 * 1024)
1136
      blockdevs[devpath] = size
1137
  return blockdevs
1138

    
1139

    
1140
def GetVolumeList(vg_names):
1141
  """Compute list of logical volumes and their size.
1142

1143
  @type vg_names: list
1144
  @param vg_names: the volume groups whose LVs we should list, or
1145
      empty for all volume groups
1146
  @rtype: dict
1147
  @return:
1148
      dictionary of all partions (key) with value being a tuple of
1149
      their size (in MiB), inactive and online status::
1150

1151
        {'xenvg/test1': ('20.06', True, True)}
1152

1153
      in case of errors, a string is returned with the error
1154
      details.
1155

1156
  """
1157
  lvs = {}
1158
  sep = "|"
1159
  if not vg_names:
1160
    vg_names = []
1161
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1162
                         "--separator=%s" % sep,
1163
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
1164
  if result.failed:
1165
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
1166

    
1167
  for line in result.stdout.splitlines():
1168
    line = line.strip()
1169
    match = _LVSLINE_REGEX.match(line)
1170
    if not match:
1171
      logging.error("Invalid line returned from lvs output: '%s'", line)
1172
      continue
1173
    vg_name, name, size, attr = match.groups()
1174
    inactive = attr[4] == "-"
1175
    online = attr[5] == "o"
1176
    virtual = attr[0] == "v"
1177
    if virtual:
1178
      # we don't want to report such volumes as existing, since they
1179
      # don't really hold data
1180
      continue
1181
    lvs[vg_name + "/" + name] = (size, inactive, online)
1182

    
1183
  return lvs
1184

    
1185

    
1186
def ListVolumeGroups():
1187
  """List the volume groups and their size.
1188

1189
  @rtype: dict
1190
  @return: dictionary with keys volume name and values the
1191
      size of the volume
1192

1193
  """
1194
  return utils.ListVolumeGroups()
1195

    
1196

    
1197
def NodeVolumes():
1198
  """List all volumes on this node.
1199

1200
  @rtype: list
1201
  @return:
1202
    A list of dictionaries, each having four keys:
1203
      - name: the logical volume name,
1204
      - size: the size of the logical volume
1205
      - dev: the physical device on which the LV lives
1206
      - vg: the volume group to which it belongs
1207

1208
    In case of errors, we return an empty list and log the
1209
    error.
1210

1211
    Note that since a logical volume can live on multiple physical
1212
    volumes, the resulting list might include a logical volume
1213
    multiple times.
1214

1215
  """
1216
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1217
                         "--separator=|",
1218
                         "--options=lv_name,lv_size,devices,vg_name"])
1219
  if result.failed:
1220
    _Fail("Failed to list logical volumes, lvs output: %s",
1221
          result.output)
1222

    
1223
  def parse_dev(dev):
1224
    return dev.split("(")[0]
1225

    
1226
  def handle_dev(dev):
1227
    return [parse_dev(x) for x in dev.split(",")]
1228

    
1229
  def map_line(line):
1230
    line = [v.strip() for v in line]
1231
    return [{"name": line[0], "size": line[1],
1232
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
1233

    
1234
  all_devs = []
1235
  for line in result.stdout.splitlines():
1236
    if line.count("|") >= 3:
1237
      all_devs.extend(map_line(line.split("|")))
1238
    else:
1239
      logging.warning("Strange line in the output from lvs: '%s'", line)
1240
  return all_devs
1241

    
1242

    
1243
def BridgesExist(bridges_list):
1244
  """Check if a list of bridges exist on the current node.
1245

1246
  @rtype: boolean
1247
  @return: C{True} if all of them exist, C{False} otherwise
1248

1249
  """
1250
  missing = []
1251
  for bridge in bridges_list:
1252
    if not utils.BridgeExists(bridge):
1253
      missing.append(bridge)
1254

    
1255
  if missing:
1256
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
1257

    
1258

    
1259
def GetInstanceListForHypervisor(hname, hvparams=None,
1260
                                 get_hv_fn=hypervisor.GetHypervisor):
1261
  """Provides a list of instances of the given hypervisor.
1262

1263
  @type hname: string
1264
  @param hname: name of the hypervisor
1265
  @type hvparams: dict of strings
1266
  @param hvparams: hypervisor parameters for the given hypervisor
1267
  @type get_hv_fn: function
1268
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1269
    name; optional parameter to increase testability
1270

1271
  @rtype: list
1272
  @return: a list of all running instances on the current node
1273
    - instance1.example.com
1274
    - instance2.example.com
1275

1276
  """
1277
  results = []
1278
  try:
1279
    hv = get_hv_fn(hname)
1280
    names = hv.ListInstances(hvparams=hvparams)
1281
    results.extend(names)
1282
  except errors.HypervisorError, err:
1283
    _Fail("Error enumerating instances (hypervisor %s): %s",
1284
          hname, err, exc=True)
1285
  return results
1286

    
1287

    
1288
def GetInstanceList(hypervisor_list, all_hvparams=None,
1289
                    get_hv_fn=hypervisor.GetHypervisor):
1290
  """Provides a list of instances.
1291

1292
  @type hypervisor_list: list
1293
  @param hypervisor_list: the list of hypervisors to query information
1294
  @type all_hvparams: dict of dict of strings
1295
  @param all_hvparams: a dictionary mapping hypervisor types to respective
1296
    cluster-wide hypervisor parameters
1297
  @type get_hv_fn: function
1298
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1299
    name; optional parameter to increase testability
1300

1301
  @rtype: list
1302
  @return: a list of all running instances on the current node
1303
    - instance1.example.com
1304
    - instance2.example.com
1305

1306
  """
1307
  results = []
1308
  for hname in hypervisor_list:
1309
    hvparams = all_hvparams[hname]
1310
    results.extend(GetInstanceListForHypervisor(hname, hvparams=hvparams,
1311
                                                get_hv_fn=get_hv_fn))
1312
  return results
1313

    
1314

    
1315
def GetInstanceInfo(instance, hname, hvparams=None):
1316
  """Gives back the information about an instance as a dictionary.
1317

1318
  @type instance: string
1319
  @param instance: the instance name
1320
  @type hname: string
1321
  @param hname: the hypervisor type of the instance
1322
  @type hvparams: dict of strings
1323
  @param hvparams: the instance's hvparams
1324

1325
  @rtype: dict
1326
  @return: dictionary with the following keys:
1327
      - memory: memory size of instance (int)
1328
      - state: xen state of instance (string)
1329
      - time: cpu time of instance (float)
1330
      - vcpus: the number of vcpus (int)
1331

1332
  """
1333
  output = {}
1334

    
1335
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance,
1336
                                                          hvparams=hvparams)
1337
  if iinfo is not None:
1338
    output["memory"] = iinfo[2]
1339
    output["vcpus"] = iinfo[3]
1340
    output["state"] = iinfo[4]
1341
    output["time"] = iinfo[5]
1342

    
1343
  return output
1344

    
1345

    
1346
def GetInstanceMigratable(instance):
1347
  """Computes whether an instance can be migrated.
1348

1349
  @type instance: L{objects.Instance}
1350
  @param instance: object representing the instance to be checked.
1351

1352
  @rtype: tuple
1353
  @return: tuple of (result, description) where:
1354
      - result: whether the instance can be migrated or not
1355
      - description: a description of the issue, if relevant
1356

1357
  """
1358
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1359
  iname = instance.name
1360
  if iname not in hyper.ListInstances(instance.hvparams):
1361
    _Fail("Instance %s is not running", iname)
1362

    
1363
  for idx in range(len(instance.disks)):
1364
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1365
    if not os.path.islink(link_name):
1366
      logging.warning("Instance %s is missing symlink %s for disk %d",
1367
                      iname, link_name, idx)
1368

    
1369

    
1370
def GetAllInstancesInfo(hypervisor_list, all_hvparams):
1371
  """Gather data about all instances.
1372

1373
  This is the equivalent of L{GetInstanceInfo}, except that it
1374
  computes data for all instances at once, thus being faster if one
1375
  needs data about more than one instance.
1376

1377
  @type hypervisor_list: list
1378
  @param hypervisor_list: list of hypervisors to query for instance data
1379
  @type all_hvparams: dict of dict of strings
1380
  @param all_hvparams: mapping of hypervisor names to hvparams
1381

1382
  @rtype: dict
1383
  @return: dictionary of instance: data, with data having the following keys:
1384
      - memory: memory size of instance (int)
1385
      - state: xen state of instance (string)
1386
      - time: cpu time of instance (float)
1387
      - vcpus: the number of vcpus
1388

1389
  """
1390
  output = {}
1391

    
1392
  for hname in hypervisor_list:
1393
    hvparams = all_hvparams[hname]
1394
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo(hvparams)
1395
    if iinfo:
1396
      for name, _, memory, vcpus, state, times in iinfo:
1397
        value = {
1398
          "memory": memory,
1399
          "vcpus": vcpus,
1400
          "state": state,
1401
          "time": times,
1402
          }
1403
        if name in output:
1404
          # we only check static parameters, like memory and vcpus,
1405
          # and not state and time which can change between the
1406
          # invocations of the different hypervisors
1407
          for key in "memory", "vcpus":
1408
            if value[key] != output[name][key]:
1409
              _Fail("Instance %s is running twice"
1410
                    " with different parameters", name)
1411
        output[name] = value
1412

    
1413
  return output
1414

    
1415

    
1416
def _InstanceLogName(kind, os_name, instance, component):
1417
  """Compute the OS log filename for a given instance and operation.
1418

1419
  The instance name and os name are passed in as strings since not all
1420
  operations have these as part of an instance object.
1421

1422
  @type kind: string
1423
  @param kind: the operation type (e.g. add, import, etc.)
1424
  @type os_name: string
1425
  @param os_name: the os name
1426
  @type instance: string
1427
  @param instance: the name of the instance being imported/added/etc.
1428
  @type component: string or None
1429
  @param component: the name of the component of the instance being
1430
      transferred
1431

1432
  """
1433
  # TODO: Use tempfile.mkstemp to create unique filename
1434
  if component:
1435
    assert "/" not in component
1436
    c_msg = "-%s" % component
1437
  else:
1438
    c_msg = ""
1439
  base = ("%s-%s-%s%s-%s.log" %
1440
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1441
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1442

    
1443

    
1444
def InstanceOsAdd(instance, reinstall, debug):
1445
  """Add an OS to an instance.
1446

1447
  @type instance: L{objects.Instance}
1448
  @param instance: Instance whose OS is to be installed
1449
  @type reinstall: boolean
1450
  @param reinstall: whether this is an instance reinstall
1451
  @type debug: integer
1452
  @param debug: debug level, passed to the OS scripts
1453
  @rtype: None
1454

1455
  """
1456
  inst_os = OSFromDisk(instance.os)
1457

    
1458
  create_env = OSEnvironment(instance, inst_os, debug)
1459
  if reinstall:
1460
    create_env["INSTANCE_REINSTALL"] = "1"
1461

    
1462
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1463

    
1464
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1465
                        cwd=inst_os.path, output=logfile, reset_env=True)
1466
  if result.failed:
1467
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1468
                  " output: %s", result.cmd, result.fail_reason, logfile,
1469
                  result.output)
1470
    lines = [utils.SafeEncode(val)
1471
             for val in utils.TailFile(logfile, lines=20)]
1472
    _Fail("OS create script failed (%s), last lines in the"
1473
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1474

    
1475

    
1476
def RunRenameInstance(instance, old_name, debug):
1477
  """Run the OS rename script for an instance.
1478

1479
  @type instance: L{objects.Instance}
1480
  @param instance: Instance whose OS is to be installed
1481
  @type old_name: string
1482
  @param old_name: previous instance name
1483
  @type debug: integer
1484
  @param debug: debug level, passed to the OS scripts
1485
  @rtype: boolean
1486
  @return: the success of the operation
1487

1488
  """
1489
  inst_os = OSFromDisk(instance.os)
1490

    
1491
  rename_env = OSEnvironment(instance, inst_os, debug)
1492
  rename_env["OLD_INSTANCE_NAME"] = old_name
1493

    
1494
  logfile = _InstanceLogName("rename", instance.os,
1495
                             "%s-%s" % (old_name, instance.name), None)
1496

    
1497
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1498
                        cwd=inst_os.path, output=logfile, reset_env=True)
1499

    
1500
  if result.failed:
1501
    logging.error("os create command '%s' returned error: %s output: %s",
1502
                  result.cmd, result.fail_reason, result.output)
1503
    lines = [utils.SafeEncode(val)
1504
             for val in utils.TailFile(logfile, lines=20)]
1505
    _Fail("OS rename script failed (%s), last lines in the"
1506
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1507

    
1508

    
1509
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1510
  """Returns symlink path for block device.
1511

1512
  """
1513
  if _dir is None:
1514
    _dir = pathutils.DISK_LINKS_DIR
1515

    
1516
  return utils.PathJoin(_dir,
1517
                        ("%s%s%s" %
1518
                         (instance_name, constants.DISK_SEPARATOR, idx)))
1519

    
1520

    
1521
def _SymlinkBlockDev(instance_name, device_path, idx):
1522
  """Set up symlinks to a instance's block device.
1523

1524
  This is an auxiliary function run when an instance is start (on the primary
1525
  node) or when an instance is migrated (on the target node).
1526

1527

1528
  @param instance_name: the name of the target instance
1529
  @param device_path: path of the physical block device, on the node
1530
  @param idx: the disk index
1531
  @return: absolute path to the disk's symlink
1532

1533
  """
1534
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1535
  try:
1536
    os.symlink(device_path, link_name)
1537
  except OSError, err:
1538
    if err.errno == errno.EEXIST:
1539
      if (not os.path.islink(link_name) or
1540
          os.readlink(link_name) != device_path):
1541
        os.remove(link_name)
1542
        os.symlink(device_path, link_name)
1543
    else:
1544
      raise
1545

    
1546
  return link_name
1547

    
1548

    
1549
def _RemoveBlockDevLinks(instance_name, disks):
1550
  """Remove the block device symlinks belonging to the given instance.
1551

1552
  """
1553
  for idx, _ in enumerate(disks):
1554
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1555
    if os.path.islink(link_name):
1556
      try:
1557
        os.remove(link_name)
1558
      except OSError:
1559
        logging.exception("Can't remove symlink '%s'", link_name)
1560

    
1561

    
1562
def _GatherAndLinkBlockDevs(instance):
1563
  """Set up an instance's block device(s).
1564

1565
  This is run on the primary node at instance startup. The block
1566
  devices must be already assembled.
1567

1568
  @type instance: L{objects.Instance}
1569
  @param instance: the instance whose disks we shoul assemble
1570
  @rtype: list
1571
  @return: list of (disk_object, device_path)
1572

1573
  """
1574
  block_devices = []
1575
  for idx, disk in enumerate(instance.disks):
1576
    device = _RecursiveFindBD(disk)
1577
    if device is None:
1578
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1579
                                    str(disk))
1580
    device.Open()
1581
    try:
1582
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1583
    except OSError, e:
1584
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1585
                                    e.strerror)
1586

    
1587
    block_devices.append((disk, link_name))
1588

    
1589
  return block_devices
1590

    
1591

    
1592
def StartInstance(instance, startup_paused, reason, store_reason=True):
1593
  """Start an instance.
1594

1595
  @type instance: L{objects.Instance}
1596
  @param instance: the instance object
1597
  @type startup_paused: bool
1598
  @param instance: pause instance at startup?
1599
  @type reason: list of reasons
1600
  @param reason: the reason trail for this startup
1601
  @type store_reason: boolean
1602
  @param store_reason: whether to store the shutdown reason trail on file
1603
  @rtype: None
1604

1605
  """
1606
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1607
                                                   instance.hvparams)
1608

    
1609
  if instance.name in running_instances:
1610
    logging.info("Instance %s already running, not starting", instance.name)
1611
    return
1612

    
1613
  try:
1614
    block_devices = _GatherAndLinkBlockDevs(instance)
1615
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1616
    hyper.StartInstance(instance, block_devices, startup_paused)
1617
    if store_reason:
1618
      _StoreInstReasonTrail(instance.name, reason)
1619
  except errors.BlockDeviceError, err:
1620
    _Fail("Block device error: %s", err, exc=True)
1621
  except errors.HypervisorError, err:
1622
    _RemoveBlockDevLinks(instance.name, instance.disks)
1623
    _Fail("Hypervisor error: %s", err, exc=True)
1624

    
1625

    
1626
def InstanceShutdown(instance, timeout, reason, store_reason=True):
1627
  """Shut an instance down.
1628

1629
  @note: this functions uses polling with a hardcoded timeout.
1630

1631
  @type instance: L{objects.Instance}
1632
  @param instance: the instance object
1633
  @type timeout: integer
1634
  @param timeout: maximum timeout for soft shutdown
1635
  @type reason: list of reasons
1636
  @param reason: the reason trail for this shutdown
1637
  @type store_reason: boolean
1638
  @param store_reason: whether to store the shutdown reason trail on file
1639
  @rtype: None
1640

1641
  """
1642
  hv_name = instance.hypervisor
1643
  hyper = hypervisor.GetHypervisor(hv_name)
1644
  iname = instance.name
1645

    
1646
  if instance.name not in hyper.ListInstances(instance.hvparams):
1647
    logging.info("Instance %s not running, doing nothing", iname)
1648
    return
1649

    
1650
  class _TryShutdown:
1651
    def __init__(self):
1652
      self.tried_once = False
1653

    
1654
    def __call__(self):
1655
      if iname not in hyper.ListInstances(instance.hvparams):
1656
        return
1657

    
1658
      try:
1659
        hyper.StopInstance(instance, retry=self.tried_once)
1660
        if store_reason:
1661
          _StoreInstReasonTrail(instance.name, reason)
1662
      except errors.HypervisorError, err:
1663
        if iname not in hyper.ListInstances(instance.hvparams):
1664
          # if the instance is no longer existing, consider this a
1665
          # success and go to cleanup
1666
          return
1667

    
1668
        _Fail("Failed to stop instance %s: %s", iname, err)
1669

    
1670
      self.tried_once = True
1671

    
1672
      raise utils.RetryAgain()
1673

    
1674
  try:
1675
    utils.Retry(_TryShutdown(), 5, timeout)
1676
  except utils.RetryTimeout:
1677
    # the shutdown did not succeed
1678
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1679

    
1680
    try:
1681
      hyper.StopInstance(instance, force=True)
1682
    except errors.HypervisorError, err:
1683
      if iname in hyper.ListInstances(instance.hvparams):
1684
        # only raise an error if the instance still exists, otherwise
1685
        # the error could simply be "instance ... unknown"!
1686
        _Fail("Failed to force stop instance %s: %s", iname, err)
1687

    
1688
    time.sleep(1)
1689

    
1690
    if iname in hyper.ListInstances(instance.hvparams):
1691
      _Fail("Could not shutdown instance %s even by destroy", iname)
1692

    
1693
  try:
1694
    hyper.CleanupInstance(instance.name)
1695
  except errors.HypervisorError, err:
1696
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1697

    
1698
  _RemoveBlockDevLinks(iname, instance.disks)
1699

    
1700

    
1701
def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1702
  """Reboot an instance.
1703

1704
  @type instance: L{objects.Instance}
1705
  @param instance: the instance object to reboot
1706
  @type reboot_type: str
1707
  @param reboot_type: the type of reboot, one the following
1708
    constants:
1709
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1710
        instance OS, do not recreate the VM
1711
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1712
        restart the VM (at the hypervisor level)
1713
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1714
        not accepted here, since that mode is handled differently, in
1715
        cmdlib, and translates into full stop and start of the
1716
        instance (instead of a call_instance_reboot RPC)
1717
  @type shutdown_timeout: integer
1718
  @param shutdown_timeout: maximum timeout for soft shutdown
1719
  @type reason: list of reasons
1720
  @param reason: the reason trail for this reboot
1721
  @rtype: None
1722

1723
  """
1724
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1725
                                                   instance.hvparams)
1726

    
1727
  if instance.name not in running_instances:
1728
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1729

    
1730
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1731
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1732
    try:
1733
      hyper.RebootInstance(instance)
1734
    except errors.HypervisorError, err:
1735
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1736
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1737
    try:
1738
      InstanceShutdown(instance, shutdown_timeout, reason, store_reason=False)
1739
      result = StartInstance(instance, False, reason, store_reason=False)
1740
      _StoreInstReasonTrail(instance.name, reason)
1741
      return result
1742
    except errors.HypervisorError, err:
1743
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1744
  else:
1745
    _Fail("Invalid reboot_type received: %s", reboot_type)
1746

    
1747

    
1748
def InstanceBalloonMemory(instance, memory):
1749
  """Resize an instance's memory.
1750

1751
  @type instance: L{objects.Instance}
1752
  @param instance: the instance object
1753
  @type memory: int
1754
  @param memory: new memory amount in MB
1755
  @rtype: None
1756

1757
  """
1758
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1759
  running = hyper.ListInstances(instance.hvparams)
1760
  if instance.name not in running:
1761
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1762
    return
1763
  try:
1764
    hyper.BalloonInstanceMemory(instance, memory)
1765
  except errors.HypervisorError, err:
1766
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1767

    
1768

    
1769
def MigrationInfo(instance):
1770
  """Gather information about an instance to be migrated.
1771

1772
  @type instance: L{objects.Instance}
1773
  @param instance: the instance definition
1774

1775
  """
1776
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1777
  try:
1778
    info = hyper.MigrationInfo(instance)
1779
  except errors.HypervisorError, err:
1780
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1781
  return info
1782

    
1783

    
1784
def AcceptInstance(instance, info, target):
1785
  """Prepare the node to accept an instance.
1786

1787
  @type instance: L{objects.Instance}
1788
  @param instance: the instance definition
1789
  @type info: string/data (opaque)
1790
  @param info: migration information, from the source node
1791
  @type target: string
1792
  @param target: target host (usually ip), on this node
1793

1794
  """
1795
  # TODO: why is this required only for DTS_EXT_MIRROR?
1796
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1797
    # Create the symlinks, as the disks are not active
1798
    # in any way
1799
    try:
1800
      _GatherAndLinkBlockDevs(instance)
1801
    except errors.BlockDeviceError, err:
1802
      _Fail("Block device error: %s", err, exc=True)
1803

    
1804
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1805
  try:
1806
    hyper.AcceptInstance(instance, info, target)
1807
  except errors.HypervisorError, err:
1808
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1809
      _RemoveBlockDevLinks(instance.name, instance.disks)
1810
    _Fail("Failed to accept instance: %s", err, exc=True)
1811

    
1812

    
1813
def FinalizeMigrationDst(instance, info, success):
1814
  """Finalize any preparation to accept an instance.
1815

1816
  @type instance: L{objects.Instance}
1817
  @param instance: the instance definition
1818
  @type info: string/data (opaque)
1819
  @param info: migration information, from the source node
1820
  @type success: boolean
1821
  @param success: whether the migration was a success or a failure
1822

1823
  """
1824
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1825
  try:
1826
    hyper.FinalizeMigrationDst(instance, info, success)
1827
  except errors.HypervisorError, err:
1828
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1829

    
1830

    
1831
def MigrateInstance(cluster_name, instance, target, live):
1832
  """Migrates an instance to another node.
1833

1834
  @type cluster_name: string
1835
  @param cluster_name: name of the cluster
1836
  @type instance: L{objects.Instance}
1837
  @param instance: the instance definition
1838
  @type target: string
1839
  @param target: the target node name
1840
  @type live: boolean
1841
  @param live: whether the migration should be done live or not (the
1842
      interpretation of this parameter is left to the hypervisor)
1843
  @raise RPCFail: if migration fails for some reason
1844

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

    
1848
  try:
1849
    hyper.MigrateInstance(cluster_name, instance, target, live)
1850
  except errors.HypervisorError, err:
1851
    _Fail("Failed to migrate instance: %s", err, exc=True)
1852

    
1853

    
1854
def FinalizeMigrationSource(instance, success, live):
1855
  """Finalize the instance migration on the source node.
1856

1857
  @type instance: L{objects.Instance}
1858
  @param instance: the instance definition of the migrated instance
1859
  @type success: bool
1860
  @param success: whether the migration succeeded or not
1861
  @type live: bool
1862
  @param live: whether the user requested a live migration or not
1863
  @raise RPCFail: If the execution fails for some reason
1864

1865
  """
1866
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1867

    
1868
  try:
1869
    hyper.FinalizeMigrationSource(instance, success, live)
1870
  except Exception, err:  # pylint: disable=W0703
1871
    _Fail("Failed to finalize the migration on the source node: %s", err,
1872
          exc=True)
1873

    
1874

    
1875
def GetMigrationStatus(instance):
1876
  """Get the migration status
1877

1878
  @type instance: L{objects.Instance}
1879
  @param instance: the instance that is being migrated
1880
  @rtype: L{objects.MigrationStatus}
1881
  @return: the status of the current migration (one of
1882
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1883
           progress info that can be retrieved from the hypervisor
1884
  @raise RPCFail: If the migration status cannot be retrieved
1885

1886
  """
1887
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1888
  try:
1889
    return hyper.GetMigrationStatus(instance)
1890
  except Exception, err:  # pylint: disable=W0703
1891
    _Fail("Failed to get migration status: %s", err, exc=True)
1892

    
1893

    
1894
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
1895
  """Creates a block device for an instance.
1896

1897
  @type disk: L{objects.Disk}
1898
  @param disk: the object describing the disk we should create
1899
  @type size: int
1900
  @param size: the size of the physical underlying device, in MiB
1901
  @type owner: str
1902
  @param owner: the name of the instance for which disk is created,
1903
      used for device cache data
1904
  @type on_primary: boolean
1905
  @param on_primary:  indicates if it is the primary node or not
1906
  @type info: string
1907
  @param info: string that will be sent to the physical device
1908
      creation, used for example to set (LVM) tags on LVs
1909
  @type excl_stor: boolean
1910
  @param excl_stor: Whether exclusive_storage is active
1911

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

1916
  """
1917
  # TODO: remove the obsolete "size" argument
1918
  # pylint: disable=W0613
1919
  clist = []
1920
  if disk.children:
1921
    for child in disk.children:
1922
      try:
1923
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1924
      except errors.BlockDeviceError, err:
1925
        _Fail("Can't assemble device %s: %s", child, err)
1926
      if on_primary or disk.AssembleOnSecondary():
1927
        # we need the children open in case the device itself has to
1928
        # be assembled
1929
        try:
1930
          # pylint: disable=E1103
1931
          crdev.Open()
1932
        except errors.BlockDeviceError, err:
1933
          _Fail("Can't make child '%s' read-write: %s", child, err)
1934
      clist.append(crdev)
1935

    
1936
  try:
1937
    device = bdev.Create(disk, clist, excl_stor)
1938
  except errors.BlockDeviceError, err:
1939
    _Fail("Can't create block device: %s", err)
1940

    
1941
  if on_primary or disk.AssembleOnSecondary():
1942
    try:
1943
      device.Assemble()
1944
    except errors.BlockDeviceError, err:
1945
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1946
    if on_primary or disk.OpenOnSecondary():
1947
      try:
1948
        device.Open(force=True)
1949
      except errors.BlockDeviceError, err:
1950
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1951
    DevCacheManager.UpdateCache(device.dev_path, owner,
1952
                                on_primary, disk.iv_name)
1953

    
1954
  device.SetInfo(info)
1955

    
1956
  return device.unique_id
1957

    
1958

    
1959
def _WipeDevice(path, offset, size):
1960
  """This function actually wipes the device.
1961

1962
  @param path: The path to the device to wipe
1963
  @param offset: The offset in MiB in the file
1964
  @param size: The size in MiB to write
1965

1966
  """
1967
  # Internal sizes are always in Mebibytes; if the following "dd" command
1968
  # should use a different block size the offset and size given to this
1969
  # function must be adjusted accordingly before being passed to "dd".
1970
  block_size = 1024 * 1024
1971

    
1972
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1973
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
1974
         "count=%d" % size]
1975
  result = utils.RunCmd(cmd)
1976

    
1977
  if result.failed:
1978
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1979
          result.fail_reason, result.output)
1980

    
1981

    
1982
def BlockdevWipe(disk, offset, size):
1983
  """Wipes a block device.
1984

1985
  @type disk: L{objects.Disk}
1986
  @param disk: the disk object we want to wipe
1987
  @type offset: int
1988
  @param offset: The offset in MiB in the file
1989
  @type size: int
1990
  @param size: The size in MiB to write
1991

1992
  """
1993
  try:
1994
    rdev = _RecursiveFindBD(disk)
1995
  except errors.BlockDeviceError:
1996
    rdev = None
1997

    
1998
  if not rdev:
1999
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
2000

    
2001
  # Do cross verify some of the parameters
2002
  if offset < 0:
2003
    _Fail("Negative offset")
2004
  if size < 0:
2005
    _Fail("Negative size")
2006
  if offset > rdev.size:
2007
    _Fail("Offset is bigger than device size")
2008
  if (offset + size) > rdev.size:
2009
    _Fail("The provided offset and size to wipe is bigger than device size")
2010

    
2011
  _WipeDevice(rdev.dev_path, offset, size)
2012

    
2013

    
2014
def BlockdevPauseResumeSync(disks, pause):
2015
  """Pause or resume the sync of the block device.
2016

2017
  @type disks: list of L{objects.Disk}
2018
  @param disks: the disks object we want to pause/resume
2019
  @type pause: bool
2020
  @param pause: Wheater to pause or resume
2021

2022
  """
2023
  success = []
2024
  for disk in disks:
2025
    try:
2026
      rdev = _RecursiveFindBD(disk)
2027
    except errors.BlockDeviceError:
2028
      rdev = None
2029

    
2030
    if not rdev:
2031
      success.append((False, ("Cannot change sync for device %s:"
2032
                              " device not found" % disk.iv_name)))
2033
      continue
2034

    
2035
    result = rdev.PauseResumeSync(pause)
2036

    
2037
    if result:
2038
      success.append((result, None))
2039
    else:
2040
      if pause:
2041
        msg = "Pause"
2042
      else:
2043
        msg = "Resume"
2044
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
2045

    
2046
  return success
2047

    
2048

    
2049
def BlockdevRemove(disk):
2050
  """Remove a block device.
2051

2052
  @note: This is intended to be called recursively.
2053

2054
  @type disk: L{objects.Disk}
2055
  @param disk: the disk object we should remove
2056
  @rtype: boolean
2057
  @return: the success of the operation
2058

2059
  """
2060
  msgs = []
2061
  try:
2062
    rdev = _RecursiveFindBD(disk)
2063
  except errors.BlockDeviceError, err:
2064
    # probably can't attach
2065
    logging.info("Can't attach to device %s in remove", disk)
2066
    rdev = None
2067
  if rdev is not None:
2068
    r_path = rdev.dev_path
2069
    try:
2070
      rdev.Remove()
2071
    except errors.BlockDeviceError, err:
2072
      msgs.append(str(err))
2073
    if not msgs:
2074
      DevCacheManager.RemoveCache(r_path)
2075

    
2076
  if disk.children:
2077
    for child in disk.children:
2078
      try:
2079
        BlockdevRemove(child)
2080
      except RPCFail, err:
2081
        msgs.append(str(err))
2082

    
2083
  if msgs:
2084
    _Fail("; ".join(msgs))
2085

    
2086

    
2087
def _RecursiveAssembleBD(disk, owner, as_primary):
2088
  """Activate a block device for an instance.
2089

2090
  This is run on the primary and secondary nodes for an instance.
2091

2092
  @note: this function is called recursively.
2093

2094
  @type disk: L{objects.Disk}
2095
  @param disk: the disk we try to assemble
2096
  @type owner: str
2097
  @param owner: the name of the instance which owns the disk
2098
  @type as_primary: boolean
2099
  @param as_primary: if we should make the block device
2100
      read/write
2101

2102
  @return: the assembled device or None (in case no device
2103
      was assembled)
2104
  @raise errors.BlockDeviceError: in case there is an error
2105
      during the activation of the children or the device
2106
      itself
2107

2108
  """
2109
  children = []
2110
  if disk.children:
2111
    mcn = disk.ChildrenNeeded()
2112
    if mcn == -1:
2113
      mcn = 0 # max number of Nones allowed
2114
    else:
2115
      mcn = len(disk.children) - mcn # max number of Nones
2116
    for chld_disk in disk.children:
2117
      try:
2118
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
2119
      except errors.BlockDeviceError, err:
2120
        if children.count(None) >= mcn:
2121
          raise
2122
        cdev = None
2123
        logging.error("Error in child activation (but continuing): %s",
2124
                      str(err))
2125
      children.append(cdev)
2126

    
2127
  if as_primary or disk.AssembleOnSecondary():
2128
    r_dev = bdev.Assemble(disk, children)
2129
    result = r_dev
2130
    if as_primary or disk.OpenOnSecondary():
2131
      r_dev.Open()
2132
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
2133
                                as_primary, disk.iv_name)
2134

    
2135
  else:
2136
    result = True
2137
  return result
2138

    
2139

    
2140
def BlockdevAssemble(disk, owner, as_primary, idx):
2141
  """Activate a block device for an instance.
2142

2143
  This is a wrapper over _RecursiveAssembleBD.
2144

2145
  @rtype: str or boolean
2146
  @return: a C{/dev/...} path for primary nodes, and
2147
      C{True} for secondary nodes
2148

2149
  """
2150
  try:
2151
    result = _RecursiveAssembleBD(disk, owner, as_primary)
2152
    if isinstance(result, BlockDev):
2153
      # pylint: disable=E1103
2154
      result = result.dev_path
2155
      if as_primary:
2156
        _SymlinkBlockDev(owner, result, idx)
2157
  except errors.BlockDeviceError, err:
2158
    _Fail("Error while assembling disk: %s", err, exc=True)
2159
  except OSError, err:
2160
    _Fail("Error while symlinking disk: %s", err, exc=True)
2161

    
2162
  return result
2163

    
2164

    
2165
def BlockdevShutdown(disk):
2166
  """Shut down a block device.
2167

2168
  First, if the device is assembled (Attach() is successful), then
2169
  the device is shutdown. Then the children of the device are
2170
  shutdown.
2171

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

2176
  @type disk: L{objects.Disk}
2177
  @param disk: the description of the disk we should
2178
      shutdown
2179
  @rtype: None
2180

2181
  """
2182
  msgs = []
2183
  r_dev = _RecursiveFindBD(disk)
2184
  if r_dev is not None:
2185
    r_path = r_dev.dev_path
2186
    try:
2187
      r_dev.Shutdown()
2188
      DevCacheManager.RemoveCache(r_path)
2189
    except errors.BlockDeviceError, err:
2190
      msgs.append(str(err))
2191

    
2192
  if disk.children:
2193
    for child in disk.children:
2194
      try:
2195
        BlockdevShutdown(child)
2196
      except RPCFail, err:
2197
        msgs.append(str(err))
2198

    
2199
  if msgs:
2200
    _Fail("; ".join(msgs))
2201

    
2202

    
2203
def BlockdevAddchildren(parent_cdev, new_cdevs):
2204
  """Extend a mirrored block device.
2205

2206
  @type parent_cdev: L{objects.Disk}
2207
  @param parent_cdev: the disk to which we should add children
2208
  @type new_cdevs: list of L{objects.Disk}
2209
  @param new_cdevs: the list of children which we should add
2210
  @rtype: None
2211

2212
  """
2213
  parent_bdev = _RecursiveFindBD(parent_cdev)
2214
  if parent_bdev is None:
2215
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
2216
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
2217
  if new_bdevs.count(None) > 0:
2218
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
2219
  parent_bdev.AddChildren(new_bdevs)
2220

    
2221

    
2222
def BlockdevRemovechildren(parent_cdev, new_cdevs):
2223
  """Shrink a mirrored block device.
2224

2225
  @type parent_cdev: L{objects.Disk}
2226
  @param parent_cdev: the disk from which we should remove children
2227
  @type new_cdevs: list of L{objects.Disk}
2228
  @param new_cdevs: the list of children which we should remove
2229
  @rtype: None
2230

2231
  """
2232
  parent_bdev = _RecursiveFindBD(parent_cdev)
2233
  if parent_bdev is None:
2234
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
2235
  devs = []
2236
  for disk in new_cdevs:
2237
    rpath = disk.StaticDevPath()
2238
    if rpath is None:
2239
      bd = _RecursiveFindBD(disk)
2240
      if bd is None:
2241
        _Fail("Can't find device %s while removing children", disk)
2242
      else:
2243
        devs.append(bd.dev_path)
2244
    else:
2245
      if not utils.IsNormAbsPath(rpath):
2246
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
2247
      devs.append(rpath)
2248
  parent_bdev.RemoveChildren(devs)
2249

    
2250

    
2251
def BlockdevGetmirrorstatus(disks):
2252
  """Get the mirroring status of a list of devices.
2253

2254
  @type disks: list of L{objects.Disk}
2255
  @param disks: the list of disks which we should query
2256
  @rtype: disk
2257
  @return: List of L{objects.BlockDevStatus}, one for each disk
2258
  @raise errors.BlockDeviceError: if any of the disks cannot be
2259
      found
2260

2261
  """
2262
  stats = []
2263
  for dsk in disks:
2264
    rbd = _RecursiveFindBD(dsk)
2265
    if rbd is None:
2266
      _Fail("Can't find device %s", dsk)
2267

    
2268
    stats.append(rbd.CombinedSyncStatus())
2269

    
2270
  return stats
2271

    
2272

    
2273
def BlockdevGetmirrorstatusMulti(disks):
2274
  """Get the mirroring status of a list of devices.
2275

2276
  @type disks: list of L{objects.Disk}
2277
  @param disks: the list of disks which we should query
2278
  @rtype: disk
2279
  @return: List of tuples, (bool, status), one for each disk; bool denotes
2280
    success/failure, status is L{objects.BlockDevStatus} on success, string
2281
    otherwise
2282

2283
  """
2284
  result = []
2285
  for disk in disks:
2286
    try:
2287
      rbd = _RecursiveFindBD(disk)
2288
      if rbd is None:
2289
        result.append((False, "Can't find device %s" % disk))
2290
        continue
2291

    
2292
      status = rbd.CombinedSyncStatus()
2293
    except errors.BlockDeviceError, err:
2294
      logging.exception("Error while getting disk status")
2295
      result.append((False, str(err)))
2296
    else:
2297
      result.append((True, status))
2298

    
2299
  assert len(disks) == len(result)
2300

    
2301
  return result
2302

    
2303

    
2304
def _RecursiveFindBD(disk):
2305
  """Check if a device is activated.
2306

2307
  If so, return information about the real device.
2308

2309
  @type disk: L{objects.Disk}
2310
  @param disk: the disk object we need to find
2311

2312
  @return: None if the device can't be found,
2313
      otherwise the device instance
2314

2315
  """
2316
  children = []
2317
  if disk.children:
2318
    for chdisk in disk.children:
2319
      children.append(_RecursiveFindBD(chdisk))
2320

    
2321
  return bdev.FindDevice(disk, children)
2322

    
2323

    
2324
def _OpenRealBD(disk):
2325
  """Opens the underlying block device of a disk.
2326

2327
  @type disk: L{objects.Disk}
2328
  @param disk: the disk object we want to open
2329

2330
  """
2331
  real_disk = _RecursiveFindBD(disk)
2332
  if real_disk is None:
2333
    _Fail("Block device '%s' is not set up", disk)
2334

    
2335
  real_disk.Open()
2336

    
2337
  return real_disk
2338

    
2339

    
2340
def BlockdevFind(disk):
2341
  """Check if a device is activated.
2342

2343
  If it is, return information about the real device.
2344

2345
  @type disk: L{objects.Disk}
2346
  @param disk: the disk to find
2347
  @rtype: None or objects.BlockDevStatus
2348
  @return: None if the disk cannot be found, otherwise a the current
2349
           information
2350

2351
  """
2352
  try:
2353
    rbd = _RecursiveFindBD(disk)
2354
  except errors.BlockDeviceError, err:
2355
    _Fail("Failed to find device: %s", err, exc=True)
2356

    
2357
  if rbd is None:
2358
    return None
2359

    
2360
  return rbd.GetSyncStatus()
2361

    
2362

    
2363
def BlockdevGetdimensions(disks):
2364
  """Computes the size of the given disks.
2365

2366
  If a disk is not found, returns None instead.
2367

2368
  @type disks: list of L{objects.Disk}
2369
  @param disks: the list of disk to compute the size for
2370
  @rtype: list
2371
  @return: list with elements None if the disk cannot be found,
2372
      otherwise the pair (size, spindles), where spindles is None if the
2373
      device doesn't support that
2374

2375
  """
2376
  result = []
2377
  for cf in disks:
2378
    try:
2379
      rbd = _RecursiveFindBD(cf)
2380
    except errors.BlockDeviceError:
2381
      result.append(None)
2382
      continue
2383
    if rbd is None:
2384
      result.append(None)
2385
    else:
2386
      result.append(rbd.GetActualDimensions())
2387
  return result
2388

    
2389

    
2390
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2391
  """Export a block device to a remote node.
2392

2393
  @type disk: L{objects.Disk}
2394
  @param disk: the description of the disk to export
2395
  @type dest_node: str
2396
  @param dest_node: the destination node to export to
2397
  @type dest_path: str
2398
  @param dest_path: the destination path on the target node
2399
  @type cluster_name: str
2400
  @param cluster_name: the cluster name, needed for SSH hostalias
2401
  @rtype: None
2402

2403
  """
2404
  real_disk = _OpenRealBD(disk)
2405

    
2406
  # the block size on the read dd is 1MiB to match our units
2407
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2408
                               "dd if=%s bs=1048576 count=%s",
2409
                               real_disk.dev_path, str(disk.size))
2410

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

    
2420
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2421
                                                   constants.SSH_LOGIN_USER,
2422
                                                   destcmd)
2423

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

    
2427
  result = utils.RunCmd(["bash", "-c", command])
2428

    
2429
  if result.failed:
2430
    _Fail("Disk copy command '%s' returned error: %s"
2431
          " output: %s", command, result.fail_reason, result.output)
2432

    
2433

    
2434
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2435
  """Write a file to the filesystem.
2436

2437
  This allows the master to overwrite(!) a file. It will only perform
2438
  the operation if the file belongs to a list of configuration files.
2439

2440
  @type file_name: str
2441
  @param file_name: the target file name
2442
  @type data: str
2443
  @param data: the new contents of the file
2444
  @type mode: int
2445
  @param mode: the mode to give the file (can be None)
2446
  @type uid: string
2447
  @param uid: the owner of the file
2448
  @type gid: string
2449
  @param gid: the group of the file
2450
  @type atime: float
2451
  @param atime: the atime to set on the file (can be None)
2452
  @type mtime: float
2453
  @param mtime: the mtime to set on the file (can be None)
2454
  @rtype: None
2455

2456
  """
2457
  file_name = vcluster.LocalizeVirtualPath(file_name)
2458

    
2459
  if not os.path.isabs(file_name):
2460
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2461

    
2462
  if file_name not in _ALLOWED_UPLOAD_FILES:
2463
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2464
          file_name)
2465

    
2466
  raw_data = _Decompress(data)
2467

    
2468
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2469
    _Fail("Invalid username/groupname type")
2470

    
2471
  getents = runtime.GetEnts()
2472
  uid = getents.LookupUser(uid)
2473
  gid = getents.LookupGroup(gid)
2474

    
2475
  utils.SafeWriteFile(file_name, None,
2476
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2477
                      atime=atime, mtime=mtime)
2478

    
2479

    
2480
def RunOob(oob_program, command, node, timeout):
2481
  """Executes oob_program with given command on given node.
2482

2483
  @param oob_program: The path to the executable oob_program
2484
  @param command: The command to invoke on oob_program
2485
  @param node: The node given as an argument to the program
2486
  @param timeout: Timeout after which we kill the oob program
2487

2488
  @return: stdout
2489
  @raise RPCFail: If execution fails for some reason
2490

2491
  """
2492
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2493

    
2494
  if result.failed:
2495
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2496
          result.fail_reason, result.output)
2497

    
2498
  return result.stdout
2499

    
2500

    
2501
def _OSOndiskAPIVersion(os_dir):
2502
  """Compute and return the API version of a given OS.
2503

2504
  This function will try to read the API version of the OS residing in
2505
  the 'os_dir' directory.
2506

2507
  @type os_dir: str
2508
  @param os_dir: the directory in which we should look for the OS
2509
  @rtype: tuple
2510
  @return: tuple (status, data) with status denoting the validity and
2511
      data holding either the vaid versions or an error message
2512

2513
  """
2514
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2515

    
2516
  try:
2517
    st = os.stat(api_file)
2518
  except EnvironmentError, err:
2519
    return False, ("Required file '%s' not found under path %s: %s" %
2520
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2521

    
2522
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2523
    return False, ("File '%s' in %s is not a regular file" %
2524
                   (constants.OS_API_FILE, os_dir))
2525

    
2526
  try:
2527
    api_versions = utils.ReadFile(api_file).splitlines()
2528
  except EnvironmentError, err:
2529
    return False, ("Error while reading the API version file at %s: %s" %
2530
                   (api_file, utils.ErrnoOrStr(err)))
2531

    
2532
  try:
2533
    api_versions = [int(version.strip()) for version in api_versions]
2534
  except (TypeError, ValueError), err:
2535
    return False, ("API version(s) can't be converted to integer: %s" %
2536
                   str(err))
2537

    
2538
  return True, api_versions
2539

    
2540

    
2541
def DiagnoseOS(top_dirs=None):
2542
  """Compute the validity for all OSes.
2543

2544
  @type top_dirs: list
2545
  @param top_dirs: the list of directories in which to
2546
      search (if not given defaults to
2547
      L{pathutils.OS_SEARCH_PATH})
2548
  @rtype: list of L{objects.OS}
2549
  @return: a list of tuples (name, path, status, diagnose, variants,
2550
      parameters, api_version) for all (potential) OSes under all
2551
      search paths, where:
2552
          - name is the (potential) OS name
2553
          - path is the full path to the OS
2554
          - status True/False is the validity of the OS
2555
          - diagnose is the error message for an invalid OS, otherwise empty
2556
          - variants is a list of supported OS variants, if any
2557
          - parameters is a list of (name, help) parameters, if any
2558
          - api_version is a list of support OS API versions
2559

2560
  """
2561
  if top_dirs is None:
2562
    top_dirs = pathutils.OS_SEARCH_PATH
2563

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

    
2586
  return result
2587

    
2588

    
2589
def _TryOSFromDisk(name, base_dir=None):
2590
  """Create an OS instance from disk.
2591

2592
  This function will return an OS instance if the given name is a
2593
  valid OS name.
2594

2595
  @type base_dir: string
2596
  @keyword base_dir: Base directory containing OS installations.
2597
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2598
  @rtype: tuple
2599
  @return: success and either the OS instance if we find a valid one,
2600
      or error message
2601

2602
  """
2603
  if base_dir is None:
2604
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2605
  else:
2606
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2607

    
2608
  if os_dir is None:
2609
    return False, "Directory for OS %s not found in search path" % name
2610

    
2611
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2612
  if not status:
2613
    # push the error up
2614
    return status, api_versions
2615

    
2616
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2617
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2618
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2619

    
2620
  # OS Files dictionary, we will populate it with the absolute path
2621
  # names; if the value is True, then it is a required file, otherwise
2622
  # an optional one
2623
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2624

    
2625
  if max(api_versions) >= constants.OS_API_V15:
2626
    os_files[constants.OS_VARIANTS_FILE] = False
2627

    
2628
  if max(api_versions) >= constants.OS_API_V20:
2629
    os_files[constants.OS_PARAMETERS_FILE] = True
2630
  else:
2631
    del os_files[constants.OS_SCRIPT_VERIFY]
2632

    
2633
  for (filename, required) in os_files.items():
2634
    os_files[filename] = utils.PathJoin(os_dir, filename)
2635

    
2636
    try:
2637
      st = os.stat(os_files[filename])
2638
    except EnvironmentError, err:
2639
      if err.errno == errno.ENOENT and not required:
2640
        del os_files[filename]
2641
        continue
2642
      return False, ("File '%s' under path '%s' is missing (%s)" %
2643
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2644

    
2645
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2646
      return False, ("File '%s' under path '%s' is not a regular file" %
2647
                     (filename, os_dir))
2648

    
2649
    if filename in constants.OS_SCRIPTS:
2650
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2651
        return False, ("File '%s' under path '%s' is not executable" %
2652
                       (filename, os_dir))
2653

    
2654
  variants = []
2655
  if constants.OS_VARIANTS_FILE in os_files:
2656
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2657
    try:
2658
      variants = \
2659
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2660
    except EnvironmentError, err:
2661
      # we accept missing files, but not other errors
2662
      if err.errno != errno.ENOENT:
2663
        return False, ("Error while reading the OS variants file at %s: %s" %
2664
                       (variants_file, utils.ErrnoOrStr(err)))
2665

    
2666
  parameters = []
2667
  if constants.OS_PARAMETERS_FILE in os_files:
2668
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2669
    try:
2670
      parameters = utils.ReadFile(parameters_file).splitlines()
2671
    except EnvironmentError, err:
2672
      return False, ("Error while reading the OS parameters file at %s: %s" %
2673
                     (parameters_file, utils.ErrnoOrStr(err)))
2674
    parameters = [v.split(None, 1) for v in parameters]
2675

    
2676
  os_obj = objects.OS(name=name, path=os_dir,
2677
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2678
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2679
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2680
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2681
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2682
                                                 None),
2683
                      supported_variants=variants,
2684
                      supported_parameters=parameters,
2685
                      api_versions=api_versions)
2686
  return True, os_obj
2687

    
2688

    
2689
def OSFromDisk(name, base_dir=None):
2690
  """Create an OS instance from disk.
2691

2692
  This function will return an OS instance if the given name is a
2693
  valid OS name. Otherwise, it will raise an appropriate
2694
  L{RPCFail} exception, detailing why this is not a valid OS.
2695

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

2699
  @type base_dir: string
2700
  @keyword base_dir: Base directory containing OS installations.
2701
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2702
  @rtype: L{objects.OS}
2703
  @return: the OS instance if we find a valid one
2704
  @raise RPCFail: if we don't find a valid OS
2705

2706
  """
2707
  name_only = objects.OS.GetName(name)
2708
  status, payload = _TryOSFromDisk(name_only, base_dir)
2709

    
2710
  if not status:
2711
    _Fail(payload)
2712

    
2713
  return payload
2714

    
2715

    
2716
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2717
  """Calculate the basic environment for an os script.
2718

2719
  @type os_name: str
2720
  @param os_name: full operating system name (including variant)
2721
  @type inst_os: L{objects.OS}
2722
  @param inst_os: operating system for which the environment is being built
2723
  @type os_params: dict
2724
  @param os_params: the OS parameters
2725
  @type debug: integer
2726
  @param debug: debug level (0 or 1, for OS Api 10)
2727
  @rtype: dict
2728
  @return: dict of environment variables
2729
  @raise errors.BlockDeviceError: if the block device
2730
      cannot be found
2731

2732
  """
2733
  result = {}
2734
  api_version = \
2735
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2736
  result["OS_API_VERSION"] = "%d" % api_version
2737
  result["OS_NAME"] = inst_os.name
2738
  result["DEBUG_LEVEL"] = "%d" % debug
2739

    
2740
  # OS variants
2741
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2742
    variant = objects.OS.GetVariant(os_name)
2743
    if not variant:
2744
      variant = inst_os.supported_variants[0]
2745
  else:
2746
    variant = ""
2747
  result["OS_VARIANT"] = variant
2748

    
2749
  # OS params
2750
  for pname, pvalue in os_params.items():
2751
    result["OSP_%s" % pname.upper()] = pvalue
2752

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

    
2758
  return result
2759

    
2760

    
2761
def OSEnvironment(instance, inst_os, debug=0):
2762
  """Calculate the environment for an os script.
2763

2764
  @type instance: L{objects.Instance}
2765
  @param instance: target instance for the os script run
2766
  @type inst_os: L{objects.OS}
2767
  @param inst_os: operating system for which the environment is being built
2768
  @type debug: integer
2769
  @param debug: debug level (0 or 1, for OS Api 10)
2770
  @rtype: dict
2771
  @return: dict of environment variables
2772
  @raise errors.BlockDeviceError: if the block device
2773
      cannot be found
2774

2775
  """
2776
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2777

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

    
2781
  result["HYPERVISOR"] = instance.hypervisor
2782
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2783
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2784
  result["INSTANCE_SECONDARY_NODES"] = \
2785
      ("%s" % " ".join(instance.secondary_nodes))
2786

    
2787
  # Disks
2788
  for idx, disk in enumerate(instance.disks):
2789
    real_disk = _OpenRealBD(disk)
2790
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2791
    result["DISK_%d_ACCESS" % idx] = disk.mode
2792
    result["DISK_%d_UUID" % idx] = disk.uuid
2793
    if disk.name:
2794
      result["DISK_%d_NAME" % idx] = disk.name
2795
    if constants.HV_DISK_TYPE in instance.hvparams:
2796
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2797
        instance.hvparams[constants.HV_DISK_TYPE]
2798
    if disk.dev_type in constants.LDS_BLOCK:
2799
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2800
    elif disk.dev_type == constants.LD_FILE:
2801
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2802
        "file:%s" % disk.physical_id[0]
2803

    
2804
  # NICs
2805
  for idx, nic in enumerate(instance.nics):
2806
    result["NIC_%d_MAC" % idx] = nic.mac
2807
    result["NIC_%d_UUID" % idx] = nic.uuid
2808
    if nic.name:
2809
      result["NIC_%d_NAME" % idx] = nic.name
2810
    if nic.ip:
2811
      result["NIC_%d_IP" % idx] = nic.ip
2812
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2813
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2814
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2815
    if nic.nicparams[constants.NIC_LINK]:
2816
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2817
    if nic.netinfo:
2818
      nobj = objects.Network.FromDict(nic.netinfo)
2819
      result.update(nobj.HooksDict("NIC_%d_" % idx))
2820
    if constants.HV_NIC_TYPE in instance.hvparams:
2821
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2822
        instance.hvparams[constants.HV_NIC_TYPE]
2823

    
2824
  # HV/BE params
2825
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2826
    for key, value in source.items():
2827
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2828

    
2829
  return result
2830

    
2831

    
2832
def DiagnoseExtStorage(top_dirs=None):
2833
  """Compute the validity for all ExtStorage Providers.
2834

2835
  @type top_dirs: list
2836
  @param top_dirs: the list of directories in which to
2837
      search (if not given defaults to
2838
      L{pathutils.ES_SEARCH_PATH})
2839
  @rtype: list of L{objects.ExtStorage}
2840
  @return: a list of tuples (name, path, status, diagnose, parameters)
2841
      for all (potential) ExtStorage Providers under all
2842
      search paths, where:
2843
          - name is the (potential) ExtStorage Provider
2844
          - path is the full path to the ExtStorage Provider
2845
          - status True/False is the validity of the ExtStorage Provider
2846
          - diagnose is the error message for an invalid ExtStorage Provider,
2847
            otherwise empty
2848
          - parameters is a list of (name, help) parameters, if any
2849

2850
  """
2851
  if top_dirs is None:
2852
    top_dirs = pathutils.ES_SEARCH_PATH
2853

    
2854
  result = []
2855
  for dir_name in top_dirs:
2856
    if os.path.isdir(dir_name):
2857
      try:
2858
        f_names = utils.ListVisibleFiles(dir_name)
2859
      except EnvironmentError, err:
2860
        logging.exception("Can't list the ExtStorage directory %s: %s",
2861
                          dir_name, err)
2862
        break
2863
      for name in f_names:
2864
        es_path = utils.PathJoin(dir_name, name)
2865
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2866
        if status:
2867
          diagnose = ""
2868
          parameters = es_inst.supported_parameters
2869
        else:
2870
          diagnose = es_inst
2871
          parameters = []
2872
        result.append((name, es_path, status, diagnose, parameters))
2873

    
2874
  return result
2875

    
2876

    
2877
def BlockdevGrow(disk, amount, dryrun, backingstore, excl_stor):
2878
  """Grow a stack of block devices.
2879

2880
  This function is called recursively, with the childrens being the
2881
  first ones to resize.
2882

2883
  @type disk: L{objects.Disk}
2884
  @param disk: the disk to be grown
2885
  @type amount: integer
2886
  @param amount: the amount (in mebibytes) to grow with
2887
  @type dryrun: boolean
2888
  @param dryrun: whether to execute the operation in simulation mode
2889
      only, without actually increasing the size
2890
  @param backingstore: whether to execute the operation on backing storage
2891
      only, or on "logical" storage only; e.g. DRBD is logical storage,
2892
      whereas LVM, file, RBD are backing storage
2893
  @rtype: (status, result)
2894
  @type excl_stor: boolean
2895
  @param excl_stor: Whether exclusive_storage is active
2896
  @return: a tuple with the status of the operation (True/False), and
2897
      the errors message if status is False
2898

2899
  """
2900
  r_dev = _RecursiveFindBD(disk)
2901
  if r_dev is None:
2902
    _Fail("Cannot find block device %s", disk)
2903

    
2904
  try:
2905
    r_dev.Grow(amount, dryrun, backingstore, excl_stor)
2906
  except errors.BlockDeviceError, err:
2907
    _Fail("Failed to grow block device: %s", err, exc=True)
2908

    
2909

    
2910
def BlockdevSnapshot(disk):
2911
  """Create a snapshot copy of a block device.
2912

2913
  This function is called recursively, and the snapshot is actually created
2914
  just for the leaf lvm backend device.
2915

2916
  @type disk: L{objects.Disk}
2917
  @param disk: the disk to be snapshotted
2918
  @rtype: string
2919
  @return: snapshot disk ID as (vg, lv)
2920

2921
  """
2922
  if disk.dev_type == constants.LD_DRBD8:
2923
    if not disk.children:
2924
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2925
            disk.unique_id)
2926
    return BlockdevSnapshot(disk.children[0])
2927
  elif disk.dev_type == constants.LD_LV:
2928
    r_dev = _RecursiveFindBD(disk)
2929
    if r_dev is not None:
2930
      # FIXME: choose a saner value for the snapshot size
2931
      # let's stay on the safe side and ask for the full size, for now
2932
      return r_dev.Snapshot(disk.size)
2933
    else:
2934
      _Fail("Cannot find block device %s", disk)
2935
  else:
2936
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2937
          disk.unique_id, disk.dev_type)
2938

    
2939

    
2940
def BlockdevSetInfo(disk, info):
2941
  """Sets 'metadata' information on block devices.
2942

2943
  This function sets 'info' metadata on block devices. Initial
2944
  information is set at device creation; this function should be used
2945
  for example after renames.
2946

2947
  @type disk: L{objects.Disk}
2948
  @param disk: the disk to be grown
2949
  @type info: string
2950
  @param info: new 'info' metadata
2951
  @rtype: (status, result)
2952
  @return: a tuple with the status of the operation (True/False), and
2953
      the errors message if status is False
2954

2955
  """
2956
  r_dev = _RecursiveFindBD(disk)
2957
  if r_dev is None:
2958
    _Fail("Cannot find block device %s", disk)
2959

    
2960
  try:
2961
    r_dev.SetInfo(info)
2962
  except errors.BlockDeviceError, err:
2963
    _Fail("Failed to set information on block device: %s", err, exc=True)
2964

    
2965

    
2966
def FinalizeExport(instance, snap_disks):
2967
  """Write out the export configuration information.
2968

2969
  @type instance: L{objects.Instance}
2970
  @param instance: the instance which we export, used for
2971
      saving configuration
2972
  @type snap_disks: list of L{objects.Disk}
2973
  @param snap_disks: list of snapshot block devices, which
2974
      will be used to get the actual name of the dump file
2975

2976
  @rtype: None
2977

2978
  """
2979
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
2980
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
2981

    
2982
  config = objects.SerializableConfigParser()
2983

    
2984
  config.add_section(constants.INISECT_EXP)
2985
  config.set(constants.INISECT_EXP, "version", "0")
2986
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2987
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2988
  config.set(constants.INISECT_EXP, "os", instance.os)
2989
  config.set(constants.INISECT_EXP, "compression", "none")
2990

    
2991
  config.add_section(constants.INISECT_INS)
2992
  config.set(constants.INISECT_INS, "name", instance.name)
2993
  config.set(constants.INISECT_INS, "maxmem", "%d" %
2994
             instance.beparams[constants.BE_MAXMEM])
2995
  config.set(constants.INISECT_INS, "minmem", "%d" %
2996
             instance.beparams[constants.BE_MINMEM])
2997
  # "memory" is deprecated, but useful for exporting to old ganeti versions
2998
  config.set(constants.INISECT_INS, "memory", "%d" %
2999
             instance.beparams[constants.BE_MAXMEM])
3000
  config.set(constants.INISECT_INS, "vcpus", "%d" %
3001
             instance.beparams[constants.BE_VCPUS])
3002
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
3003
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
3004
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
3005

    
3006
  nic_total = 0
3007
  for nic_count, nic in enumerate(instance.nics):
3008
    nic_total += 1
3009
    config.set(constants.INISECT_INS, "nic%d_mac" %
3010
               nic_count, "%s" % nic.mac)
3011
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
3012
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
3013
               "%s" % nic.network)
3014
    for param in constants.NICS_PARAMETER_TYPES:
3015
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
3016
                 "%s" % nic.nicparams.get(param, None))
3017
  # TODO: redundant: on load can read nics until it doesn't exist
3018
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
3019

    
3020
  disk_total = 0
3021
  for disk_count, disk in enumerate(snap_disks):
3022
    if disk:
3023
      disk_total += 1
3024
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
3025
                 ("%s" % disk.iv_name))
3026
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
3027
                 ("%s" % disk.physical_id[1]))
3028
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
3029
                 ("%d" % disk.size))
3030

    
3031
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
3032

    
3033
  # New-style hypervisor/backend parameters
3034

    
3035
  config.add_section(constants.INISECT_HYP)
3036
  for name, value in instance.hvparams.items():
3037
    if name not in constants.HVC_GLOBALS:
3038
      config.set(constants.INISECT_HYP, name, str(value))
3039

    
3040
  config.add_section(constants.INISECT_BEP)
3041
  for name, value in instance.beparams.items():
3042
    config.set(constants.INISECT_BEP, name, str(value))
3043

    
3044
  config.add_section(constants.INISECT_OSP)
3045
  for name, value in instance.osparams.items():
3046
    config.set(constants.INISECT_OSP, name, str(value))
3047

    
3048
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
3049
                  data=config.Dumps())
3050
  shutil.rmtree(finaldestdir, ignore_errors=True)
3051
  shutil.move(destdir, finaldestdir)
3052

    
3053

    
3054
def ExportInfo(dest):
3055
  """Get export configuration information.
3056

3057
  @type dest: str
3058
  @param dest: directory containing the export
3059

3060
  @rtype: L{objects.SerializableConfigParser}
3061
  @return: a serializable config file containing the
3062
      export info
3063

3064
  """
3065
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
3066

    
3067
  config = objects.SerializableConfigParser()
3068
  config.read(cff)
3069

    
3070
  if (not config.has_section(constants.INISECT_EXP) or
3071
      not config.has_section(constants.INISECT_INS)):
3072
    _Fail("Export info file doesn't have the required fields")
3073

    
3074
  return config.Dumps()
3075

    
3076

    
3077
def ListExports():
3078
  """Return a list of exports currently available on this machine.
3079

3080
  @rtype: list
3081
  @return: list of the exports
3082

3083
  """
3084
  if os.path.isdir(pathutils.EXPORT_DIR):
3085
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
3086
  else:
3087
    _Fail("No exports directory")
3088

    
3089

    
3090
def RemoveExport(export):
3091
  """Remove an existing export from the node.
3092

3093
  @type export: str
3094
  @param export: the name of the export to remove
3095
  @rtype: None
3096

3097
  """
3098
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
3099

    
3100
  try:
3101
    shutil.rmtree(target)
3102
  except EnvironmentError, err:
3103
    _Fail("Error while removing the export: %s", err, exc=True)
3104

    
3105

    
3106
def BlockdevRename(devlist):
3107
  """Rename a list of block devices.
3108

3109
  @type devlist: list of tuples
3110
  @param devlist: list of tuples of the form  (disk,
3111
      new_logical_id, new_physical_id); disk is an
3112
      L{objects.Disk} object describing the current disk,
3113
      and new logical_id/physical_id is the name we
3114
      rename it to
3115
  @rtype: boolean
3116
  @return: True if all renames succeeded, False otherwise
3117

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

    
3146

    
3147
def _TransformFileStorageDir(fs_dir):
3148
  """Checks whether given file_storage_dir is valid.
3149

3150
  Checks wheter the given fs_dir is within the cluster-wide default
3151
  file_storage_dir or the shared_file_storage_dir, which are stored in
3152
  SimpleStore. Only paths under those directories are allowed.
3153

3154
  @type fs_dir: str
3155
  @param fs_dir: the path to check
3156

3157
  @return: the normalized path if valid, None otherwise
3158

3159
  """
3160
  if not (constants.ENABLE_FILE_STORAGE or
3161
          constants.ENABLE_SHARED_FILE_STORAGE):
3162
    _Fail("File storage disabled at configure time")
3163

    
3164
  bdev.CheckFileStoragePath(fs_dir)
3165

    
3166
  return os.path.normpath(fs_dir)
3167

    
3168

    
3169
def CreateFileStorageDir(file_storage_dir):
3170
  """Create file storage directory.
3171

3172
  @type file_storage_dir: str
3173
  @param file_storage_dir: directory to create
3174

3175
  @rtype: tuple
3176
  @return: tuple with first element a boolean indicating wheter dir
3177
      creation was successful or not
3178

3179
  """
3180
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3181
  if os.path.exists(file_storage_dir):
3182
    if not os.path.isdir(file_storage_dir):
3183
      _Fail("Specified storage dir '%s' is not a directory",
3184
            file_storage_dir)
3185
  else:
3186
    try:
3187
      os.makedirs(file_storage_dir, 0750)
3188
    except OSError, err:
3189
      _Fail("Cannot create file storage directory '%s': %s",
3190
            file_storage_dir, err, exc=True)
3191

    
3192

    
3193
def RemoveFileStorageDir(file_storage_dir):
3194
  """Remove file storage directory.
3195

3196
  Remove it only if it's empty. If not log an error and return.
3197

3198
  @type file_storage_dir: str
3199
  @param file_storage_dir: the directory we should cleanup
3200
  @rtype: tuple (success,)
3201
  @return: tuple of one element, C{success}, denoting
3202
      whether the operation was successful
3203

3204
  """
3205
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3206
  if os.path.exists(file_storage_dir):
3207
    if not os.path.isdir(file_storage_dir):
3208
      _Fail("Specified Storage directory '%s' is not a directory",
3209
            file_storage_dir)
3210
    # deletes dir only if empty, otherwise we want to fail the rpc call
3211
    try:
3212
      os.rmdir(file_storage_dir)
3213
    except OSError, err:
3214
      _Fail("Cannot remove file storage directory '%s': %s",
3215
            file_storage_dir, err)
3216

    
3217

    
3218
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
3219
  """Rename the file storage directory.
3220

3221
  @type old_file_storage_dir: str
3222
  @param old_file_storage_dir: the current path
3223
  @type new_file_storage_dir: str
3224
  @param new_file_storage_dir: the name we should rename to
3225
  @rtype: tuple (success,)
3226
  @return: tuple of one element, C{success}, denoting
3227
      whether the operation was successful
3228

3229
  """
3230
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
3231
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
3232
  if not os.path.exists(new_file_storage_dir):
3233
    if os.path.isdir(old_file_storage_dir):
3234
      try:
3235
        os.rename(old_file_storage_dir, new_file_storage_dir)
3236
      except OSError, err:
3237
        _Fail("Cannot rename '%s' to '%s': %s",
3238
              old_file_storage_dir, new_file_storage_dir, err)
3239
    else:
3240
      _Fail("Specified storage dir '%s' is not a directory",
3241
            old_file_storage_dir)
3242
  else:
3243
    if os.path.exists(old_file_storage_dir):
3244
      _Fail("Cannot rename '%s' to '%s': both locations exist",
3245
            old_file_storage_dir, new_file_storage_dir)
3246

    
3247

    
3248
def _EnsureJobQueueFile(file_name):
3249
  """Checks whether the given filename is in the queue directory.
3250

3251
  @type file_name: str
3252
  @param file_name: the file name we should check
3253
  @rtype: None
3254
  @raises RPCFail: if the file is not valid
3255

3256
  """
3257
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
3258
    _Fail("Passed job queue file '%s' does not belong to"
3259
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
3260

    
3261

    
3262
def JobQueueUpdate(file_name, content):
3263
  """Updates a file in the queue directory.
3264

3265
  This is just a wrapper over L{utils.io.WriteFile}, with proper
3266
  checking.
3267

3268
  @type file_name: str
3269
  @param file_name: the job file name
3270
  @type content: str
3271
  @param content: the new job contents
3272
  @rtype: boolean
3273
  @return: the success of the operation
3274

3275
  """
3276
  file_name = vcluster.LocalizeVirtualPath(file_name)
3277

    
3278
  _EnsureJobQueueFile(file_name)
3279
  getents = runtime.GetEnts()
3280

    
3281
  # Write and replace the file atomically
3282
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3283
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3284

    
3285

    
3286
def JobQueueRename(old, new):
3287
  """Renames a job queue file.
3288

3289
  This is just a wrapper over os.rename with proper checking.
3290

3291
  @type old: str
3292
  @param old: the old (actual) file name
3293
  @type new: str
3294
  @param new: the desired file name
3295
  @rtype: tuple
3296
  @return: the success of the operation and payload
3297

3298
  """
3299
  old = vcluster.LocalizeVirtualPath(old)
3300
  new = vcluster.LocalizeVirtualPath(new)
3301

    
3302
  _EnsureJobQueueFile(old)
3303
  _EnsureJobQueueFile(new)
3304

    
3305
  getents = runtime.GetEnts()
3306

    
3307
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3308
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3309

    
3310

    
3311
def BlockdevClose(instance_name, disks):
3312
  """Closes the given block devices.
3313

3314
  This means they will be switched to secondary mode (in case of
3315
  DRBD).
3316

3317
  @param instance_name: if the argument is not empty, the symlinks
3318
      of this instance will be removed
3319
  @type disks: list of L{objects.Disk}
3320
  @param disks: the list of disks to be closed
3321
  @rtype: tuple (success, message)
3322
  @return: a tuple of success and message, where success
3323
      indicates the succes of the operation, and message
3324
      which will contain the error details in case we
3325
      failed
3326

3327
  """
3328
  bdevs = []
3329
  for cf in disks:
3330
    rd = _RecursiveFindBD(cf)
3331
    if rd is None:
3332
      _Fail("Can't find device %s", cf)
3333
    bdevs.append(rd)
3334

    
3335
  msg = []
3336
  for rd in bdevs:
3337
    try:
3338
      rd.Close()
3339
    except errors.BlockDeviceError, err:
3340
      msg.append(str(err))
3341
  if msg:
3342
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3343
  else:
3344
    if instance_name:
3345
      _RemoveBlockDevLinks(instance_name, disks)
3346

    
3347

    
3348
def ValidateHVParams(hvname, hvparams):
3349
  """Validates the given hypervisor parameters.
3350

3351
  @type hvname: string
3352
  @param hvname: the hypervisor name
3353
  @type hvparams: dict
3354
  @param hvparams: the hypervisor parameters to be validated
3355
  @rtype: None
3356

3357
  """
3358
  try:
3359
    hv_type = hypervisor.GetHypervisor(hvname)
3360
    hv_type.ValidateParameters(hvparams)
3361
  except errors.HypervisorError, err:
3362
    _Fail(str(err), log=False)
3363

    
3364

    
3365
def _CheckOSPList(os_obj, parameters):
3366
  """Check whether a list of parameters is supported by the OS.
3367

3368
  @type os_obj: L{objects.OS}
3369
  @param os_obj: OS object to check
3370
  @type parameters: list
3371
  @param parameters: the list of parameters to check
3372

3373
  """
3374
  supported = [v[0] for v in os_obj.supported_parameters]
3375
  delta = frozenset(parameters).difference(supported)
3376
  if delta:
3377
    _Fail("The following parameters are not supported"
3378
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3379

    
3380

    
3381
def ValidateOS(required, osname, checks, osparams):
3382
  """Validate the given OS' parameters.
3383

3384
  @type required: boolean
3385
  @param required: whether absence of the OS should translate into
3386
      failure or not
3387
  @type osname: string
3388
  @param osname: the OS to be validated
3389
  @type checks: list
3390
  @param checks: list of the checks to run (currently only 'parameters')
3391
  @type osparams: dict
3392
  @param osparams: dictionary with OS parameters
3393
  @rtype: boolean
3394
  @return: True if the validation passed, or False if the OS was not
3395
      found and L{required} was false
3396

3397
  """
3398
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3399
    _Fail("Unknown checks required for OS %s: %s", osname,
3400
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3401

    
3402
  name_only = objects.OS.GetName(osname)
3403
  status, tbv = _TryOSFromDisk(name_only, None)
3404

    
3405
  if not status:
3406
    if required:
3407
      _Fail(tbv)
3408
    else:
3409
      return False
3410

    
3411
  if max(tbv.api_versions) < constants.OS_API_V20:
3412
    return True
3413

    
3414
  if constants.OS_VALIDATE_PARAMETERS in checks:
3415
    _CheckOSPList(tbv, osparams.keys())
3416

    
3417
  validate_env = OSCoreEnv(osname, tbv, osparams)
3418
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3419
                        cwd=tbv.path, reset_env=True)
3420
  if result.failed:
3421
    logging.error("os validate command '%s' returned error: %s output: %s",
3422
                  result.cmd, result.fail_reason, result.output)
3423
    _Fail("OS validation script failed (%s), output: %s",
3424
          result.fail_reason, result.output, log=False)
3425

    
3426
  return True
3427

    
3428

    
3429
def DemoteFromMC():
3430
  """Demotes the current node from master candidate role.
3431

3432
  """
3433
  # try to ensure we're not the master by mistake
3434
  master, myself = ssconf.GetMasterAndMyself()
3435
  if master == myself:
3436
    _Fail("ssconf status shows I'm the master node, will not demote")
3437

    
3438
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3439
  if not result.failed:
3440
    _Fail("The master daemon is running, will not demote")
3441

    
3442
  try:
3443
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3444
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3445
  except EnvironmentError, err:
3446
    if err.errno != errno.ENOENT:
3447
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3448

    
3449
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3450

    
3451

    
3452
def _GetX509Filenames(cryptodir, name):
3453
  """Returns the full paths for the private key and certificate.
3454

3455
  """
3456
  return (utils.PathJoin(cryptodir, name),
3457
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3458
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3459

    
3460

    
3461
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3462
  """Creates a new X509 certificate for SSL/TLS.
3463

3464
  @type validity: int
3465
  @param validity: Validity in seconds
3466
  @rtype: tuple; (string, string)
3467
  @return: Certificate name and public part
3468

3469
  """
3470
  (key_pem, cert_pem) = \
3471
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3472
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3473

    
3474
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3475
                              prefix="x509-%s-" % utils.TimestampForFilename())
3476
  try:
3477
    name = os.path.basename(cert_dir)
3478
    assert len(name) > 5
3479

    
3480
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3481

    
3482
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3483
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3484

    
3485
    # Never return private key as it shouldn't leave the node
3486
    return (name, cert_pem)
3487
  except Exception:
3488
    shutil.rmtree(cert_dir, ignore_errors=True)
3489
    raise
3490

    
3491

    
3492
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3493
  """Removes a X509 certificate.
3494

3495
  @type name: string
3496
  @param name: Certificate name
3497

3498
  """
3499
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3500

    
3501
  utils.RemoveFile(key_file)
3502
  utils.RemoveFile(cert_file)
3503

    
3504
  try:
3505
    os.rmdir(cert_dir)
3506
  except EnvironmentError, err:
3507
    _Fail("Cannot remove certificate directory '%s': %s",
3508
          cert_dir, err)
3509

    
3510

    
3511
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3512
  """Returns the command for the requested input/output.
3513

3514
  @type instance: L{objects.Instance}
3515
  @param instance: The instance object
3516
  @param mode: Import/export mode
3517
  @param ieio: Input/output type
3518
  @param ieargs: Input/output arguments
3519

3520
  """
3521
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3522

    
3523
  env = None
3524
  prefix = None
3525
  suffix = None
3526
  exp_size = None
3527

    
3528
  if ieio == constants.IEIO_FILE:
3529
    (filename, ) = ieargs
3530

    
3531
    if not utils.IsNormAbsPath(filename):
3532
      _Fail("Path '%s' is not normalized or absolute", filename)
3533

    
3534
    real_filename = os.path.realpath(filename)
3535
    directory = os.path.dirname(real_filename)
3536

    
3537
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3538
      _Fail("File '%s' is not under exports directory '%s': %s",
3539
            filename, pathutils.EXPORT_DIR, real_filename)
3540

    
3541
    # Create directory
3542
    utils.Makedirs(directory, mode=0750)
3543

    
3544
    quoted_filename = utils.ShellQuote(filename)
3545

    
3546
    if mode == constants.IEM_IMPORT:
3547
      suffix = "> %s" % quoted_filename
3548
    elif mode == constants.IEM_EXPORT:
3549
      suffix = "< %s" % quoted_filename
3550

    
3551
      # Retrieve file size
3552
      try:
3553
        st = os.stat(filename)
3554
      except EnvironmentError, err:
3555
        logging.error("Can't stat(2) %s: %s", filename, err)
3556
      else:
3557
        exp_size = utils.BytesToMebibyte(st.st_size)
3558

    
3559
  elif ieio == constants.IEIO_RAW_DISK:
3560
    (disk, ) = ieargs
3561

    
3562
    real_disk = _OpenRealBD(disk)
3563

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

    
3576
    elif mode == constants.IEM_EXPORT:
3577
      # the block size on the read dd is 1MiB to match our units
3578
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3579
                                   real_disk.dev_path,
3580
                                   str(1024 * 1024), # 1 MB
3581
                                   str(disk.size))
3582
      exp_size = disk.size
3583

    
3584
  elif ieio == constants.IEIO_SCRIPT:
3585
    (disk, disk_index, ) = ieargs
3586

    
3587
    assert isinstance(disk_index, (int, long))
3588

    
3589
    real_disk = _OpenRealBD(disk)
3590

    
3591
    inst_os = OSFromDisk(instance.os)
3592
    env = OSEnvironment(instance, inst_os)
3593

    
3594
    if mode == constants.IEM_IMPORT:
3595
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3596
      env["IMPORT_INDEX"] = str(disk_index)
3597
      script = inst_os.import_script
3598

    
3599
    elif mode == constants.IEM_EXPORT:
3600
      env["EXPORT_DEVICE"] = real_disk.dev_path
3601
      env["EXPORT_INDEX"] = str(disk_index)
3602
      script = inst_os.export_script
3603

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

    
3607
    if mode == constants.IEM_IMPORT:
3608
      suffix = "| %s" % script_cmd
3609

    
3610
    elif mode == constants.IEM_EXPORT:
3611
      prefix = "%s |" % script_cmd
3612

    
3613
    # Let script predict size
3614
    exp_size = constants.IE_CUSTOM_SIZE
3615

    
3616
  else:
3617
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3618

    
3619
  return (env, prefix, suffix, exp_size)
3620

    
3621

    
3622
def _CreateImportExportStatusDir(prefix):
3623
  """Creates status directory for import/export.
3624

3625
  """
3626
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3627
                          prefix=("%s-%s-" %
3628
                                  (prefix, utils.TimestampForFilename())))
3629

    
3630

    
3631
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3632
                            ieio, ieioargs):
3633
  """Starts an import or export daemon.
3634

3635
  @param mode: Import/output mode
3636
  @type opts: L{objects.ImportExportOptions}
3637
  @param opts: Daemon options
3638
  @type host: string
3639
  @param host: Remote host for export (None for import)
3640
  @type port: int
3641
  @param port: Remote port for export (None for import)
3642
  @type instance: L{objects.Instance}
3643
  @param instance: Instance object
3644
  @type component: string
3645
  @param component: which part of the instance is transferred now,
3646
      e.g. 'disk/0'
3647
  @param ieio: Input/output type
3648
  @param ieioargs: Input/output arguments
3649

3650
  """
3651
  if mode == constants.IEM_IMPORT:
3652
    prefix = "import"
3653

    
3654
    if not (host is None and port is None):
3655
      _Fail("Can not specify host or port on import")
3656

    
3657
  elif mode == constants.IEM_EXPORT:
3658
    prefix = "export"
3659

    
3660
    if host is None or port is None:
3661
      _Fail("Host and port must be specified for an export")
3662

    
3663
  else:
3664
    _Fail("Invalid mode %r", mode)
3665

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

    
3669
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3670
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3671

    
3672
  if opts.key_name is None:
3673
    # Use server.pem
3674
    key_path = pathutils.NODED_CERT_FILE
3675
    cert_path = pathutils.NODED_CERT_FILE
3676
    assert opts.ca_pem is None
3677
  else:
3678
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3679
                                                 opts.key_name)
3680
    assert opts.ca_pem is not None
3681

    
3682
  for i in [key_path, cert_path]:
3683
    if not os.path.exists(i):
3684
      _Fail("File '%s' does not exist" % i)
3685

    
3686
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3687
  try:
3688
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3689
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3690
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3691

    
3692
    if opts.ca_pem is None:
3693
      # Use server.pem
3694
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3695
    else:
3696
      ca = opts.ca_pem
3697

    
3698
    # Write CA file
3699
    utils.WriteFile(ca_file, data=ca, mode=0400)
3700

    
3701
    cmd = [
3702
      pathutils.IMPORT_EXPORT_DAEMON,
3703
      status_file, mode,
3704
      "--key=%s" % key_path,
3705
      "--cert=%s" % cert_path,
3706
      "--ca=%s" % ca_file,
3707
      ]
3708

    
3709
    if host:
3710
      cmd.append("--host=%s" % host)
3711

    
3712
    if port:
3713
      cmd.append("--port=%s" % port)
3714

    
3715
    if opts.ipv6:
3716
      cmd.append("--ipv6")
3717
    else:
3718
      cmd.append("--ipv4")
3719

    
3720
    if opts.compress:
3721
      cmd.append("--compress=%s" % opts.compress)
3722

    
3723
    if opts.magic:
3724
      cmd.append("--magic=%s" % opts.magic)
3725

    
3726
    if exp_size is not None:
3727
      cmd.append("--expected-size=%s" % exp_size)
3728

    
3729
    if cmd_prefix:
3730
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3731

    
3732
    if cmd_suffix:
3733
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3734

    
3735
    if mode == constants.IEM_EXPORT:
3736
      # Retry connection a few times when connecting to remote peer
3737
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3738
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3739
    elif opts.connect_timeout is not None:
3740
      assert mode == constants.IEM_IMPORT
3741
      # Overall timeout for establishing connection while listening
3742
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3743

    
3744
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3745

    
3746
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3747
    # support for receiving a file descriptor for output
3748
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3749
                      output=logfile)
3750

    
3751
    # The import/export name is simply the status directory name
3752
    return os.path.basename(status_dir)
3753

    
3754
  except Exception:
3755
    shutil.rmtree(status_dir, ignore_errors=True)
3756
    raise
3757

    
3758

    
3759
def GetImportExportStatus(names):
3760
  """Returns import/export daemon status.
3761

3762
  @type names: sequence
3763
  @param names: List of names
3764
  @rtype: List of dicts
3765
  @return: Returns a list of the state of each named import/export or None if a
3766
           status couldn't be read
3767

3768
  """
3769
  result = []
3770

    
3771
  for name in names:
3772
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3773
                                 _IES_STATUS_FILE)
3774

    
3775
    try:
3776
      data = utils.ReadFile(status_file)
3777
    except EnvironmentError, err:
3778
      if err.errno != errno.ENOENT:
3779
        raise
3780
      data = None
3781

    
3782
    if not data:
3783
      result.append(None)
3784
      continue
3785

    
3786
    result.append(serializer.LoadJson(data))
3787

    
3788
  return result
3789

    
3790

    
3791
def AbortImportExport(name):
3792
  """Sends SIGTERM to a running import/export daemon.
3793

3794
  """
3795
  logging.info("Abort import/export %s", name)
3796

    
3797
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3798
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3799

    
3800
  if pid:
3801
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3802
                 name, pid)
3803
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3804

    
3805

    
3806
def CleanupImportExport(name):
3807
  """Cleanup after an import or export.
3808

3809
  If the import/export daemon is still running it's killed. Afterwards the
3810
  whole status directory is removed.
3811

3812
  """
3813
  logging.info("Finalizing import/export %s", name)
3814

    
3815
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3816

    
3817
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3818

    
3819
  if pid:
3820
    logging.info("Import/export %s is still running with PID %s",
3821
                 name, pid)
3822
    utils.KillProcess(pid, waitpid=False)
3823

    
3824
  shutil.rmtree(status_dir, ignore_errors=True)
3825

    
3826

    
3827
def _SetPhysicalId(target_node_uuid, nodes_ip, disks):
3828
  """Sets the correct physical ID on all passed disks.
3829

3830
  """
3831
  for cf in disks:
3832
    cf.SetPhysicalID(target_node_uuid, nodes_ip)
3833

    
3834

    
3835
def _FindDisks(target_node_uuid, nodes_ip, disks):
3836
  """Sets the physical ID on disks and returns the block devices.
3837

3838
  """
3839
  _SetPhysicalId(target_node_uuid, nodes_ip, disks)
3840

    
3841
  bdevs = []
3842

    
3843
  for cf in disks:
3844
    rd = _RecursiveFindBD(cf)
3845
    if rd is None:
3846
      _Fail("Can't find device %s", cf)
3847
    bdevs.append(rd)
3848
  return bdevs
3849

    
3850

    
3851
def DrbdDisconnectNet(target_node_uuid, nodes_ip, disks):
3852
  """Disconnects the network on a list of drbd devices.
3853

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

    
3857
  # disconnect disks
3858
  for rd in bdevs:
3859
    try:
3860
      rd.DisconnectNet()
3861
    except errors.BlockDeviceError, err:
3862
      _Fail("Can't change network configuration to standalone mode: %s",
3863
            err, exc=True)
3864

    
3865

    
3866
def DrbdAttachNet(target_node_uuid, nodes_ip, disks, instance_name,
3867
                  multimaster):
3868
  """Attaches the network on a list of drbd devices.
3869

3870
  """
3871
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3872

    
3873
  if multimaster:
3874
    for idx, rd in enumerate(bdevs):
3875
      try:
3876
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3877
      except EnvironmentError, err:
3878
        _Fail("Can't create symlink: %s", err)
3879
  # reconnect disks, switch to new master configuration and if
3880
  # needed primary mode
3881
  for rd in bdevs:
3882
    try:
3883
      rd.AttachNet(multimaster)
3884
    except errors.BlockDeviceError, err:
3885
      _Fail("Can't change network configuration: %s", err)
3886

    
3887
  # wait until the disks are connected; we need to retry the re-attach
3888
  # if the device becomes standalone, as this might happen if the one
3889
  # node disconnects and reconnects in a different mode before the
3890
  # other node reconnects; in this case, one or both of the nodes will
3891
  # decide it has wrong configuration and switch to standalone
3892

    
3893
  def _Attach():
3894
    all_connected = True
3895

    
3896
    for rd in bdevs:
3897
      stats = rd.GetProcStatus()
3898

    
3899
      all_connected = (all_connected and
3900
                       (stats.is_connected or stats.is_in_resync))
3901

    
3902
      if stats.is_standalone:
3903
        # peer had different config info and this node became
3904
        # standalone, even though this should not happen with the
3905
        # new staged way of changing disk configs
3906
        try:
3907
          rd.AttachNet(multimaster)
3908
        except errors.BlockDeviceError, err:
3909
          _Fail("Can't change network configuration: %s", err)
3910

    
3911
    if not all_connected:
3912
      raise utils.RetryAgain()
3913

    
3914
  try:
3915
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3916
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3917
  except utils.RetryTimeout:
3918
    _Fail("Timeout in disk reconnecting")
3919

    
3920
  if multimaster:
3921
    # change to primary mode
3922
    for rd in bdevs:
3923
      try:
3924
        rd.Open()
3925
      except errors.BlockDeviceError, err:
3926
        _Fail("Can't change to primary mode: %s", err)
3927

    
3928

    
3929
def DrbdWaitSync(target_node_uuid, nodes_ip, disks):
3930
  """Wait until DRBDs have synchronized.
3931

3932
  """
3933
  def _helper(rd):
3934
    stats = rd.GetProcStatus()
3935
    if not (stats.is_connected or stats.is_in_resync):
3936
      raise utils.RetryAgain()
3937
    return stats
3938

    
3939
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3940

    
3941
  min_resync = 100
3942
  alldone = True
3943
  for rd in bdevs:
3944
    try:
3945
      # poll each second for 15 seconds
3946
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3947
    except utils.RetryTimeout:
3948
      stats = rd.GetProcStatus()
3949
      # last check
3950
      if not (stats.is_connected or stats.is_in_resync):
3951
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3952
    alldone = alldone and (not stats.is_in_resync)
3953
    if stats.sync_percent is not None:
3954
      min_resync = min(min_resync, stats.sync_percent)
3955

    
3956
  return (alldone, min_resync)
3957

    
3958

    
3959
def DrbdNeedsActivation(target_node_uuid, nodes_ip, disks):
3960
  """Checks which of the passed disks needs activation and returns their UUIDs.
3961

3962
  """
3963
  _SetPhysicalId(target_node_uuid, nodes_ip, disks)
3964
  faulty_disks = []
3965

    
3966
  for disk in disks:
3967
    rd = _RecursiveFindBD(disk)
3968
    if rd is None:
3969
      faulty_disks.append(disk)
3970
      continue
3971

    
3972
    stats = rd.GetProcStatus()
3973
    if stats.is_standalone or stats.is_diskless:
3974
      faulty_disks.append(disk)
3975

    
3976
  return [disk.uuid for disk in faulty_disks]
3977

    
3978

    
3979
def GetDrbdUsermodeHelper():
3980
  """Returns DRBD usermode helper currently configured.
3981

3982
  """
3983
  try:
3984
    return drbd.DRBD8.GetUsermodeHelper()
3985
  except errors.BlockDeviceError, err:
3986
    _Fail(str(err))
3987

    
3988

    
3989
def PowercycleNode(hypervisor_type, hvparams=None):
3990
  """Hard-powercycle the node.
3991

3992
  Because we need to return first, and schedule the powercycle in the
3993
  background, we won't be able to report failures nicely.
3994

3995
  """
3996
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3997
  try:
3998
    pid = os.fork()
3999
  except OSError:
4000
    # if we can't fork, we'll pretend that we're in the child process
4001
    pid = 0
4002
  if pid > 0:
4003
    return "Reboot scheduled in 5 seconds"
4004
  # ensure the child is running on ram
4005
  try:
4006
    utils.Mlockall()
4007
  except Exception: # pylint: disable=W0703
4008
    pass
4009
  time.sleep(5)
4010
  hyper.PowercycleNode(hvparams=hvparams)
4011

    
4012

    
4013
def _VerifyRestrictedCmdName(cmd):
4014
  """Verifies a restricted command name.
4015

4016
  @type cmd: string
4017
  @param cmd: Command name
4018
  @rtype: tuple; (boolean, string or None)
4019
  @return: The tuple's first element is the status; if C{False}, the second
4020
    element is an error message string, otherwise it's C{None}
4021

4022
  """
4023
  if not cmd.strip():
4024
    return (False, "Missing command name")
4025

    
4026
  if os.path.basename(cmd) != cmd:
4027
    return (False, "Invalid command name")
4028

    
4029
  if not constants.EXT_PLUGIN_MASK.match(cmd):
4030
    return (False, "Command name contains forbidden characters")
4031

    
4032
  return (True, None)
4033

    
4034

    
4035
def _CommonRestrictedCmdCheck(path, owner):
4036
  """Common checks for restricted command file system directories and files.
4037

4038
  @type path: string
4039
  @param path: Path to check
4040
  @param owner: C{None} or tuple containing UID and GID
4041
  @rtype: tuple; (boolean, string or C{os.stat} result)
4042
  @return: The tuple's first element is the status; if C{False}, the second
4043
    element is an error message string, otherwise it's the result of C{os.stat}
4044

4045
  """
4046
  if owner is None:
4047
    # Default to root as owner
4048
    owner = (0, 0)
4049

    
4050
  try:
4051
    st = os.stat(path)
4052
  except EnvironmentError, err:
4053
    return (False, "Can't stat(2) '%s': %s" % (path, err))
4054

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

    
4058
  if (st.st_uid, st.st_gid) != owner:
4059
    (owner_uid, owner_gid) = owner
4060
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
4061

    
4062
  return (True, st)
4063

    
4064

    
4065
def _VerifyRestrictedCmdDirectory(path, _owner=None):
4066
  """Verifies restricted command directory.
4067

4068
  @type path: string
4069
  @param path: Path to check
4070
  @rtype: tuple; (boolean, string or None)
4071
  @return: The tuple's first element is the status; if C{False}, the second
4072
    element is an error message string, otherwise it's C{None}
4073

4074
  """
4075
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
4076

    
4077
  if not status:
4078
    return (False, value)
4079

    
4080
  if not stat.S_ISDIR(value.st_mode):
4081
    return (False, "Path '%s' is not a directory" % path)
4082

    
4083
  return (True, None)
4084

    
4085

    
4086
def _VerifyRestrictedCmd(path, cmd, _owner=None):
4087
  """Verifies a whole restricted command and returns its executable filename.
4088

4089
  @type path: string
4090
  @param path: Directory containing restricted commands
4091
  @type cmd: string
4092
  @param cmd: Command name
4093
  @rtype: tuple; (boolean, string)
4094
  @return: The tuple's first element is the status; if C{False}, the second
4095
    element is an error message string, otherwise the second element is the
4096
    absolute path to the executable
4097

4098
  """
4099
  executable = utils.PathJoin(path, cmd)
4100

    
4101
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
4102

    
4103
  if not status:
4104
    return (False, msg)
4105

    
4106
  if not utils.IsExecutable(executable):
4107
    return (False, "access(2) thinks '%s' can't be executed" % executable)
4108

    
4109
  return (True, executable)
4110

    
4111

    
4112
def _PrepareRestrictedCmd(path, cmd,
4113
                          _verify_dir=_VerifyRestrictedCmdDirectory,
4114
                          _verify_name=_VerifyRestrictedCmdName,
4115
                          _verify_cmd=_VerifyRestrictedCmd):
4116
  """Performs a number of tests on a restricted command.
4117

4118
  @type path: string
4119
  @param path: Directory containing restricted commands
4120
  @type cmd: string
4121
  @param cmd: Command name
4122
  @return: Same as L{_VerifyRestrictedCmd}
4123

4124
  """
4125
  # Verify the directory first
4126
  (status, msg) = _verify_dir(path)
4127
  if status:
4128
    # Check command if everything was alright
4129
    (status, msg) = _verify_name(cmd)
4130

    
4131
  if not status:
4132
    return (False, msg)
4133

    
4134
  # Check actual executable
4135
  return _verify_cmd(path, cmd)
4136

    
4137

    
4138
def RunRestrictedCmd(cmd,
4139
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
4140
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
4141
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
4142
                     _sleep_fn=time.sleep,
4143
                     _prepare_fn=_PrepareRestrictedCmd,
4144
                     _runcmd_fn=utils.RunCmd,
4145
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
4146
  """Executes a restricted command after performing strict tests.
4147

4148
  @type cmd: string
4149
  @param cmd: Command name
4150
  @rtype: string
4151
  @return: Command output
4152
  @raise RPCFail: In case of an error
4153

4154
  """
4155
  logging.info("Preparing to run restricted command '%s'", cmd)
4156

    
4157
  if not _enabled:
4158
    _Fail("Restricted commands disabled at configure time")
4159

    
4160
  lock = None
4161
  try:
4162
    cmdresult = None
4163
    try:
4164
      lock = utils.FileLock.Open(_lock_file)
4165
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
4166

    
4167
      (status, value) = _prepare_fn(_path, cmd)
4168

    
4169
      if status:
4170
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
4171
                               postfork_fn=lambda _: lock.Unlock())
4172
      else:
4173
        logging.error(value)
4174
    except Exception: # pylint: disable=W0703
4175
      # Keep original error in log
4176
      logging.exception("Caught exception")
4177

    
4178
    if cmdresult is None:
4179
      logging.info("Sleeping for %0.1f seconds before returning",
4180
                   _RCMD_INVALID_DELAY)
4181
      _sleep_fn(_RCMD_INVALID_DELAY)
4182

    
4183
      # Do not include original error message in returned error
4184
      _Fail("Executing command '%s' failed" % cmd)
4185
    elif cmdresult.failed or cmdresult.fail_reason:
4186
      _Fail("Restricted command '%s' failed: %s; output: %s",
4187
            cmd, cmdresult.fail_reason, cmdresult.output)
4188
    else:
4189
      return cmdresult.output
4190
  finally:
4191
    if lock is not None:
4192
      # Release lock at last
4193
      lock.Close()
4194
      lock = None
4195

    
4196

    
4197
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
4198
  """Creates or removes the watcher pause file.
4199

4200
  @type until: None or number
4201
  @param until: Unix timestamp saying until when the watcher shouldn't run
4202

4203
  """
4204
  if until is None:
4205
    logging.info("Received request to no longer pause watcher")
4206
    utils.RemoveFile(_filename)
4207
  else:
4208
    logging.info("Received request to pause watcher until %s", until)
4209

    
4210
    if not ht.TNumber(until):
4211
      _Fail("Duration must be numeric")
4212

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

    
4215

    
4216
class HooksRunner(object):
4217
  """Hook runner.
4218

4219
  This class is instantiated on the node side (ganeti-noded) and not
4220
  on the master side.
4221

4222
  """
4223
  def __init__(self, hooks_base_dir=None):
4224
    """Constructor for hooks runner.
4225

4226
    @type hooks_base_dir: str or None
4227
    @param hooks_base_dir: if not None, this overrides the
4228
        L{pathutils.HOOKS_BASE_DIR} (useful for unittests)
4229

4230
    """
4231
    if hooks_base_dir is None:
4232
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
4233
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
4234
    # constant
4235
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
4236

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

4240
    """
4241
    assert len(node_list) == 1
4242
    node = node_list[0]
4243
    _, myself = ssconf.GetMasterAndMyself()
4244
    assert node == myself
4245

    
4246
    results = self.RunHooks(hpath, phase, env)
4247

    
4248
    # Return values in the form expected by HooksMaster
4249
    return {node: (None, False, results)}
4250

    
4251
  def RunHooks(self, hpath, phase, env):
4252
    """Run the scripts in the hooks directory.
4253

4254
    @type hpath: str
4255
    @param hpath: the path to the hooks directory which
4256
        holds the scripts
4257
    @type phase: str
4258
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
4259
        L{constants.HOOKS_PHASE_POST}
4260
    @type env: dict
4261
    @param env: dictionary with the environment for the hook
4262
    @rtype: list
4263
    @return: list of 3-element tuples:
4264
      - script path
4265
      - script result, either L{constants.HKR_SUCCESS} or
4266
        L{constants.HKR_FAIL}
4267
      - output of the script
4268

4269
    @raise errors.ProgrammerError: for invalid input
4270
        parameters
4271

4272
    """
4273
    if phase == constants.HOOKS_PHASE_PRE:
4274
      suffix = "pre"
4275
    elif phase == constants.HOOKS_PHASE_POST:
4276
      suffix = "post"
4277
    else:
4278
      _Fail("Unknown hooks phase '%s'", phase)
4279

    
4280
    subdir = "%s-%s.d" % (hpath, suffix)
4281
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
4282

    
4283
    results = []
4284

    
4285
    if not os.path.isdir(dir_name):
4286
      # for non-existing/non-dirs, we simply exit instead of logging a
4287
      # warning at every operation
4288
      return results
4289

    
4290
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
4291

    
4292
    for (relname, relstatus, runresult) in runparts_results:
4293
      if relstatus == constants.RUNPARTS_SKIP:
4294
        rrval = constants.HKR_SKIP
4295
        output = ""
4296
      elif relstatus == constants.RUNPARTS_ERR:
4297
        rrval = constants.HKR_FAIL
4298
        output = "Hook script execution error: %s" % runresult
4299
      elif relstatus == constants.RUNPARTS_RUN:
4300
        if runresult.failed:
4301
          rrval = constants.HKR_FAIL
4302
        else:
4303
          rrval = constants.HKR_SUCCESS
4304
        output = utils.SafeEncode(runresult.output.strip())
4305
      results.append(("%s/%s" % (subdir, relname), rrval, output))
4306

    
4307
    return results
4308

    
4309

    
4310
class IAllocatorRunner(object):
4311
  """IAllocator runner.
4312

4313
  This class is instantiated on the node side (ganeti-noded) and not on
4314
  the master side.
4315

4316
  """
4317
  @staticmethod
4318
  def Run(name, idata):
4319
    """Run an iallocator script.
4320

4321
    @type name: str
4322
    @param name: the iallocator script name
4323
    @type idata: str
4324
    @param idata: the allocator input data
4325

4326
    @rtype: tuple
4327
    @return: two element tuple of:
4328
       - status
4329
       - either error message or stdout of allocator (for success)
4330

4331
    """
4332
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
4333
                                  os.path.isfile)
4334
    if alloc_script is None:
4335
      _Fail("iallocator module '%s' not found in the search path", name)
4336

    
4337
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
4338
    try:
4339
      os.write(fd, idata)
4340
      os.close(fd)
4341
      result = utils.RunCmd([alloc_script, fin_name])
4342
      if result.failed:
4343
        _Fail("iallocator module '%s' failed: %s, output '%s'",
4344
              name, result.fail_reason, result.output)
4345
    finally:
4346
      os.unlink(fin_name)
4347

    
4348
    return result.stdout
4349

    
4350

    
4351
class DevCacheManager(object):
4352
  """Simple class for managing a cache of block device information.
4353

4354
  """
4355
  _DEV_PREFIX = "/dev/"
4356
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4357

    
4358
  @classmethod
4359
  def _ConvertPath(cls, dev_path):
4360
    """Converts a /dev/name path to the cache file name.
4361

4362
    This replaces slashes with underscores and strips the /dev
4363
    prefix. It then returns the full path to the cache file.
4364

4365
    @type dev_path: str
4366
    @param dev_path: the C{/dev/} path name
4367
    @rtype: str
4368
    @return: the converted path name
4369

4370
    """
4371
    if dev_path.startswith(cls._DEV_PREFIX):
4372
      dev_path = dev_path[len(cls._DEV_PREFIX):]
4373
    dev_path = dev_path.replace("/", "_")
4374
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4375
    return fpath
4376

    
4377
  @classmethod
4378
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4379
    """Updates the cache information for a given device.
4380

4381
    @type dev_path: str
4382
    @param dev_path: the pathname of the device
4383
    @type owner: str
4384
    @param owner: the owner (instance name) of the device
4385
    @type on_primary: bool
4386
    @param on_primary: whether this is the primary
4387
        node nor not
4388
    @type iv_name: str
4389
    @param iv_name: the instance-visible name of the
4390
        device, as in objects.Disk.iv_name
4391

4392
    @rtype: None
4393

4394
    """
4395
    if dev_path is None:
4396
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
4397
      return
4398
    fpath = cls._ConvertPath(dev_path)
4399
    if on_primary:
4400
      state = "primary"
4401
    else:
4402
      state = "secondary"
4403
    if iv_name is None:
4404
      iv_name = "not_visible"
4405
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4406
    try:
4407
      utils.WriteFile(fpath, data=fdata)
4408
    except EnvironmentError, err:
4409
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4410

    
4411
  @classmethod
4412
  def RemoveCache(cls, dev_path):
4413
    """Remove data for a dev_path.
4414

4415
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
4416
    path name and logging.
4417

4418
    @type dev_path: str
4419
    @param dev_path: the pathname of the device
4420

4421
    @rtype: None
4422

4423
    """
4424
    if dev_path is None:
4425
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
4426
      return
4427
    fpath = cls._ConvertPath(dev_path)
4428
    try:
4429
      utils.RemoveFile(fpath)
4430
    except EnvironmentError, err:
4431
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)