Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ b01b7a50

History | View | Annotate | Download (136.4 kB)

1
#
2
#
3

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

    
21

    
22
"""Functions used by the node daemon
23

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

29
"""
30

    
31
# pylint: disable=E1103
32

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

    
37

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

    
52
from ganeti import errors
53
from ganeti import utils
54
from ganeti import ssh
55
from ganeti import hypervisor
56
from ganeti import constants
57
from ganeti.storage import bdev
58
from ganeti.storage import drbd
59
from ganeti.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 _CheckStorageParams(params, num_params):
577
  """Performs sanity checks for storage parameters.
578

579
  @type params: list
580
  @param params: list of storage parameters
581
  @type num_params: int
582
  @param num_params: expected number of parameters
583

584
  """
585
  if params is None:
586
    raise errors.ProgrammerError("No storage parameters for storage"
587
                                 " reporting is provided.")
588
  if not isinstance(params, list):
589
    raise errors.ProgrammerError("The storage parameters are not of type"
590
                                 " list: '%s'" % params)
591
  if not len(params) == num_params:
592
    raise errors.ProgrammerError("Did not receive the expected number of"
593
                                 "storage parameters: expected %s,"
594
                                 " received '%s'" % (num_params, len(params)))
595

    
596

    
597
def _GetLvmVgSpaceInfo(name, params):
598
  """Wrapper around C{_GetVgInfo} which checks the storage parameters.
599

600
  @type name: string
601
  @param name: name of the volume group
602
  @type params: list
603
  @param params: list of storage parameters, which in this case should be
604
    containing only one for exclusive storage
605

606
  """
607
  _CheckStorageParams(params, 1)
608
  excl_stor = bool(params[0])
609
  return _GetVgInfo(name, excl_stor)
610

    
611

    
612
def _GetVgInfo(name, excl_stor):
613
  """Retrieves information about a LVM volume group.
614

615
  """
616
  # TODO: GetVGInfo supports returning information for multiple VGs at once
617
  vginfo = bdev.LogicalVolume.GetVGInfo([name], excl_stor)
618
  if vginfo:
619
    vg_free = int(round(vginfo[0][0], 0))
620
    vg_size = int(round(vginfo[0][1], 0))
621
  else:
622
    vg_free = None
623
    vg_size = None
624

    
625
  return {
626
    "type": constants.ST_LVM_VG,
627
    "name": name,
628
    "storage_free": vg_free,
629
    "storage_size": vg_size,
630
    }
631

    
632

    
633
def _GetVgSpindlesInfo(name, excl_stor):
634
  """Retrieves information about spindles in an LVM volume group.
635

636
  @type name: string
637
  @param name: VG name
638
  @type excl_stor: bool
639
  @param excl_stor: exclusive storage
640
  @rtype: dict
641
  @return: dictionary whose keys are "name", "vg_free", "vg_size" for VG name,
642
      free spindles, total spindles respectively
643

644
  """
645
  if excl_stor:
646
    (vg_free, vg_size) = bdev.LogicalVolume.GetVgSpindlesInfo(name)
647
  else:
648
    vg_free = 0
649
    vg_size = 0
650
  return {
651
    "type": constants.ST_LVM_PV,
652
    "name": name,
653
    "storage_free": vg_free,
654
    "storage_size": vg_size,
655
    }
656

    
657

    
658
def _GetHvInfo(name, hvparams, get_hv_fn=hypervisor.GetHypervisor):
659
  """Retrieves node information from a hypervisor.
660

661
  The information returned depends on the hypervisor. Common items:
662

663
    - vg_size is the size of the configured volume group in MiB
664
    - vg_free is the free size of the volume group in MiB
665
    - memory_dom0 is the memory allocated for domain0 in MiB
666
    - memory_free is the currently available (free) ram in MiB
667
    - memory_total is the total number of ram in MiB
668
    - hv_version: the hypervisor version, if available
669

670
  @type hvparams: dict of string
671
  @param hvparams: the hypervisor's hvparams
672

673
  """
674
  return get_hv_fn(name).GetNodeInfo(hvparams=hvparams)
675

    
676

    
677
def _GetHvInfoAll(hv_specs, get_hv_fn=hypervisor.GetHypervisor):
678
  """Retrieves node information for all hypervisors.
679

680
  See C{_GetHvInfo} for information on the output.
681

682
  @type hv_specs: list of pairs (string, dict of strings)
683
  @param hv_specs: list of pairs of a hypervisor's name and its hvparams
684

685
  """
686
  if hv_specs is None:
687
    return None
688

    
689
  result = []
690
  for hvname, hvparams in hv_specs:
691
    result.append(_GetHvInfo(hvname, hvparams, get_hv_fn))
692
  return result
693

    
694

    
695
def _GetNamedNodeInfo(names, fn):
696
  """Calls C{fn} for all names in C{names} and returns a dictionary.
697

698
  @rtype: None or dict
699

700
  """
701
  if names is None:
702
    return None
703
  else:
704
    return map(fn, names)
705

    
706

    
707
def GetNodeInfo(storage_units, hv_specs):
708
  """Gives back a hash with different information about the node.
709

710
  @type storage_units: list of tuples (string, string, list)
711
  @param storage_units: List of tuples (storage unit, identifier, parameters) to
712
    ask for disk space information. In case of lvm-vg, the identifier is
713
    the VG name. The parameters can contain additional, storage-type-specific
714
    parameters, for example exclusive storage for lvm storage.
715
  @type hv_specs: list of pairs (string, dict of strings)
716
  @param hv_specs: list of pairs of a hypervisor's name and its hvparams
717
  @rtype: tuple; (string, None/dict, None/dict)
718
  @return: Tuple containing boot ID, volume group information and hypervisor
719
    information
720

721
  """
722
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
723
  storage_info = _GetNamedNodeInfo(
724
    storage_units,
725
    (lambda (storage_type, storage_key, storage_params):
726
        _ApplyStorageInfoFunction(storage_type, storage_key, storage_params)))
727
  hv_info = _GetHvInfoAll(hv_specs)
728
  return (bootid, storage_info, hv_info)
729

    
730

    
731
def _GetFileStorageSpaceInfo(path, params):
732
  """Wrapper around filestorage.GetSpaceInfo.
733

734
  The purpose of this wrapper is to call filestorage.GetFileStorageSpaceInfo
735
  and ignore the *args parameter to not leak it into the filestorage
736
  module's code.
737

738
  @see: C{filestorage.GetFileStorageSpaceInfo} for description of the
739
    parameters.
740

741
  """
742
  _CheckStorageParams(params, 0)
743
  return filestorage.GetFileStorageSpaceInfo(path)
744

    
745

    
746
# FIXME: implement storage reporting for all missing storage types.
747
_STORAGE_TYPE_INFO_FN = {
748
  constants.ST_BLOCK: None,
749
  constants.ST_DISKLESS: None,
750
  constants.ST_EXT: None,
751
  constants.ST_FILE: _GetFileStorageSpaceInfo,
752
  constants.ST_LVM_PV: _GetVgSpindlesInfo,
753
  constants.ST_LVM_VG: _GetLvmVgSpaceInfo,
754
  constants.ST_RADOS: None,
755
}
756

    
757

    
758
def _ApplyStorageInfoFunction(storage_type, storage_key, *args):
759
  """Looks up and applies the correct function to calculate free and total
760
  storage for the given storage type.
761

762
  @type storage_type: string
763
  @param storage_type: the storage type for which the storage shall be reported.
764
  @type storage_key: string
765
  @param storage_key: identifier of a storage unit, e.g. the volume group name
766
    of an LVM storage unit
767
  @type args: any
768
  @param args: various parameters that can be used for storage reporting. These
769
    parameters and their semantics vary from storage type to storage type and
770
    are just propagated in this function.
771
  @return: the results of the application of the storage space function (see
772
    _STORAGE_TYPE_INFO_FN) if storage space reporting is implemented for that
773
    storage type
774
  @raises NotImplementedError: for storage types who don't support space
775
    reporting yet
776
  """
777
  fn = _STORAGE_TYPE_INFO_FN[storage_type]
778
  if fn is not None:
779
    return fn(storage_key, *args)
780
  else:
781
    raise NotImplementedError
782

    
783

    
784
def _CheckExclusivePvs(pvi_list):
785
  """Check that PVs are not shared among LVs
786

787
  @type pvi_list: list of L{objects.LvmPvInfo} objects
788
  @param pvi_list: information about the PVs
789

790
  @rtype: list of tuples (string, list of strings)
791
  @return: offending volumes, as tuples: (pv_name, [lv1_name, lv2_name...])
792

793
  """
794
  res = []
795
  for pvi in pvi_list:
796
    if len(pvi.lv_list) > 1:
797
      res.append((pvi.name, pvi.lv_list))
798
  return res
799

    
800

    
801
def _VerifyHypervisors(what, vm_capable, result, all_hvparams,
802
                       get_hv_fn=hypervisor.GetHypervisor):
803
  """Verifies the hypervisor. Appends the results to the 'results' list.
804

805
  @type what: C{dict}
806
  @param what: a dictionary of things to check
807
  @type vm_capable: boolean
808
  @param vm_capable: whether or not this node is vm capable
809
  @type result: dict
810
  @param result: dictionary of verification results; results of the
811
    verifications in this function will be added here
812
  @type all_hvparams: dict of dict of string
813
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
814
  @type get_hv_fn: function
815
  @param get_hv_fn: function to retrieve the hypervisor, to improve testability
816

817
  """
818
  if not vm_capable:
819
    return
820

    
821
  if constants.NV_HYPERVISOR in what:
822
    result[constants.NV_HYPERVISOR] = {}
823
    for hv_name in what[constants.NV_HYPERVISOR]:
824
      hvparams = all_hvparams[hv_name]
825
      try:
826
        val = get_hv_fn(hv_name).Verify(hvparams=hvparams)
827
      except errors.HypervisorError, err:
828
        val = "Error while checking hypervisor: %s" % str(err)
829
      result[constants.NV_HYPERVISOR][hv_name] = val
830

    
831

    
832
def _VerifyHvparams(what, vm_capable, result,
833
                    get_hv_fn=hypervisor.GetHypervisor):
834
  """Verifies the hvparams. Appends the results to the 'results' list.
835

836
  @type what: C{dict}
837
  @param what: a dictionary of things to check
838
  @type vm_capable: boolean
839
  @param vm_capable: whether or not this node is vm capable
840
  @type result: dict
841
  @param result: dictionary of verification results; results of the
842
    verifications in this function will be added here
843
  @type get_hv_fn: function
844
  @param get_hv_fn: function to retrieve the hypervisor, to improve testability
845

846
  """
847
  if not vm_capable:
848
    return
849

    
850
  if constants.NV_HVPARAMS in what:
851
    result[constants.NV_HVPARAMS] = []
852
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
853
      try:
854
        logging.info("Validating hv %s, %s", hv_name, hvparms)
855
        get_hv_fn(hv_name).ValidateParameters(hvparms)
856
      except errors.HypervisorError, err:
857
        result[constants.NV_HVPARAMS].append((source, hv_name, str(err)))
858

    
859

    
860
def _VerifyInstanceList(what, vm_capable, result, all_hvparams):
861
  """Verifies the instance list.
862

863
  @type what: C{dict}
864
  @param what: a dictionary of things to check
865
  @type vm_capable: boolean
866
  @param vm_capable: whether or not this node is vm capable
867
  @type result: dict
868
  @param result: dictionary of verification results; results of the
869
    verifications in this function will be added here
870
  @type all_hvparams: dict of dict of string
871
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
872

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

    
883

    
884
def _VerifyNodeInfo(what, vm_capable, result, all_hvparams):
885
  """Verifies the node info.
886

887
  @type what: C{dict}
888
  @param what: a dictionary of things to check
889
  @type vm_capable: boolean
890
  @param vm_capable: whether or not this node is vm capable
891
  @type result: dict
892
  @param result: dictionary of verification results; results of the
893
    verifications in this function will be added here
894
  @type all_hvparams: dict of dict of string
895
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
896

897
  """
898
  if constants.NV_HVINFO in what and vm_capable:
899
    hvname = what[constants.NV_HVINFO]
900
    hyper = hypervisor.GetHypervisor(hvname)
901
    hvparams = all_hvparams[hvname]
902
    result[constants.NV_HVINFO] = hyper.GetNodeInfo(hvparams=hvparams)
903

    
904

    
905
def VerifyNode(what, cluster_name, all_hvparams):
906
  """Verify the status of the local node.
907

908
  Based on the input L{what} parameter, various checks are done on the
909
  local node.
910

911
  If the I{filelist} key is present, this list of
912
  files is checksummed and the file/checksum pairs are returned.
913

914
  If the I{nodelist} key is present, we check that we have
915
  connectivity via ssh with the target nodes (and check the hostname
916
  report).
917

918
  If the I{node-net-test} key is present, we check that we have
919
  connectivity to the given nodes via both primary IP and, if
920
  applicable, secondary IPs.
921

922
  @type what: C{dict}
923
  @param what: a dictionary of things to check:
924
      - filelist: list of files for which to compute checksums
925
      - nodelist: list of nodes we should check ssh communication with
926
      - node-net-test: list of nodes we should check node daemon port
927
        connectivity with
928
      - hypervisor: list with hypervisors to run the verify for
929
  @type cluster_name: string
930
  @param cluster_name: the cluster's name
931
  @type all_hvparams: dict of dict of strings
932
  @param all_hvparams: a dictionary mapping hypervisor names to hvparams
933
  @rtype: dict
934
  @return: a dictionary with the same keys as the input dict, and
935
      values representing the result of the checks
936

937
  """
938
  result = {}
939
  my_name = netutils.Hostname.GetSysName()
940
  port = netutils.GetDaemonPort(constants.NODED)
941
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
942

    
943
  _VerifyHypervisors(what, vm_capable, result, all_hvparams)
944
  _VerifyHvparams(what, vm_capable, result)
945

    
946
  if constants.NV_FILELIST in what:
947
    fingerprints = utils.FingerprintFiles(map(vcluster.LocalizeVirtualPath,
948
                                              what[constants.NV_FILELIST]))
949
    result[constants.NV_FILELIST] = \
950
      dict((vcluster.MakeVirtualPath(key), value)
951
           for (key, value) in fingerprints.items())
952

    
953
  if constants.NV_NODELIST in what:
954
    (nodes, bynode) = what[constants.NV_NODELIST]
955

    
956
    # Add nodes from other groups (different for each node)
957
    try:
958
      nodes.extend(bynode[my_name])
959
    except KeyError:
960
      pass
961

    
962
    # Use a random order
963
    random.shuffle(nodes)
964

    
965
    # Try to contact all nodes
966
    val = {}
967
    for node in nodes:
968
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
969
      if not success:
970
        val[node] = message
971

    
972
    result[constants.NV_NODELIST] = val
973

    
974
  if constants.NV_NODENETTEST in what:
975
    result[constants.NV_NODENETTEST] = tmp = {}
976
    my_pip = my_sip = None
977
    for name, pip, sip in what[constants.NV_NODENETTEST]:
978
      if name == my_name:
979
        my_pip = pip
980
        my_sip = sip
981
        break
982
    if not my_pip:
983
      tmp[my_name] = ("Can't find my own primary/secondary IP"
984
                      " in the node list")
985
    else:
986
      for name, pip, sip in what[constants.NV_NODENETTEST]:
987
        fail = []
988
        if not netutils.TcpPing(pip, port, source=my_pip):
989
          fail.append("primary")
990
        if sip != pip:
991
          if not netutils.TcpPing(sip, port, source=my_sip):
992
            fail.append("secondary")
993
        if fail:
994
          tmp[name] = ("failure using the %s interface(s)" %
995
                       " and ".join(fail))
996

    
997
  if constants.NV_MASTERIP in what:
998
    # FIXME: add checks on incoming data structures (here and in the
999
    # rest of the function)
1000
    master_name, master_ip = what[constants.NV_MASTERIP]
1001
    if master_name == my_name:
1002
      source = constants.IP4_ADDRESS_LOCALHOST
1003
    else:
1004
      source = None
1005
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
1006
                                                     source=source)
1007

    
1008
  if constants.NV_USERSCRIPTS in what:
1009
    result[constants.NV_USERSCRIPTS] = \
1010
      [script for script in what[constants.NV_USERSCRIPTS]
1011
       if not utils.IsExecutable(script)]
1012

    
1013
  if constants.NV_OOB_PATHS in what:
1014
    result[constants.NV_OOB_PATHS] = tmp = []
1015
    for path in what[constants.NV_OOB_PATHS]:
1016
      try:
1017
        st = os.stat(path)
1018
      except OSError, err:
1019
        tmp.append("error stating out of band helper: %s" % err)
1020
      else:
1021
        if stat.S_ISREG(st.st_mode):
1022
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
1023
            tmp.append(None)
1024
          else:
1025
            tmp.append("out of band helper %s is not executable" % path)
1026
        else:
1027
          tmp.append("out of band helper %s is not a file" % path)
1028

    
1029
  if constants.NV_LVLIST in what and vm_capable:
1030
    try:
1031
      val = GetVolumeList(utils.ListVolumeGroups().keys())
1032
    except RPCFail, err:
1033
      val = str(err)
1034
    result[constants.NV_LVLIST] = val
1035

    
1036
  _VerifyInstanceList(what, vm_capable, result, all_hvparams)
1037

    
1038
  if constants.NV_VGLIST in what and vm_capable:
1039
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
1040

    
1041
  if constants.NV_PVLIST in what and vm_capable:
1042
    check_exclusive_pvs = constants.NV_EXCLUSIVEPVS in what
1043
    val = bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
1044
                                       filter_allocatable=False,
1045
                                       include_lvs=check_exclusive_pvs)
1046
    if check_exclusive_pvs:
1047
      result[constants.NV_EXCLUSIVEPVS] = _CheckExclusivePvs(val)
1048
      for pvi in val:
1049
        # Avoid sending useless data on the wire
1050
        pvi.lv_list = []
1051
    result[constants.NV_PVLIST] = map(objects.LvmPvInfo.ToDict, val)
1052

    
1053
  if constants.NV_VERSION in what:
1054
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
1055
                                    constants.RELEASE_VERSION)
1056

    
1057
  _VerifyNodeInfo(what, vm_capable, result, all_hvparams)
1058

    
1059
  if constants.NV_DRBDVERSION in what and vm_capable:
1060
    try:
1061
      drbd_version = DRBD8.GetProcInfo().GetVersionString()
1062
    except errors.BlockDeviceError, err:
1063
      logging.warning("Can't get DRBD version", exc_info=True)
1064
      drbd_version = str(err)
1065
    result[constants.NV_DRBDVERSION] = drbd_version
1066

    
1067
  if constants.NV_DRBDLIST in what and vm_capable:
1068
    try:
1069
      used_minors = drbd.DRBD8.GetUsedDevs()
1070
    except errors.BlockDeviceError, err:
1071
      logging.warning("Can't get used minors list", exc_info=True)
1072
      used_minors = str(err)
1073
    result[constants.NV_DRBDLIST] = used_minors
1074

    
1075
  if constants.NV_DRBDHELPER in what and vm_capable:
1076
    status = True
1077
    try:
1078
      payload = drbd.DRBD8.GetUsermodeHelper()
1079
    except errors.BlockDeviceError, err:
1080
      logging.error("Can't get DRBD usermode helper: %s", str(err))
1081
      status = False
1082
      payload = str(err)
1083
    result[constants.NV_DRBDHELPER] = (status, payload)
1084

    
1085
  if constants.NV_NODESETUP in what:
1086
    result[constants.NV_NODESETUP] = tmpr = []
1087
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
1088
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
1089
                  " under /sys, missing required directories /sys/block"
1090
                  " and /sys/class/net")
1091
    if (not os.path.isdir("/proc/sys") or
1092
        not os.path.isfile("/proc/sysrq-trigger")):
1093
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
1094
                  " under /proc, missing required directory /proc/sys and"
1095
                  " the file /proc/sysrq-trigger")
1096

    
1097
  if constants.NV_TIME in what:
1098
    result[constants.NV_TIME] = utils.SplitTime(time.time())
1099

    
1100
  if constants.NV_OSLIST in what and vm_capable:
1101
    result[constants.NV_OSLIST] = DiagnoseOS()
1102

    
1103
  if constants.NV_BRIDGES in what and vm_capable:
1104
    result[constants.NV_BRIDGES] = [bridge
1105
                                    for bridge in what[constants.NV_BRIDGES]
1106
                                    if not utils.BridgeExists(bridge)]
1107

    
1108
  if what.get(constants.NV_FILE_STORAGE_PATHS) == my_name:
1109
    result[constants.NV_FILE_STORAGE_PATHS] = \
1110
      bdev.ComputeWrongFileStoragePaths()
1111

    
1112
  return result
1113

    
1114

    
1115
def GetBlockDevSizes(devices):
1116
  """Return the size of the given block devices
1117

1118
  @type devices: list
1119
  @param devices: list of block device nodes to query
1120
  @rtype: dict
1121
  @return:
1122
    dictionary of all block devices under /dev (key). The value is their
1123
    size in MiB.
1124

1125
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
1126

1127
  """
1128
  DEV_PREFIX = "/dev/"
1129
  blockdevs = {}
1130

    
1131
  for devpath in devices:
1132
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
1133
      continue
1134

    
1135
    try:
1136
      st = os.stat(devpath)
1137
    except EnvironmentError, err:
1138
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
1139
      continue
1140

    
1141
    if stat.S_ISBLK(st.st_mode):
1142
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
1143
      if result.failed:
1144
        # We don't want to fail, just do not list this device as available
1145
        logging.warning("Cannot get size for block device %s", devpath)
1146
        continue
1147

    
1148
      size = int(result.stdout) / (1024 * 1024)
1149
      blockdevs[devpath] = size
1150
  return blockdevs
1151

    
1152

    
1153
def GetVolumeList(vg_names):
1154
  """Compute list of logical volumes and their size.
1155

1156
  @type vg_names: list
1157
  @param vg_names: the volume groups whose LVs we should list, or
1158
      empty for all volume groups
1159
  @rtype: dict
1160
  @return:
1161
      dictionary of all partions (key) with value being a tuple of
1162
      their size (in MiB), inactive and online status::
1163

1164
        {'xenvg/test1': ('20.06', True, True)}
1165

1166
      in case of errors, a string is returned with the error
1167
      details.
1168

1169
  """
1170
  lvs = {}
1171
  sep = "|"
1172
  if not vg_names:
1173
    vg_names = []
1174
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1175
                         "--separator=%s" % sep,
1176
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
1177
  if result.failed:
1178
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
1179

    
1180
  for line in result.stdout.splitlines():
1181
    line = line.strip()
1182
    match = _LVSLINE_REGEX.match(line)
1183
    if not match:
1184
      logging.error("Invalid line returned from lvs output: '%s'", line)
1185
      continue
1186
    vg_name, name, size, attr = match.groups()
1187
    inactive = attr[4] == "-"
1188
    online = attr[5] == "o"
1189
    virtual = attr[0] == "v"
1190
    if virtual:
1191
      # we don't want to report such volumes as existing, since they
1192
      # don't really hold data
1193
      continue
1194
    lvs[vg_name + "/" + name] = (size, inactive, online)
1195

    
1196
  return lvs
1197

    
1198

    
1199
def ListVolumeGroups():
1200
  """List the volume groups and their size.
1201

1202
  @rtype: dict
1203
  @return: dictionary with keys volume name and values the
1204
      size of the volume
1205

1206
  """
1207
  return utils.ListVolumeGroups()
1208

    
1209

    
1210
def NodeVolumes():
1211
  """List all volumes on this node.
1212

1213
  @rtype: list
1214
  @return:
1215
    A list of dictionaries, each having four keys:
1216
      - name: the logical volume name,
1217
      - size: the size of the logical volume
1218
      - dev: the physical device on which the LV lives
1219
      - vg: the volume group to which it belongs
1220

1221
    In case of errors, we return an empty list and log the
1222
    error.
1223

1224
    Note that since a logical volume can live on multiple physical
1225
    volumes, the resulting list might include a logical volume
1226
    multiple times.
1227

1228
  """
1229
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1230
                         "--separator=|",
1231
                         "--options=lv_name,lv_size,devices,vg_name"])
1232
  if result.failed:
1233
    _Fail("Failed to list logical volumes, lvs output: %s",
1234
          result.output)
1235

    
1236
  def parse_dev(dev):
1237
    return dev.split("(")[0]
1238

    
1239
  def handle_dev(dev):
1240
    return [parse_dev(x) for x in dev.split(",")]
1241

    
1242
  def map_line(line):
1243
    line = [v.strip() for v in line]
1244
    return [{"name": line[0], "size": line[1],
1245
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
1246

    
1247
  all_devs = []
1248
  for line in result.stdout.splitlines():
1249
    if line.count("|") >= 3:
1250
      all_devs.extend(map_line(line.split("|")))
1251
    else:
1252
      logging.warning("Strange line in the output from lvs: '%s'", line)
1253
  return all_devs
1254

    
1255

    
1256
def BridgesExist(bridges_list):
1257
  """Check if a list of bridges exist on the current node.
1258

1259
  @rtype: boolean
1260
  @return: C{True} if all of them exist, C{False} otherwise
1261

1262
  """
1263
  missing = []
1264
  for bridge in bridges_list:
1265
    if not utils.BridgeExists(bridge):
1266
      missing.append(bridge)
1267

    
1268
  if missing:
1269
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
1270

    
1271

    
1272
def GetInstanceListForHypervisor(hname, hvparams=None,
1273
                                 get_hv_fn=hypervisor.GetHypervisor):
1274
  """Provides a list of instances of the given hypervisor.
1275

1276
  @type hname: string
1277
  @param hname: name of the hypervisor
1278
  @type hvparams: dict of strings
1279
  @param hvparams: hypervisor parameters for the given hypervisor
1280
  @type get_hv_fn: function
1281
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1282
    name; optional parameter to increase testability
1283

1284
  @rtype: list
1285
  @return: a list of all running instances on the current node
1286
    - instance1.example.com
1287
    - instance2.example.com
1288

1289
  """
1290
  results = []
1291
  try:
1292
    hv = get_hv_fn(hname)
1293
    names = hv.ListInstances(hvparams=hvparams)
1294
    results.extend(names)
1295
  except errors.HypervisorError, err:
1296
    _Fail("Error enumerating instances (hypervisor %s): %s",
1297
          hname, err, exc=True)
1298
  return results
1299

    
1300

    
1301
def GetInstanceList(hypervisor_list, all_hvparams=None,
1302
                    get_hv_fn=hypervisor.GetHypervisor):
1303
  """Provides a list of instances.
1304

1305
  @type hypervisor_list: list
1306
  @param hypervisor_list: the list of hypervisors to query information
1307
  @type all_hvparams: dict of dict of strings
1308
  @param all_hvparams: a dictionary mapping hypervisor types to respective
1309
    cluster-wide hypervisor parameters
1310
  @type get_hv_fn: function
1311
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1312
    name; optional parameter to increase testability
1313

1314
  @rtype: list
1315
  @return: a list of all running instances on the current node
1316
    - instance1.example.com
1317
    - instance2.example.com
1318

1319
  """
1320
  results = []
1321
  for hname in hypervisor_list:
1322
    hvparams = all_hvparams[hname]
1323
    results.extend(GetInstanceListForHypervisor(hname, hvparams=hvparams,
1324
                                                get_hv_fn=get_hv_fn))
1325
  return results
1326

    
1327

    
1328
def GetInstanceInfo(instance, hname, hvparams=None):
1329
  """Gives back the information about an instance as a dictionary.
1330

1331
  @type instance: string
1332
  @param instance: the instance name
1333
  @type hname: string
1334
  @param hname: the hypervisor type of the instance
1335
  @type hvparams: dict of strings
1336
  @param hvparams: the instance's hvparams
1337

1338
  @rtype: dict
1339
  @return: dictionary with the following keys:
1340
      - memory: memory size of instance (int)
1341
      - state: xen state of instance (string)
1342
      - time: cpu time of instance (float)
1343
      - vcpus: the number of vcpus (int)
1344

1345
  """
1346
  output = {}
1347

    
1348
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance,
1349
                                                          hvparams=hvparams)
1350
  if iinfo is not None:
1351
    output["memory"] = iinfo[2]
1352
    output["vcpus"] = iinfo[3]
1353
    output["state"] = iinfo[4]
1354
    output["time"] = iinfo[5]
1355

    
1356
  return output
1357

    
1358

    
1359
def GetInstanceMigratable(instance):
1360
  """Computes whether an instance can be migrated.
1361

1362
  @type instance: L{objects.Instance}
1363
  @param instance: object representing the instance to be checked.
1364

1365
  @rtype: tuple
1366
  @return: tuple of (result, description) where:
1367
      - result: whether the instance can be migrated or not
1368
      - description: a description of the issue, if relevant
1369

1370
  """
1371
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1372
  iname = instance.name
1373
  if iname not in hyper.ListInstances(instance.hvparams):
1374
    _Fail("Instance %s is not running", iname)
1375

    
1376
  for idx in range(len(instance.disks)):
1377
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1378
    if not os.path.islink(link_name):
1379
      logging.warning("Instance %s is missing symlink %s for disk %d",
1380
                      iname, link_name, idx)
1381

    
1382

    
1383
def GetAllInstancesInfo(hypervisor_list, all_hvparams):
1384
  """Gather data about all instances.
1385

1386
  This is the equivalent of L{GetInstanceInfo}, except that it
1387
  computes data for all instances at once, thus being faster if one
1388
  needs data about more than one instance.
1389

1390
  @type hypervisor_list: list
1391
  @param hypervisor_list: list of hypervisors to query for instance data
1392
  @type all_hvparams: dict of dict of strings
1393
  @param all_hvparams: mapping of hypervisor names to hvparams
1394

1395
  @rtype: dict
1396
  @return: dictionary of instance: data, with data having the following keys:
1397
      - memory: memory size of instance (int)
1398
      - state: xen state of instance (string)
1399
      - time: cpu time of instance (float)
1400
      - vcpus: the number of vcpus
1401

1402
  """
1403
  output = {}
1404

    
1405
  for hname in hypervisor_list:
1406
    hvparams = all_hvparams[hname]
1407
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo(hvparams)
1408
    if iinfo:
1409
      for name, _, memory, vcpus, state, times in iinfo:
1410
        value = {
1411
          "memory": memory,
1412
          "vcpus": vcpus,
1413
          "state": state,
1414
          "time": times,
1415
          }
1416
        if name in output:
1417
          # we only check static parameters, like memory and vcpus,
1418
          # and not state and time which can change between the
1419
          # invocations of the different hypervisors
1420
          for key in "memory", "vcpus":
1421
            if value[key] != output[name][key]:
1422
              _Fail("Instance %s is running twice"
1423
                    " with different parameters", name)
1424
        output[name] = value
1425

    
1426
  return output
1427

    
1428

    
1429
def _InstanceLogName(kind, os_name, instance, component):
1430
  """Compute the OS log filename for a given instance and operation.
1431

1432
  The instance name and os name are passed in as strings since not all
1433
  operations have these as part of an instance object.
1434

1435
  @type kind: string
1436
  @param kind: the operation type (e.g. add, import, etc.)
1437
  @type os_name: string
1438
  @param os_name: the os name
1439
  @type instance: string
1440
  @param instance: the name of the instance being imported/added/etc.
1441
  @type component: string or None
1442
  @param component: the name of the component of the instance being
1443
      transferred
1444

1445
  """
1446
  # TODO: Use tempfile.mkstemp to create unique filename
1447
  if component:
1448
    assert "/" not in component
1449
    c_msg = "-%s" % component
1450
  else:
1451
    c_msg = ""
1452
  base = ("%s-%s-%s%s-%s.log" %
1453
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1454
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1455

    
1456

    
1457
def InstanceOsAdd(instance, reinstall, debug):
1458
  """Add an OS to an instance.
1459

1460
  @type instance: L{objects.Instance}
1461
  @param instance: Instance whose OS is to be installed
1462
  @type reinstall: boolean
1463
  @param reinstall: whether this is an instance reinstall
1464
  @type debug: integer
1465
  @param debug: debug level, passed to the OS scripts
1466
  @rtype: None
1467

1468
  """
1469
  inst_os = OSFromDisk(instance.os)
1470

    
1471
  create_env = OSEnvironment(instance, inst_os, debug)
1472
  if reinstall:
1473
    create_env["INSTANCE_REINSTALL"] = "1"
1474

    
1475
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1476

    
1477
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1478
                        cwd=inst_os.path, output=logfile, reset_env=True)
1479
  if result.failed:
1480
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1481
                  " output: %s", result.cmd, result.fail_reason, logfile,
1482
                  result.output)
1483
    lines = [utils.SafeEncode(val)
1484
             for val in utils.TailFile(logfile, lines=20)]
1485
    _Fail("OS create script failed (%s), last lines in the"
1486
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1487

    
1488

    
1489
def RunRenameInstance(instance, old_name, debug):
1490
  """Run the OS rename script for an instance.
1491

1492
  @type instance: L{objects.Instance}
1493
  @param instance: Instance whose OS is to be installed
1494
  @type old_name: string
1495
  @param old_name: previous instance name
1496
  @type debug: integer
1497
  @param debug: debug level, passed to the OS scripts
1498
  @rtype: boolean
1499
  @return: the success of the operation
1500

1501
  """
1502
  inst_os = OSFromDisk(instance.os)
1503

    
1504
  rename_env = OSEnvironment(instance, inst_os, debug)
1505
  rename_env["OLD_INSTANCE_NAME"] = old_name
1506

    
1507
  logfile = _InstanceLogName("rename", instance.os,
1508
                             "%s-%s" % (old_name, instance.name), None)
1509

    
1510
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1511
                        cwd=inst_os.path, output=logfile, reset_env=True)
1512

    
1513
  if result.failed:
1514
    logging.error("os create command '%s' returned error: %s output: %s",
1515
                  result.cmd, result.fail_reason, result.output)
1516
    lines = [utils.SafeEncode(val)
1517
             for val in utils.TailFile(logfile, lines=20)]
1518
    _Fail("OS rename script failed (%s), last lines in the"
1519
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1520

    
1521

    
1522
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1523
  """Returns symlink path for block device.
1524

1525
  """
1526
  if _dir is None:
1527
    _dir = pathutils.DISK_LINKS_DIR
1528

    
1529
  return utils.PathJoin(_dir,
1530
                        ("%s%s%s" %
1531
                         (instance_name, constants.DISK_SEPARATOR, idx)))
1532

    
1533

    
1534
def _SymlinkBlockDev(instance_name, device_path, idx):
1535
  """Set up symlinks to a instance's block device.
1536

1537
  This is an auxiliary function run when an instance is start (on the primary
1538
  node) or when an instance is migrated (on the target node).
1539

1540

1541
  @param instance_name: the name of the target instance
1542
  @param device_path: path of the physical block device, on the node
1543
  @param idx: the disk index
1544
  @return: absolute path to the disk's symlink
1545

1546
  """
1547
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1548
  try:
1549
    os.symlink(device_path, link_name)
1550
  except OSError, err:
1551
    if err.errno == errno.EEXIST:
1552
      if (not os.path.islink(link_name) or
1553
          os.readlink(link_name) != device_path):
1554
        os.remove(link_name)
1555
        os.symlink(device_path, link_name)
1556
    else:
1557
      raise
1558

    
1559
  return link_name
1560

    
1561

    
1562
def _RemoveBlockDevLinks(instance_name, disks):
1563
  """Remove the block device symlinks belonging to the given instance.
1564

1565
  """
1566
  for idx, _ in enumerate(disks):
1567
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1568
    if os.path.islink(link_name):
1569
      try:
1570
        os.remove(link_name)
1571
      except OSError:
1572
        logging.exception("Can't remove symlink '%s'", link_name)
1573

    
1574

    
1575
def _GatherAndLinkBlockDevs(instance):
1576
  """Set up an instance's block device(s).
1577

1578
  This is run on the primary node at instance startup. The block
1579
  devices must be already assembled.
1580

1581
  @type instance: L{objects.Instance}
1582
  @param instance: the instance whose disks we shoul assemble
1583
  @rtype: list
1584
  @return: list of (disk_object, device_path)
1585

1586
  """
1587
  block_devices = []
1588
  for idx, disk in enumerate(instance.disks):
1589
    device = _RecursiveFindBD(disk)
1590
    if device is None:
1591
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1592
                                    str(disk))
1593
    device.Open()
1594
    try:
1595
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1596
    except OSError, e:
1597
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1598
                                    e.strerror)
1599

    
1600
    block_devices.append((disk, link_name))
1601

    
1602
  return block_devices
1603

    
1604

    
1605
def StartInstance(instance, startup_paused, reason, store_reason=True):
1606
  """Start an instance.
1607

1608
  @type instance: L{objects.Instance}
1609
  @param instance: the instance object
1610
  @type startup_paused: bool
1611
  @param instance: pause instance at startup?
1612
  @type reason: list of reasons
1613
  @param reason: the reason trail for this startup
1614
  @type store_reason: boolean
1615
  @param store_reason: whether to store the shutdown reason trail on file
1616
  @rtype: None
1617

1618
  """
1619
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1620
                                                   instance.hvparams)
1621

    
1622
  if instance.name in running_instances:
1623
    logging.info("Instance %s already running, not starting", instance.name)
1624
    return
1625

    
1626
  try:
1627
    block_devices = _GatherAndLinkBlockDevs(instance)
1628
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1629
    hyper.StartInstance(instance, block_devices, startup_paused)
1630
    if store_reason:
1631
      _StoreInstReasonTrail(instance.name, reason)
1632
  except errors.BlockDeviceError, err:
1633
    _Fail("Block device error: %s", err, exc=True)
1634
  except errors.HypervisorError, err:
1635
    _RemoveBlockDevLinks(instance.name, instance.disks)
1636
    _Fail("Hypervisor error: %s", err, exc=True)
1637

    
1638

    
1639
def InstanceShutdown(instance, timeout, reason, store_reason=True):
1640
  """Shut an instance down.
1641

1642
  @note: this functions uses polling with a hardcoded timeout.
1643

1644
  @type instance: L{objects.Instance}
1645
  @param instance: the instance object
1646
  @type timeout: integer
1647
  @param timeout: maximum timeout for soft shutdown
1648
  @type reason: list of reasons
1649
  @param reason: the reason trail for this shutdown
1650
  @type store_reason: boolean
1651
  @param store_reason: whether to store the shutdown reason trail on file
1652
  @rtype: None
1653

1654
  """
1655
  hv_name = instance.hypervisor
1656
  hyper = hypervisor.GetHypervisor(hv_name)
1657
  iname = instance.name
1658

    
1659
  if instance.name not in hyper.ListInstances(instance.hvparams):
1660
    logging.info("Instance %s not running, doing nothing", iname)
1661
    return
1662

    
1663
  class _TryShutdown:
1664
    def __init__(self):
1665
      self.tried_once = False
1666

    
1667
    def __call__(self):
1668
      if iname not in hyper.ListInstances(instance.hvparams):
1669
        return
1670

    
1671
      try:
1672
        hyper.StopInstance(instance, retry=self.tried_once)
1673
        if store_reason:
1674
          _StoreInstReasonTrail(instance.name, reason)
1675
      except errors.HypervisorError, err:
1676
        if iname not in hyper.ListInstances(instance.hvparams):
1677
          # if the instance is no longer existing, consider this a
1678
          # success and go to cleanup
1679
          return
1680

    
1681
        _Fail("Failed to stop instance %s: %s", iname, err)
1682

    
1683
      self.tried_once = True
1684

    
1685
      raise utils.RetryAgain()
1686

    
1687
  try:
1688
    utils.Retry(_TryShutdown(), 5, timeout)
1689
  except utils.RetryTimeout:
1690
    # the shutdown did not succeed
1691
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1692

    
1693
    try:
1694
      hyper.StopInstance(instance, force=True)
1695
    except errors.HypervisorError, err:
1696
      if iname in hyper.ListInstances(instance.hvparams):
1697
        # only raise an error if the instance still exists, otherwise
1698
        # the error could simply be "instance ... unknown"!
1699
        _Fail("Failed to force stop instance %s: %s", iname, err)
1700

    
1701
    time.sleep(1)
1702

    
1703
    if iname in hyper.ListInstances(instance.hvparams):
1704
      _Fail("Could not shutdown instance %s even by destroy", iname)
1705

    
1706
  try:
1707
    hyper.CleanupInstance(instance.name)
1708
  except errors.HypervisorError, err:
1709
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1710

    
1711
  _RemoveBlockDevLinks(iname, instance.disks)
1712

    
1713

    
1714
def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1715
  """Reboot an instance.
1716

1717
  @type instance: L{objects.Instance}
1718
  @param instance: the instance object to reboot
1719
  @type reboot_type: str
1720
  @param reboot_type: the type of reboot, one the following
1721
    constants:
1722
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1723
        instance OS, do not recreate the VM
1724
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1725
        restart the VM (at the hypervisor level)
1726
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1727
        not accepted here, since that mode is handled differently, in
1728
        cmdlib, and translates into full stop and start of the
1729
        instance (instead of a call_instance_reboot RPC)
1730
  @type shutdown_timeout: integer
1731
  @param shutdown_timeout: maximum timeout for soft shutdown
1732
  @type reason: list of reasons
1733
  @param reason: the reason trail for this reboot
1734
  @rtype: None
1735

1736
  """
1737
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1738
                                                   instance.hvparams)
1739

    
1740
  if instance.name not in running_instances:
1741
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1742

    
1743
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1744
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1745
    try:
1746
      hyper.RebootInstance(instance)
1747
    except errors.HypervisorError, err:
1748
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1749
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1750
    try:
1751
      InstanceShutdown(instance, shutdown_timeout, reason, store_reason=False)
1752
      result = StartInstance(instance, False, reason, store_reason=False)
1753
      _StoreInstReasonTrail(instance.name, reason)
1754
      return result
1755
    except errors.HypervisorError, err:
1756
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1757
  else:
1758
    _Fail("Invalid reboot_type received: %s", reboot_type)
1759

    
1760

    
1761
def InstanceBalloonMemory(instance, memory):
1762
  """Resize an instance's memory.
1763

1764
  @type instance: L{objects.Instance}
1765
  @param instance: the instance object
1766
  @type memory: int
1767
  @param memory: new memory amount in MB
1768
  @rtype: None
1769

1770
  """
1771
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1772
  running = hyper.ListInstances(instance.hvparams)
1773
  if instance.name not in running:
1774
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1775
    return
1776
  try:
1777
    hyper.BalloonInstanceMemory(instance, memory)
1778
  except errors.HypervisorError, err:
1779
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1780

    
1781

    
1782
def MigrationInfo(instance):
1783
  """Gather information about an instance to be migrated.
1784

1785
  @type instance: L{objects.Instance}
1786
  @param instance: the instance definition
1787

1788
  """
1789
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1790
  try:
1791
    info = hyper.MigrationInfo(instance)
1792
  except errors.HypervisorError, err:
1793
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1794
  return info
1795

    
1796

    
1797
def AcceptInstance(instance, info, target):
1798
  """Prepare the node to accept an instance.
1799

1800
  @type instance: L{objects.Instance}
1801
  @param instance: the instance definition
1802
  @type info: string/data (opaque)
1803
  @param info: migration information, from the source node
1804
  @type target: string
1805
  @param target: target host (usually ip), on this node
1806

1807
  """
1808
  # TODO: why is this required only for DTS_EXT_MIRROR?
1809
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1810
    # Create the symlinks, as the disks are not active
1811
    # in any way
1812
    try:
1813
      _GatherAndLinkBlockDevs(instance)
1814
    except errors.BlockDeviceError, err:
1815
      _Fail("Block device error: %s", err, exc=True)
1816

    
1817
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1818
  try:
1819
    hyper.AcceptInstance(instance, info, target)
1820
  except errors.HypervisorError, err:
1821
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1822
      _RemoveBlockDevLinks(instance.name, instance.disks)
1823
    _Fail("Failed to accept instance: %s", err, exc=True)
1824

    
1825

    
1826
def FinalizeMigrationDst(instance, info, success):
1827
  """Finalize any preparation to accept an instance.
1828

1829
  @type instance: L{objects.Instance}
1830
  @param instance: the instance definition
1831
  @type info: string/data (opaque)
1832
  @param info: migration information, from the source node
1833
  @type success: boolean
1834
  @param success: whether the migration was a success or a failure
1835

1836
  """
1837
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1838
  try:
1839
    hyper.FinalizeMigrationDst(instance, info, success)
1840
  except errors.HypervisorError, err:
1841
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1842

    
1843

    
1844
def MigrateInstance(cluster_name, instance, target, live):
1845
  """Migrates an instance to another node.
1846

1847
  @type cluster_name: string
1848
  @param cluster_name: name of the cluster
1849
  @type instance: L{objects.Instance}
1850
  @param instance: the instance definition
1851
  @type target: string
1852
  @param target: the target node name
1853
  @type live: boolean
1854
  @param live: whether the migration should be done live or not (the
1855
      interpretation of this parameter is left to the hypervisor)
1856
  @raise RPCFail: if migration fails for some reason
1857

1858
  """
1859
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1860

    
1861
  try:
1862
    hyper.MigrateInstance(cluster_name, instance, target, live)
1863
  except errors.HypervisorError, err:
1864
    _Fail("Failed to migrate instance: %s", err, exc=True)
1865

    
1866

    
1867
def FinalizeMigrationSource(instance, success, live):
1868
  """Finalize the instance migration on the source node.
1869

1870
  @type instance: L{objects.Instance}
1871
  @param instance: the instance definition of the migrated instance
1872
  @type success: bool
1873
  @param success: whether the migration succeeded or not
1874
  @type live: bool
1875
  @param live: whether the user requested a live migration or not
1876
  @raise RPCFail: If the execution fails for some reason
1877

1878
  """
1879
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1880

    
1881
  try:
1882
    hyper.FinalizeMigrationSource(instance, success, live)
1883
  except Exception, err:  # pylint: disable=W0703
1884
    _Fail("Failed to finalize the migration on the source node: %s", err,
1885
          exc=True)
1886

    
1887

    
1888
def GetMigrationStatus(instance):
1889
  """Get the migration status
1890

1891
  @type instance: L{objects.Instance}
1892
  @param instance: the instance that is being migrated
1893
  @rtype: L{objects.MigrationStatus}
1894
  @return: the status of the current migration (one of
1895
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1896
           progress info that can be retrieved from the hypervisor
1897
  @raise RPCFail: If the migration status cannot be retrieved
1898

1899
  """
1900
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1901
  try:
1902
    return hyper.GetMigrationStatus(instance)
1903
  except Exception, err:  # pylint: disable=W0703
1904
    _Fail("Failed to get migration status: %s", err, exc=True)
1905

    
1906

    
1907
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
1908
  """Creates a block device for an instance.
1909

1910
  @type disk: L{objects.Disk}
1911
  @param disk: the object describing the disk we should create
1912
  @type size: int
1913
  @param size: the size of the physical underlying device, in MiB
1914
  @type owner: str
1915
  @param owner: the name of the instance for which disk is created,
1916
      used for device cache data
1917
  @type on_primary: boolean
1918
  @param on_primary:  indicates if it is the primary node or not
1919
  @type info: string
1920
  @param info: string that will be sent to the physical device
1921
      creation, used for example to set (LVM) tags on LVs
1922
  @type excl_stor: boolean
1923
  @param excl_stor: Whether exclusive_storage is active
1924

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

1929
  """
1930
  # TODO: remove the obsolete "size" argument
1931
  # pylint: disable=W0613
1932
  clist = []
1933
  if disk.children:
1934
    for child in disk.children:
1935
      try:
1936
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1937
      except errors.BlockDeviceError, err:
1938
        _Fail("Can't assemble device %s: %s", child, err)
1939
      if on_primary or disk.AssembleOnSecondary():
1940
        # we need the children open in case the device itself has to
1941
        # be assembled
1942
        try:
1943
          # pylint: disable=E1103
1944
          crdev.Open()
1945
        except errors.BlockDeviceError, err:
1946
          _Fail("Can't make child '%s' read-write: %s", child, err)
1947
      clist.append(crdev)
1948

    
1949
  try:
1950
    device = bdev.Create(disk, clist, excl_stor)
1951
  except errors.BlockDeviceError, err:
1952
    _Fail("Can't create block device: %s", err)
1953

    
1954
  if on_primary or disk.AssembleOnSecondary():
1955
    try:
1956
      device.Assemble()
1957
    except errors.BlockDeviceError, err:
1958
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1959
    if on_primary or disk.OpenOnSecondary():
1960
      try:
1961
        device.Open(force=True)
1962
      except errors.BlockDeviceError, err:
1963
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1964
    DevCacheManager.UpdateCache(device.dev_path, owner,
1965
                                on_primary, disk.iv_name)
1966

    
1967
  device.SetInfo(info)
1968

    
1969
  return device.unique_id
1970

    
1971

    
1972
def _WipeDevice(path, offset, size):
1973
  """This function actually wipes the device.
1974

1975
  @param path: The path to the device to wipe
1976
  @param offset: The offset in MiB in the file
1977
  @param size: The size in MiB to write
1978

1979
  """
1980
  # Internal sizes are always in Mebibytes; if the following "dd" command
1981
  # should use a different block size the offset and size given to this
1982
  # function must be adjusted accordingly before being passed to "dd".
1983
  block_size = 1024 * 1024
1984

    
1985
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1986
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
1987
         "count=%d" % size]
1988
  result = utils.RunCmd(cmd)
1989

    
1990
  if result.failed:
1991
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1992
          result.fail_reason, result.output)
1993

    
1994

    
1995
def BlockdevWipe(disk, offset, size):
1996
  """Wipes a block device.
1997

1998
  @type disk: L{objects.Disk}
1999
  @param disk: the disk object we want to wipe
2000
  @type offset: int
2001
  @param offset: The offset in MiB in the file
2002
  @type size: int
2003
  @param size: The size in MiB to write
2004

2005
  """
2006
  try:
2007
    rdev = _RecursiveFindBD(disk)
2008
  except errors.BlockDeviceError:
2009
    rdev = None
2010

    
2011
  if not rdev:
2012
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
2013

    
2014
  # Do cross verify some of the parameters
2015
  if offset < 0:
2016
    _Fail("Negative offset")
2017
  if size < 0:
2018
    _Fail("Negative size")
2019
  if offset > rdev.size:
2020
    _Fail("Offset is bigger than device size")
2021
  if (offset + size) > rdev.size:
2022
    _Fail("The provided offset and size to wipe is bigger than device size")
2023

    
2024
  _WipeDevice(rdev.dev_path, offset, size)
2025

    
2026

    
2027
def BlockdevPauseResumeSync(disks, pause):
2028
  """Pause or resume the sync of the block device.
2029

2030
  @type disks: list of L{objects.Disk}
2031
  @param disks: the disks object we want to pause/resume
2032
  @type pause: bool
2033
  @param pause: Wheater to pause or resume
2034

2035
  """
2036
  success = []
2037
  for disk in disks:
2038
    try:
2039
      rdev = _RecursiveFindBD(disk)
2040
    except errors.BlockDeviceError:
2041
      rdev = None
2042

    
2043
    if not rdev:
2044
      success.append((False, ("Cannot change sync for device %s:"
2045
                              " device not found" % disk.iv_name)))
2046
      continue
2047

    
2048
    result = rdev.PauseResumeSync(pause)
2049

    
2050
    if result:
2051
      success.append((result, None))
2052
    else:
2053
      if pause:
2054
        msg = "Pause"
2055
      else:
2056
        msg = "Resume"
2057
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
2058

    
2059
  return success
2060

    
2061

    
2062
def BlockdevRemove(disk):
2063
  """Remove a block device.
2064

2065
  @note: This is intended to be called recursively.
2066

2067
  @type disk: L{objects.Disk}
2068
  @param disk: the disk object we should remove
2069
  @rtype: boolean
2070
  @return: the success of the operation
2071

2072
  """
2073
  msgs = []
2074
  try:
2075
    rdev = _RecursiveFindBD(disk)
2076
  except errors.BlockDeviceError, err:
2077
    # probably can't attach
2078
    logging.info("Can't attach to device %s in remove", disk)
2079
    rdev = None
2080
  if rdev is not None:
2081
    r_path = rdev.dev_path
2082
    try:
2083
      rdev.Remove()
2084
    except errors.BlockDeviceError, err:
2085
      msgs.append(str(err))
2086
    if not msgs:
2087
      DevCacheManager.RemoveCache(r_path)
2088

    
2089
  if disk.children:
2090
    for child in disk.children:
2091
      try:
2092
        BlockdevRemove(child)
2093
      except RPCFail, err:
2094
        msgs.append(str(err))
2095

    
2096
  if msgs:
2097
    _Fail("; ".join(msgs))
2098

    
2099

    
2100
def _RecursiveAssembleBD(disk, owner, as_primary):
2101
  """Activate a block device for an instance.
2102

2103
  This is run on the primary and secondary nodes for an instance.
2104

2105
  @note: this function is called recursively.
2106

2107
  @type disk: L{objects.Disk}
2108
  @param disk: the disk we try to assemble
2109
  @type owner: str
2110
  @param owner: the name of the instance which owns the disk
2111
  @type as_primary: boolean
2112
  @param as_primary: if we should make the block device
2113
      read/write
2114

2115
  @return: the assembled device or None (in case no device
2116
      was assembled)
2117
  @raise errors.BlockDeviceError: in case there is an error
2118
      during the activation of the children or the device
2119
      itself
2120

2121
  """
2122
  children = []
2123
  if disk.children:
2124
    mcn = disk.ChildrenNeeded()
2125
    if mcn == -1:
2126
      mcn = 0 # max number of Nones allowed
2127
    else:
2128
      mcn = len(disk.children) - mcn # max number of Nones
2129
    for chld_disk in disk.children:
2130
      try:
2131
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
2132
      except errors.BlockDeviceError, err:
2133
        if children.count(None) >= mcn:
2134
          raise
2135
        cdev = None
2136
        logging.error("Error in child activation (but continuing): %s",
2137
                      str(err))
2138
      children.append(cdev)
2139

    
2140
  if as_primary or disk.AssembleOnSecondary():
2141
    r_dev = bdev.Assemble(disk, children)
2142
    result = r_dev
2143
    if as_primary or disk.OpenOnSecondary():
2144
      r_dev.Open()
2145
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
2146
                                as_primary, disk.iv_name)
2147

    
2148
  else:
2149
    result = True
2150
  return result
2151

    
2152

    
2153
def BlockdevAssemble(disk, owner, as_primary, idx):
2154
  """Activate a block device for an instance.
2155

2156
  This is a wrapper over _RecursiveAssembleBD.
2157

2158
  @rtype: str or boolean
2159
  @return: a C{/dev/...} path for primary nodes, and
2160
      C{True} for secondary nodes
2161

2162
  """
2163
  try:
2164
    result = _RecursiveAssembleBD(disk, owner, as_primary)
2165
    if isinstance(result, BlockDev):
2166
      # pylint: disable=E1103
2167
      result = result.dev_path
2168
      if as_primary:
2169
        _SymlinkBlockDev(owner, result, idx)
2170
  except errors.BlockDeviceError, err:
2171
    _Fail("Error while assembling disk: %s", err, exc=True)
2172
  except OSError, err:
2173
    _Fail("Error while symlinking disk: %s", err, exc=True)
2174

    
2175
  return result
2176

    
2177

    
2178
def BlockdevShutdown(disk):
2179
  """Shut down a block device.
2180

2181
  First, if the device is assembled (Attach() is successful), then
2182
  the device is shutdown. Then the children of the device are
2183
  shutdown.
2184

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

2189
  @type disk: L{objects.Disk}
2190
  @param disk: the description of the disk we should
2191
      shutdown
2192
  @rtype: None
2193

2194
  """
2195
  msgs = []
2196
  r_dev = _RecursiveFindBD(disk)
2197
  if r_dev is not None:
2198
    r_path = r_dev.dev_path
2199
    try:
2200
      r_dev.Shutdown()
2201
      DevCacheManager.RemoveCache(r_path)
2202
    except errors.BlockDeviceError, err:
2203
      msgs.append(str(err))
2204

    
2205
  if disk.children:
2206
    for child in disk.children:
2207
      try:
2208
        BlockdevShutdown(child)
2209
      except RPCFail, err:
2210
        msgs.append(str(err))
2211

    
2212
  if msgs:
2213
    _Fail("; ".join(msgs))
2214

    
2215

    
2216
def BlockdevAddchildren(parent_cdev, new_cdevs):
2217
  """Extend a mirrored block device.
2218

2219
  @type parent_cdev: L{objects.Disk}
2220
  @param parent_cdev: the disk to which we should add children
2221
  @type new_cdevs: list of L{objects.Disk}
2222
  @param new_cdevs: the list of children which we should add
2223
  @rtype: None
2224

2225
  """
2226
  parent_bdev = _RecursiveFindBD(parent_cdev)
2227
  if parent_bdev is None:
2228
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
2229
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
2230
  if new_bdevs.count(None) > 0:
2231
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
2232
  parent_bdev.AddChildren(new_bdevs)
2233

    
2234

    
2235
def BlockdevRemovechildren(parent_cdev, new_cdevs):
2236
  """Shrink a mirrored block device.
2237

2238
  @type parent_cdev: L{objects.Disk}
2239
  @param parent_cdev: the disk from which we should remove children
2240
  @type new_cdevs: list of L{objects.Disk}
2241
  @param new_cdevs: the list of children which we should remove
2242
  @rtype: None
2243

2244
  """
2245
  parent_bdev = _RecursiveFindBD(parent_cdev)
2246
  if parent_bdev is None:
2247
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
2248
  devs = []
2249
  for disk in new_cdevs:
2250
    rpath = disk.StaticDevPath()
2251
    if rpath is None:
2252
      bd = _RecursiveFindBD(disk)
2253
      if bd is None:
2254
        _Fail("Can't find device %s while removing children", disk)
2255
      else:
2256
        devs.append(bd.dev_path)
2257
    else:
2258
      if not utils.IsNormAbsPath(rpath):
2259
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
2260
      devs.append(rpath)
2261
  parent_bdev.RemoveChildren(devs)
2262

    
2263

    
2264
def BlockdevGetmirrorstatus(disks):
2265
  """Get the mirroring status of a list of devices.
2266

2267
  @type disks: list of L{objects.Disk}
2268
  @param disks: the list of disks which we should query
2269
  @rtype: disk
2270
  @return: List of L{objects.BlockDevStatus}, one for each disk
2271
  @raise errors.BlockDeviceError: if any of the disks cannot be
2272
      found
2273

2274
  """
2275
  stats = []
2276
  for dsk in disks:
2277
    rbd = _RecursiveFindBD(dsk)
2278
    if rbd is None:
2279
      _Fail("Can't find device %s", dsk)
2280

    
2281
    stats.append(rbd.CombinedSyncStatus())
2282

    
2283
  return stats
2284

    
2285

    
2286
def BlockdevGetmirrorstatusMulti(disks):
2287
  """Get the mirroring status of a list of devices.
2288

2289
  @type disks: list of L{objects.Disk}
2290
  @param disks: the list of disks which we should query
2291
  @rtype: disk
2292
  @return: List of tuples, (bool, status), one for each disk; bool denotes
2293
    success/failure, status is L{objects.BlockDevStatus} on success, string
2294
    otherwise
2295

2296
  """
2297
  result = []
2298
  for disk in disks:
2299
    try:
2300
      rbd = _RecursiveFindBD(disk)
2301
      if rbd is None:
2302
        result.append((False, "Can't find device %s" % disk))
2303
        continue
2304

    
2305
      status = rbd.CombinedSyncStatus()
2306
    except errors.BlockDeviceError, err:
2307
      logging.exception("Error while getting disk status")
2308
      result.append((False, str(err)))
2309
    else:
2310
      result.append((True, status))
2311

    
2312
  assert len(disks) == len(result)
2313

    
2314
  return result
2315

    
2316

    
2317
def _RecursiveFindBD(disk):
2318
  """Check if a device is activated.
2319

2320
  If so, return information about the real device.
2321

2322
  @type disk: L{objects.Disk}
2323
  @param disk: the disk object we need to find
2324

2325
  @return: None if the device can't be found,
2326
      otherwise the device instance
2327

2328
  """
2329
  children = []
2330
  if disk.children:
2331
    for chdisk in disk.children:
2332
      children.append(_RecursiveFindBD(chdisk))
2333

    
2334
  return bdev.FindDevice(disk, children)
2335

    
2336

    
2337
def _OpenRealBD(disk):
2338
  """Opens the underlying block device of a disk.
2339

2340
  @type disk: L{objects.Disk}
2341
  @param disk: the disk object we want to open
2342

2343
  """
2344
  real_disk = _RecursiveFindBD(disk)
2345
  if real_disk is None:
2346
    _Fail("Block device '%s' is not set up", disk)
2347

    
2348
  real_disk.Open()
2349

    
2350
  return real_disk
2351

    
2352

    
2353
def BlockdevFind(disk):
2354
  """Check if a device is activated.
2355

2356
  If it is, return information about the real device.
2357

2358
  @type disk: L{objects.Disk}
2359
  @param disk: the disk to find
2360
  @rtype: None or objects.BlockDevStatus
2361
  @return: None if the disk cannot be found, otherwise a the current
2362
           information
2363

2364
  """
2365
  try:
2366
    rbd = _RecursiveFindBD(disk)
2367
  except errors.BlockDeviceError, err:
2368
    _Fail("Failed to find device: %s", err, exc=True)
2369

    
2370
  if rbd is None:
2371
    return None
2372

    
2373
  return rbd.GetSyncStatus()
2374

    
2375

    
2376
def BlockdevGetdimensions(disks):
2377
  """Computes the size of the given disks.
2378

2379
  If a disk is not found, returns None instead.
2380

2381
  @type disks: list of L{objects.Disk}
2382
  @param disks: the list of disk to compute the size for
2383
  @rtype: list
2384
  @return: list with elements None if the disk cannot be found,
2385
      otherwise the pair (size, spindles), where spindles is None if the
2386
      device doesn't support that
2387

2388
  """
2389
  result = []
2390
  for cf in disks:
2391
    try:
2392
      rbd = _RecursiveFindBD(cf)
2393
    except errors.BlockDeviceError:
2394
      result.append(None)
2395
      continue
2396
    if rbd is None:
2397
      result.append(None)
2398
    else:
2399
      result.append(rbd.GetActualDimensions())
2400
  return result
2401

    
2402

    
2403
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2404
  """Export a block device to a remote node.
2405

2406
  @type disk: L{objects.Disk}
2407
  @param disk: the description of the disk to export
2408
  @type dest_node: str
2409
  @param dest_node: the destination node to export to
2410
  @type dest_path: str
2411
  @param dest_path: the destination path on the target node
2412
  @type cluster_name: str
2413
  @param cluster_name: the cluster name, needed for SSH hostalias
2414
  @rtype: None
2415

2416
  """
2417
  real_disk = _OpenRealBD(disk)
2418

    
2419
  # the block size on the read dd is 1MiB to match our units
2420
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2421
                               "dd if=%s bs=1048576 count=%s",
2422
                               real_disk.dev_path, str(disk.size))
2423

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

    
2433
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2434
                                                   constants.SSH_LOGIN_USER,
2435
                                                   destcmd)
2436

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

    
2440
  result = utils.RunCmd(["bash", "-c", command])
2441

    
2442
  if result.failed:
2443
    _Fail("Disk copy command '%s' returned error: %s"
2444
          " output: %s", command, result.fail_reason, result.output)
2445

    
2446

    
2447
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2448
  """Write a file to the filesystem.
2449

2450
  This allows the master to overwrite(!) a file. It will only perform
2451
  the operation if the file belongs to a list of configuration files.
2452

2453
  @type file_name: str
2454
  @param file_name: the target file name
2455
  @type data: str
2456
  @param data: the new contents of the file
2457
  @type mode: int
2458
  @param mode: the mode to give the file (can be None)
2459
  @type uid: string
2460
  @param uid: the owner of the file
2461
  @type gid: string
2462
  @param gid: the group of the file
2463
  @type atime: float
2464
  @param atime: the atime to set on the file (can be None)
2465
  @type mtime: float
2466
  @param mtime: the mtime to set on the file (can be None)
2467
  @rtype: None
2468

2469
  """
2470
  file_name = vcluster.LocalizeVirtualPath(file_name)
2471

    
2472
  if not os.path.isabs(file_name):
2473
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2474

    
2475
  if file_name not in _ALLOWED_UPLOAD_FILES:
2476
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2477
          file_name)
2478

    
2479
  raw_data = _Decompress(data)
2480

    
2481
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2482
    _Fail("Invalid username/groupname type")
2483

    
2484
  getents = runtime.GetEnts()
2485
  uid = getents.LookupUser(uid)
2486
  gid = getents.LookupGroup(gid)
2487

    
2488
  utils.SafeWriteFile(file_name, None,
2489
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2490
                      atime=atime, mtime=mtime)
2491

    
2492

    
2493
def RunOob(oob_program, command, node, timeout):
2494
  """Executes oob_program with given command on given node.
2495

2496
  @param oob_program: The path to the executable oob_program
2497
  @param command: The command to invoke on oob_program
2498
  @param node: The node given as an argument to the program
2499
  @param timeout: Timeout after which we kill the oob program
2500

2501
  @return: stdout
2502
  @raise RPCFail: If execution fails for some reason
2503

2504
  """
2505
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2506

    
2507
  if result.failed:
2508
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2509
          result.fail_reason, result.output)
2510

    
2511
  return result.stdout
2512

    
2513

    
2514
def _OSOndiskAPIVersion(os_dir):
2515
  """Compute and return the API version of a given OS.
2516

2517
  This function will try to read the API version of the OS residing in
2518
  the 'os_dir' directory.
2519

2520
  @type os_dir: str
2521
  @param os_dir: the directory in which we should look for the OS
2522
  @rtype: tuple
2523
  @return: tuple (status, data) with status denoting the validity and
2524
      data holding either the vaid versions or an error message
2525

2526
  """
2527
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2528

    
2529
  try:
2530
    st = os.stat(api_file)
2531
  except EnvironmentError, err:
2532
    return False, ("Required file '%s' not found under path %s: %s" %
2533
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2534

    
2535
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2536
    return False, ("File '%s' in %s is not a regular file" %
2537
                   (constants.OS_API_FILE, os_dir))
2538

    
2539
  try:
2540
    api_versions = utils.ReadFile(api_file).splitlines()
2541
  except EnvironmentError, err:
2542
    return False, ("Error while reading the API version file at %s: %s" %
2543
                   (api_file, utils.ErrnoOrStr(err)))
2544

    
2545
  try:
2546
    api_versions = [int(version.strip()) for version in api_versions]
2547
  except (TypeError, ValueError), err:
2548
    return False, ("API version(s) can't be converted to integer: %s" %
2549
                   str(err))
2550

    
2551
  return True, api_versions
2552

    
2553

    
2554
def DiagnoseOS(top_dirs=None):
2555
  """Compute the validity for all OSes.
2556

2557
  @type top_dirs: list
2558
  @param top_dirs: the list of directories in which to
2559
      search (if not given defaults to
2560
      L{pathutils.OS_SEARCH_PATH})
2561
  @rtype: list of L{objects.OS}
2562
  @return: a list of tuples (name, path, status, diagnose, variants,
2563
      parameters, api_version) for all (potential) OSes under all
2564
      search paths, where:
2565
          - name is the (potential) OS name
2566
          - path is the full path to the OS
2567
          - status True/False is the validity of the OS
2568
          - diagnose is the error message for an invalid OS, otherwise empty
2569
          - variants is a list of supported OS variants, if any
2570
          - parameters is a list of (name, help) parameters, if any
2571
          - api_version is a list of support OS API versions
2572

2573
  """
2574
  if top_dirs is None:
2575
    top_dirs = pathutils.OS_SEARCH_PATH
2576

    
2577
  result = []
2578
  for dir_name in top_dirs:
2579
    if os.path.isdir(dir_name):
2580
      try:
2581
        f_names = utils.ListVisibleFiles(dir_name)
2582
      except EnvironmentError, err:
2583
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2584
        break
2585
      for name in f_names:
2586
        os_path = utils.PathJoin(dir_name, name)
2587
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2588
        if status:
2589
          diagnose = ""
2590
          variants = os_inst.supported_variants
2591
          parameters = os_inst.supported_parameters
2592
          api_versions = os_inst.api_versions
2593
        else:
2594
          diagnose = os_inst
2595
          variants = parameters = api_versions = []
2596
        result.append((name, os_path, status, diagnose, variants,
2597
                       parameters, api_versions))
2598

    
2599
  return result
2600

    
2601

    
2602
def _TryOSFromDisk(name, base_dir=None):
2603
  """Create an OS instance from disk.
2604

2605
  This function will return an OS instance if the given name is a
2606
  valid OS name.
2607

2608
  @type base_dir: string
2609
  @keyword base_dir: Base directory containing OS installations.
2610
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2611
  @rtype: tuple
2612
  @return: success and either the OS instance if we find a valid one,
2613
      or error message
2614

2615
  """
2616
  if base_dir is None:
2617
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2618
  else:
2619
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2620

    
2621
  if os_dir is None:
2622
    return False, "Directory for OS %s not found in search path" % name
2623

    
2624
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2625
  if not status:
2626
    # push the error up
2627
    return status, api_versions
2628

    
2629
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2630
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2631
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2632

    
2633
  # OS Files dictionary, we will populate it with the absolute path
2634
  # names; if the value is True, then it is a required file, otherwise
2635
  # an optional one
2636
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2637

    
2638
  if max(api_versions) >= constants.OS_API_V15:
2639
    os_files[constants.OS_VARIANTS_FILE] = False
2640

    
2641
  if max(api_versions) >= constants.OS_API_V20:
2642
    os_files[constants.OS_PARAMETERS_FILE] = True
2643
  else:
2644
    del os_files[constants.OS_SCRIPT_VERIFY]
2645

    
2646
  for (filename, required) in os_files.items():
2647
    os_files[filename] = utils.PathJoin(os_dir, filename)
2648

    
2649
    try:
2650
      st = os.stat(os_files[filename])
2651
    except EnvironmentError, err:
2652
      if err.errno == errno.ENOENT and not required:
2653
        del os_files[filename]
2654
        continue
2655
      return False, ("File '%s' under path '%s' is missing (%s)" %
2656
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2657

    
2658
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2659
      return False, ("File '%s' under path '%s' is not a regular file" %
2660
                     (filename, os_dir))
2661

    
2662
    if filename in constants.OS_SCRIPTS:
2663
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2664
        return False, ("File '%s' under path '%s' is not executable" %
2665
                       (filename, os_dir))
2666

    
2667
  variants = []
2668
  if constants.OS_VARIANTS_FILE in os_files:
2669
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2670
    try:
2671
      variants = \
2672
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2673
    except EnvironmentError, err:
2674
      # we accept missing files, but not other errors
2675
      if err.errno != errno.ENOENT:
2676
        return False, ("Error while reading the OS variants file at %s: %s" %
2677
                       (variants_file, utils.ErrnoOrStr(err)))
2678

    
2679
  parameters = []
2680
  if constants.OS_PARAMETERS_FILE in os_files:
2681
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2682
    try:
2683
      parameters = utils.ReadFile(parameters_file).splitlines()
2684
    except EnvironmentError, err:
2685
      return False, ("Error while reading the OS parameters file at %s: %s" %
2686
                     (parameters_file, utils.ErrnoOrStr(err)))
2687
    parameters = [v.split(None, 1) for v in parameters]
2688

    
2689
  os_obj = objects.OS(name=name, path=os_dir,
2690
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2691
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2692
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2693
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2694
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2695
                                                 None),
2696
                      supported_variants=variants,
2697
                      supported_parameters=parameters,
2698
                      api_versions=api_versions)
2699
  return True, os_obj
2700

    
2701

    
2702
def OSFromDisk(name, base_dir=None):
2703
  """Create an OS instance from disk.
2704

2705
  This function will return an OS instance if the given name is a
2706
  valid OS name. Otherwise, it will raise an appropriate
2707
  L{RPCFail} exception, detailing why this is not a valid OS.
2708

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

2712
  @type base_dir: string
2713
  @keyword base_dir: Base directory containing OS installations.
2714
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2715
  @rtype: L{objects.OS}
2716
  @return: the OS instance if we find a valid one
2717
  @raise RPCFail: if we don't find a valid OS
2718

2719
  """
2720
  name_only = objects.OS.GetName(name)
2721
  status, payload = _TryOSFromDisk(name_only, base_dir)
2722

    
2723
  if not status:
2724
    _Fail(payload)
2725

    
2726
  return payload
2727

    
2728

    
2729
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2730
  """Calculate the basic environment for an os script.
2731

2732
  @type os_name: str
2733
  @param os_name: full operating system name (including variant)
2734
  @type inst_os: L{objects.OS}
2735
  @param inst_os: operating system for which the environment is being built
2736
  @type os_params: dict
2737
  @param os_params: the OS parameters
2738
  @type debug: integer
2739
  @param debug: debug level (0 or 1, for OS Api 10)
2740
  @rtype: dict
2741
  @return: dict of environment variables
2742
  @raise errors.BlockDeviceError: if the block device
2743
      cannot be found
2744

2745
  """
2746
  result = {}
2747
  api_version = \
2748
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2749
  result["OS_API_VERSION"] = "%d" % api_version
2750
  result["OS_NAME"] = inst_os.name
2751
  result["DEBUG_LEVEL"] = "%d" % debug
2752

    
2753
  # OS variants
2754
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2755
    variant = objects.OS.GetVariant(os_name)
2756
    if not variant:
2757
      variant = inst_os.supported_variants[0]
2758
  else:
2759
    variant = ""
2760
  result["OS_VARIANT"] = variant
2761

    
2762
  # OS params
2763
  for pname, pvalue in os_params.items():
2764
    result["OSP_%s" % pname.upper()] = pvalue
2765

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

    
2771
  return result
2772

    
2773

    
2774
def OSEnvironment(instance, inst_os, debug=0):
2775
  """Calculate the environment for an os script.
2776

2777
  @type instance: L{objects.Instance}
2778
  @param instance: target instance for the os script run
2779
  @type inst_os: L{objects.OS}
2780
  @param inst_os: operating system for which the environment is being built
2781
  @type debug: integer
2782
  @param debug: debug level (0 or 1, for OS Api 10)
2783
  @rtype: dict
2784
  @return: dict of environment variables
2785
  @raise errors.BlockDeviceError: if the block device
2786
      cannot be found
2787

2788
  """
2789
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2790

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

    
2794
  result["HYPERVISOR"] = instance.hypervisor
2795
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2796
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2797
  result["INSTANCE_SECONDARY_NODES"] = \
2798
      ("%s" % " ".join(instance.secondary_nodes))
2799

    
2800
  # Disks
2801
  for idx, disk in enumerate(instance.disks):
2802
    real_disk = _OpenRealBD(disk)
2803
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2804
    result["DISK_%d_ACCESS" % idx] = disk.mode
2805
    result["DISK_%d_UUID" % idx] = disk.uuid
2806
    if disk.name:
2807
      result["DISK_%d_NAME" % idx] = disk.name
2808
    if constants.HV_DISK_TYPE in instance.hvparams:
2809
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2810
        instance.hvparams[constants.HV_DISK_TYPE]
2811
    if disk.dev_type in constants.LDS_BLOCK:
2812
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2813
    elif disk.dev_type == constants.LD_FILE:
2814
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2815
        "file:%s" % disk.physical_id[0]
2816

    
2817
  # NICs
2818
  for idx, nic in enumerate(instance.nics):
2819
    result["NIC_%d_MAC" % idx] = nic.mac
2820
    result["NIC_%d_UUID" % idx] = nic.uuid
2821
    if nic.name:
2822
      result["NIC_%d_NAME" % idx] = nic.name
2823
    if nic.ip:
2824
      result["NIC_%d_IP" % idx] = nic.ip
2825
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2826
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2827
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2828
    if nic.nicparams[constants.NIC_LINK]:
2829
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2830
    if nic.netinfo:
2831
      nobj = objects.Network.FromDict(nic.netinfo)
2832
      result.update(nobj.HooksDict("NIC_%d_" % idx))
2833
    if constants.HV_NIC_TYPE in instance.hvparams:
2834
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2835
        instance.hvparams[constants.HV_NIC_TYPE]
2836

    
2837
  # HV/BE params
2838
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2839
    for key, value in source.items():
2840
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2841

    
2842
  return result
2843

    
2844

    
2845
def DiagnoseExtStorage(top_dirs=None):
2846
  """Compute the validity for all ExtStorage Providers.
2847

2848
  @type top_dirs: list
2849
  @param top_dirs: the list of directories in which to
2850
      search (if not given defaults to
2851
      L{pathutils.ES_SEARCH_PATH})
2852
  @rtype: list of L{objects.ExtStorage}
2853
  @return: a list of tuples (name, path, status, diagnose, parameters)
2854
      for all (potential) ExtStorage Providers under all
2855
      search paths, where:
2856
          - name is the (potential) ExtStorage Provider
2857
          - path is the full path to the ExtStorage Provider
2858
          - status True/False is the validity of the ExtStorage Provider
2859
          - diagnose is the error message for an invalid ExtStorage Provider,
2860
            otherwise empty
2861
          - parameters is a list of (name, help) parameters, if any
2862

2863
  """
2864
  if top_dirs is None:
2865
    top_dirs = pathutils.ES_SEARCH_PATH
2866

    
2867
  result = []
2868
  for dir_name in top_dirs:
2869
    if os.path.isdir(dir_name):
2870
      try:
2871
        f_names = utils.ListVisibleFiles(dir_name)
2872
      except EnvironmentError, err:
2873
        logging.exception("Can't list the ExtStorage directory %s: %s",
2874
                          dir_name, err)
2875
        break
2876
      for name in f_names:
2877
        es_path = utils.PathJoin(dir_name, name)
2878
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2879
        if status:
2880
          diagnose = ""
2881
          parameters = es_inst.supported_parameters
2882
        else:
2883
          diagnose = es_inst
2884
          parameters = []
2885
        result.append((name, es_path, status, diagnose, parameters))
2886

    
2887
  return result
2888

    
2889

    
2890
def BlockdevGrow(disk, amount, dryrun, backingstore, excl_stor):
2891
  """Grow a stack of block devices.
2892

2893
  This function is called recursively, with the childrens being the
2894
  first ones to resize.
2895

2896
  @type disk: L{objects.Disk}
2897
  @param disk: the disk to be grown
2898
  @type amount: integer
2899
  @param amount: the amount (in mebibytes) to grow with
2900
  @type dryrun: boolean
2901
  @param dryrun: whether to execute the operation in simulation mode
2902
      only, without actually increasing the size
2903
  @param backingstore: whether to execute the operation on backing storage
2904
      only, or on "logical" storage only; e.g. DRBD is logical storage,
2905
      whereas LVM, file, RBD are backing storage
2906
  @rtype: (status, result)
2907
  @type excl_stor: boolean
2908
  @param excl_stor: Whether exclusive_storage is active
2909
  @return: a tuple with the status of the operation (True/False), and
2910
      the errors message if status is False
2911

2912
  """
2913
  r_dev = _RecursiveFindBD(disk)
2914
  if r_dev is None:
2915
    _Fail("Cannot find block device %s", disk)
2916

    
2917
  try:
2918
    r_dev.Grow(amount, dryrun, backingstore, excl_stor)
2919
  except errors.BlockDeviceError, err:
2920
    _Fail("Failed to grow block device: %s", err, exc=True)
2921

    
2922

    
2923
def BlockdevSnapshot(disk):
2924
  """Create a snapshot copy of a block device.
2925

2926
  This function is called recursively, and the snapshot is actually created
2927
  just for the leaf lvm backend device.
2928

2929
  @type disk: L{objects.Disk}
2930
  @param disk: the disk to be snapshotted
2931
  @rtype: string
2932
  @return: snapshot disk ID as (vg, lv)
2933

2934
  """
2935
  if disk.dev_type == constants.LD_DRBD8:
2936
    if not disk.children:
2937
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2938
            disk.unique_id)
2939
    return BlockdevSnapshot(disk.children[0])
2940
  elif disk.dev_type == constants.LD_LV:
2941
    r_dev = _RecursiveFindBD(disk)
2942
    if r_dev is not None:
2943
      # FIXME: choose a saner value for the snapshot size
2944
      # let's stay on the safe side and ask for the full size, for now
2945
      return r_dev.Snapshot(disk.size)
2946
    else:
2947
      _Fail("Cannot find block device %s", disk)
2948
  else:
2949
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2950
          disk.unique_id, disk.dev_type)
2951

    
2952

    
2953
def BlockdevSetInfo(disk, info):
2954
  """Sets 'metadata' information on block devices.
2955

2956
  This function sets 'info' metadata on block devices. Initial
2957
  information is set at device creation; this function should be used
2958
  for example after renames.
2959

2960
  @type disk: L{objects.Disk}
2961
  @param disk: the disk to be grown
2962
  @type info: string
2963
  @param info: new 'info' metadata
2964
  @rtype: (status, result)
2965
  @return: a tuple with the status of the operation (True/False), and
2966
      the errors message if status is False
2967

2968
  """
2969
  r_dev = _RecursiveFindBD(disk)
2970
  if r_dev is None:
2971
    _Fail("Cannot find block device %s", disk)
2972

    
2973
  try:
2974
    r_dev.SetInfo(info)
2975
  except errors.BlockDeviceError, err:
2976
    _Fail("Failed to set information on block device: %s", err, exc=True)
2977

    
2978

    
2979
def FinalizeExport(instance, snap_disks):
2980
  """Write out the export configuration information.
2981

2982
  @type instance: L{objects.Instance}
2983
  @param instance: the instance which we export, used for
2984
      saving configuration
2985
  @type snap_disks: list of L{objects.Disk}
2986
  @param snap_disks: list of snapshot block devices, which
2987
      will be used to get the actual name of the dump file
2988

2989
  @rtype: None
2990

2991
  """
2992
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
2993
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
2994

    
2995
  config = objects.SerializableConfigParser()
2996

    
2997
  config.add_section(constants.INISECT_EXP)
2998
  config.set(constants.INISECT_EXP, "version", "0")
2999
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
3000
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
3001
  config.set(constants.INISECT_EXP, "os", instance.os)
3002
  config.set(constants.INISECT_EXP, "compression", "none")
3003

    
3004
  config.add_section(constants.INISECT_INS)
3005
  config.set(constants.INISECT_INS, "name", instance.name)
3006
  config.set(constants.INISECT_INS, "maxmem", "%d" %
3007
             instance.beparams[constants.BE_MAXMEM])
3008
  config.set(constants.INISECT_INS, "minmem", "%d" %
3009
             instance.beparams[constants.BE_MINMEM])
3010
  # "memory" is deprecated, but useful for exporting to old ganeti versions
3011
  config.set(constants.INISECT_INS, "memory", "%d" %
3012
             instance.beparams[constants.BE_MAXMEM])
3013
  config.set(constants.INISECT_INS, "vcpus", "%d" %
3014
             instance.beparams[constants.BE_VCPUS])
3015
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
3016
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
3017
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
3018

    
3019
  nic_total = 0
3020
  for nic_count, nic in enumerate(instance.nics):
3021
    nic_total += 1
3022
    config.set(constants.INISECT_INS, "nic%d_mac" %
3023
               nic_count, "%s" % nic.mac)
3024
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
3025
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
3026
               "%s" % nic.network)
3027
    for param in constants.NICS_PARAMETER_TYPES:
3028
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
3029
                 "%s" % nic.nicparams.get(param, None))
3030
  # TODO: redundant: on load can read nics until it doesn't exist
3031
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
3032

    
3033
  disk_total = 0
3034
  for disk_count, disk in enumerate(snap_disks):
3035
    if disk:
3036
      disk_total += 1
3037
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
3038
                 ("%s" % disk.iv_name))
3039
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
3040
                 ("%s" % disk.physical_id[1]))
3041
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
3042
                 ("%d" % disk.size))
3043

    
3044
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
3045

    
3046
  # New-style hypervisor/backend parameters
3047

    
3048
  config.add_section(constants.INISECT_HYP)
3049
  for name, value in instance.hvparams.items():
3050
    if name not in constants.HVC_GLOBALS:
3051
      config.set(constants.INISECT_HYP, name, str(value))
3052

    
3053
  config.add_section(constants.INISECT_BEP)
3054
  for name, value in instance.beparams.items():
3055
    config.set(constants.INISECT_BEP, name, str(value))
3056

    
3057
  config.add_section(constants.INISECT_OSP)
3058
  for name, value in instance.osparams.items():
3059
    config.set(constants.INISECT_OSP, name, str(value))
3060

    
3061
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
3062
                  data=config.Dumps())
3063
  shutil.rmtree(finaldestdir, ignore_errors=True)
3064
  shutil.move(destdir, finaldestdir)
3065

    
3066

    
3067
def ExportInfo(dest):
3068
  """Get export configuration information.
3069

3070
  @type dest: str
3071
  @param dest: directory containing the export
3072

3073
  @rtype: L{objects.SerializableConfigParser}
3074
  @return: a serializable config file containing the
3075
      export info
3076

3077
  """
3078
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
3079

    
3080
  config = objects.SerializableConfigParser()
3081
  config.read(cff)
3082

    
3083
  if (not config.has_section(constants.INISECT_EXP) or
3084
      not config.has_section(constants.INISECT_INS)):
3085
    _Fail("Export info file doesn't have the required fields")
3086

    
3087
  return config.Dumps()
3088

    
3089

    
3090
def ListExports():
3091
  """Return a list of exports currently available on this machine.
3092

3093
  @rtype: list
3094
  @return: list of the exports
3095

3096
  """
3097
  if os.path.isdir(pathutils.EXPORT_DIR):
3098
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
3099
  else:
3100
    _Fail("No exports directory")
3101

    
3102

    
3103
def RemoveExport(export):
3104
  """Remove an existing export from the node.
3105

3106
  @type export: str
3107
  @param export: the name of the export to remove
3108
  @rtype: None
3109

3110
  """
3111
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
3112

    
3113
  try:
3114
    shutil.rmtree(target)
3115
  except EnvironmentError, err:
3116
    _Fail("Error while removing the export: %s", err, exc=True)
3117

    
3118

    
3119
def BlockdevRename(devlist):
3120
  """Rename a list of block devices.
3121

3122
  @type devlist: list of tuples
3123
  @param devlist: list of tuples of the form  (disk,
3124
      new_logical_id, new_physical_id); disk is an
3125
      L{objects.Disk} object describing the current disk,
3126
      and new logical_id/physical_id is the name we
3127
      rename it to
3128
  @rtype: boolean
3129
  @return: True if all renames succeeded, False otherwise
3130

3131
  """
3132
  msgs = []
3133
  result = True
3134
  for disk, unique_id in devlist:
3135
    dev = _RecursiveFindBD(disk)
3136
    if dev is None:
3137
      msgs.append("Can't find device %s in rename" % str(disk))
3138
      result = False
3139
      continue
3140
    try:
3141
      old_rpath = dev.dev_path
3142
      dev.Rename(unique_id)
3143
      new_rpath = dev.dev_path
3144
      if old_rpath != new_rpath:
3145
        DevCacheManager.RemoveCache(old_rpath)
3146
        # FIXME: we should add the new cache information here, like:
3147
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
3148
        # but we don't have the owner here - maybe parse from existing
3149
        # cache? for now, we only lose lvm data when we rename, which
3150
        # is less critical than DRBD or MD
3151
    except errors.BlockDeviceError, err:
3152
      msgs.append("Can't rename device '%s' to '%s': %s" %
3153
                  (dev, unique_id, err))
3154
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
3155
      result = False
3156
  if not result:
3157
    _Fail("; ".join(msgs))
3158

    
3159

    
3160
def _TransformFileStorageDir(fs_dir):
3161
  """Checks whether given file_storage_dir is valid.
3162

3163
  Checks wheter the given fs_dir is within the cluster-wide default
3164
  file_storage_dir or the shared_file_storage_dir, which are stored in
3165
  SimpleStore. Only paths under those directories are allowed.
3166

3167
  @type fs_dir: str
3168
  @param fs_dir: the path to check
3169

3170
  @return: the normalized path if valid, None otherwise
3171

3172
  """
3173
  if not (constants.ENABLE_FILE_STORAGE or
3174
          constants.ENABLE_SHARED_FILE_STORAGE):
3175
    _Fail("File storage disabled at configure time")
3176

    
3177
  bdev.CheckFileStoragePath(fs_dir)
3178

    
3179
  return os.path.normpath(fs_dir)
3180

    
3181

    
3182
def CreateFileStorageDir(file_storage_dir):
3183
  """Create file storage directory.
3184

3185
  @type file_storage_dir: str
3186
  @param file_storage_dir: directory to create
3187

3188
  @rtype: tuple
3189
  @return: tuple with first element a boolean indicating wheter dir
3190
      creation was successful or not
3191

3192
  """
3193
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3194
  if os.path.exists(file_storage_dir):
3195
    if not os.path.isdir(file_storage_dir):
3196
      _Fail("Specified storage dir '%s' is not a directory",
3197
            file_storage_dir)
3198
  else:
3199
    try:
3200
      os.makedirs(file_storage_dir, 0750)
3201
    except OSError, err:
3202
      _Fail("Cannot create file storage directory '%s': %s",
3203
            file_storage_dir, err, exc=True)
3204

    
3205

    
3206
def RemoveFileStorageDir(file_storage_dir):
3207
  """Remove file storage directory.
3208

3209
  Remove it only if it's empty. If not log an error and return.
3210

3211
  @type file_storage_dir: str
3212
  @param file_storage_dir: the directory we should cleanup
3213
  @rtype: tuple (success,)
3214
  @return: tuple of one element, C{success}, denoting
3215
      whether the operation was successful
3216

3217
  """
3218
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3219
  if os.path.exists(file_storage_dir):
3220
    if not os.path.isdir(file_storage_dir):
3221
      _Fail("Specified Storage directory '%s' is not a directory",
3222
            file_storage_dir)
3223
    # deletes dir only if empty, otherwise we want to fail the rpc call
3224
    try:
3225
      os.rmdir(file_storage_dir)
3226
    except OSError, err:
3227
      _Fail("Cannot remove file storage directory '%s': %s",
3228
            file_storage_dir, err)
3229

    
3230

    
3231
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
3232
  """Rename the file storage directory.
3233

3234
  @type old_file_storage_dir: str
3235
  @param old_file_storage_dir: the current path
3236
  @type new_file_storage_dir: str
3237
  @param new_file_storage_dir: the name we should rename to
3238
  @rtype: tuple (success,)
3239
  @return: tuple of one element, C{success}, denoting
3240
      whether the operation was successful
3241

3242
  """
3243
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
3244
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
3245
  if not os.path.exists(new_file_storage_dir):
3246
    if os.path.isdir(old_file_storage_dir):
3247
      try:
3248
        os.rename(old_file_storage_dir, new_file_storage_dir)
3249
      except OSError, err:
3250
        _Fail("Cannot rename '%s' to '%s': %s",
3251
              old_file_storage_dir, new_file_storage_dir, err)
3252
    else:
3253
      _Fail("Specified storage dir '%s' is not a directory",
3254
            old_file_storage_dir)
3255
  else:
3256
    if os.path.exists(old_file_storage_dir):
3257
      _Fail("Cannot rename '%s' to '%s': both locations exist",
3258
            old_file_storage_dir, new_file_storage_dir)
3259

    
3260

    
3261
def _EnsureJobQueueFile(file_name):
3262
  """Checks whether the given filename is in the queue directory.
3263

3264
  @type file_name: str
3265
  @param file_name: the file name we should check
3266
  @rtype: None
3267
  @raises RPCFail: if the file is not valid
3268

3269
  """
3270
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
3271
    _Fail("Passed job queue file '%s' does not belong to"
3272
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
3273

    
3274

    
3275
def JobQueueUpdate(file_name, content):
3276
  """Updates a file in the queue directory.
3277

3278
  This is just a wrapper over L{utils.io.WriteFile}, with proper
3279
  checking.
3280

3281
  @type file_name: str
3282
  @param file_name: the job file name
3283
  @type content: str
3284
  @param content: the new job contents
3285
  @rtype: boolean
3286
  @return: the success of the operation
3287

3288
  """
3289
  file_name = vcluster.LocalizeVirtualPath(file_name)
3290

    
3291
  _EnsureJobQueueFile(file_name)
3292
  getents = runtime.GetEnts()
3293

    
3294
  # Write and replace the file atomically
3295
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3296
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3297

    
3298

    
3299
def JobQueueRename(old, new):
3300
  """Renames a job queue file.
3301

3302
  This is just a wrapper over os.rename with proper checking.
3303

3304
  @type old: str
3305
  @param old: the old (actual) file name
3306
  @type new: str
3307
  @param new: the desired file name
3308
  @rtype: tuple
3309
  @return: the success of the operation and payload
3310

3311
  """
3312
  old = vcluster.LocalizeVirtualPath(old)
3313
  new = vcluster.LocalizeVirtualPath(new)
3314

    
3315
  _EnsureJobQueueFile(old)
3316
  _EnsureJobQueueFile(new)
3317

    
3318
  getents = runtime.GetEnts()
3319

    
3320
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3321
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3322

    
3323

    
3324
def BlockdevClose(instance_name, disks):
3325
  """Closes the given block devices.
3326

3327
  This means they will be switched to secondary mode (in case of
3328
  DRBD).
3329

3330
  @param instance_name: if the argument is not empty, the symlinks
3331
      of this instance will be removed
3332
  @type disks: list of L{objects.Disk}
3333
  @param disks: the list of disks to be closed
3334
  @rtype: tuple (success, message)
3335
  @return: a tuple of success and message, where success
3336
      indicates the succes of the operation, and message
3337
      which will contain the error details in case we
3338
      failed
3339

3340
  """
3341
  bdevs = []
3342
  for cf in disks:
3343
    rd = _RecursiveFindBD(cf)
3344
    if rd is None:
3345
      _Fail("Can't find device %s", cf)
3346
    bdevs.append(rd)
3347

    
3348
  msg = []
3349
  for rd in bdevs:
3350
    try:
3351
      rd.Close()
3352
    except errors.BlockDeviceError, err:
3353
      msg.append(str(err))
3354
  if msg:
3355
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3356
  else:
3357
    if instance_name:
3358
      _RemoveBlockDevLinks(instance_name, disks)
3359

    
3360

    
3361
def ValidateHVParams(hvname, hvparams):
3362
  """Validates the given hypervisor parameters.
3363

3364
  @type hvname: string
3365
  @param hvname: the hypervisor name
3366
  @type hvparams: dict
3367
  @param hvparams: the hypervisor parameters to be validated
3368
  @rtype: None
3369

3370
  """
3371
  try:
3372
    hv_type = hypervisor.GetHypervisor(hvname)
3373
    hv_type.ValidateParameters(hvparams)
3374
  except errors.HypervisorError, err:
3375
    _Fail(str(err), log=False)
3376

    
3377

    
3378
def _CheckOSPList(os_obj, parameters):
3379
  """Check whether a list of parameters is supported by the OS.
3380

3381
  @type os_obj: L{objects.OS}
3382
  @param os_obj: OS object to check
3383
  @type parameters: list
3384
  @param parameters: the list of parameters to check
3385

3386
  """
3387
  supported = [v[0] for v in os_obj.supported_parameters]
3388
  delta = frozenset(parameters).difference(supported)
3389
  if delta:
3390
    _Fail("The following parameters are not supported"
3391
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3392

    
3393

    
3394
def ValidateOS(required, osname, checks, osparams):
3395
  """Validate the given OS' parameters.
3396

3397
  @type required: boolean
3398
  @param required: whether absence of the OS should translate into
3399
      failure or not
3400
  @type osname: string
3401
  @param osname: the OS to be validated
3402
  @type checks: list
3403
  @param checks: list of the checks to run (currently only 'parameters')
3404
  @type osparams: dict
3405
  @param osparams: dictionary with OS parameters
3406
  @rtype: boolean
3407
  @return: True if the validation passed, or False if the OS was not
3408
      found and L{required} was false
3409

3410
  """
3411
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3412
    _Fail("Unknown checks required for OS %s: %s", osname,
3413
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3414

    
3415
  name_only = objects.OS.GetName(osname)
3416
  status, tbv = _TryOSFromDisk(name_only, None)
3417

    
3418
  if not status:
3419
    if required:
3420
      _Fail(tbv)
3421
    else:
3422
      return False
3423

    
3424
  if max(tbv.api_versions) < constants.OS_API_V20:
3425
    return True
3426

    
3427
  if constants.OS_VALIDATE_PARAMETERS in checks:
3428
    _CheckOSPList(tbv, osparams.keys())
3429

    
3430
  validate_env = OSCoreEnv(osname, tbv, osparams)
3431
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3432
                        cwd=tbv.path, reset_env=True)
3433
  if result.failed:
3434
    logging.error("os validate command '%s' returned error: %s output: %s",
3435
                  result.cmd, result.fail_reason, result.output)
3436
    _Fail("OS validation script failed (%s), output: %s",
3437
          result.fail_reason, result.output, log=False)
3438

    
3439
  return True
3440

    
3441

    
3442
def DemoteFromMC():
3443
  """Demotes the current node from master candidate role.
3444

3445
  """
3446
  # try to ensure we're not the master by mistake
3447
  master, myself = ssconf.GetMasterAndMyself()
3448
  if master == myself:
3449
    _Fail("ssconf status shows I'm the master node, will not demote")
3450

    
3451
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3452
  if not result.failed:
3453
    _Fail("The master daemon is running, will not demote")
3454

    
3455
  try:
3456
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3457
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3458
  except EnvironmentError, err:
3459
    if err.errno != errno.ENOENT:
3460
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3461

    
3462
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3463

    
3464

    
3465
def _GetX509Filenames(cryptodir, name):
3466
  """Returns the full paths for the private key and certificate.
3467

3468
  """
3469
  return (utils.PathJoin(cryptodir, name),
3470
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3471
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3472

    
3473

    
3474
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3475
  """Creates a new X509 certificate for SSL/TLS.
3476

3477
  @type validity: int
3478
  @param validity: Validity in seconds
3479
  @rtype: tuple; (string, string)
3480
  @return: Certificate name and public part
3481

3482
  """
3483
  (key_pem, cert_pem) = \
3484
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3485
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3486

    
3487
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3488
                              prefix="x509-%s-" % utils.TimestampForFilename())
3489
  try:
3490
    name = os.path.basename(cert_dir)
3491
    assert len(name) > 5
3492

    
3493
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3494

    
3495
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3496
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3497

    
3498
    # Never return private key as it shouldn't leave the node
3499
    return (name, cert_pem)
3500
  except Exception:
3501
    shutil.rmtree(cert_dir, ignore_errors=True)
3502
    raise
3503

    
3504

    
3505
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3506
  """Removes a X509 certificate.
3507

3508
  @type name: string
3509
  @param name: Certificate name
3510

3511
  """
3512
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3513

    
3514
  utils.RemoveFile(key_file)
3515
  utils.RemoveFile(cert_file)
3516

    
3517
  try:
3518
    os.rmdir(cert_dir)
3519
  except EnvironmentError, err:
3520
    _Fail("Cannot remove certificate directory '%s': %s",
3521
          cert_dir, err)
3522

    
3523

    
3524
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3525
  """Returns the command for the requested input/output.
3526

3527
  @type instance: L{objects.Instance}
3528
  @param instance: The instance object
3529
  @param mode: Import/export mode
3530
  @param ieio: Input/output type
3531
  @param ieargs: Input/output arguments
3532

3533
  """
3534
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3535

    
3536
  env = None
3537
  prefix = None
3538
  suffix = None
3539
  exp_size = None
3540

    
3541
  if ieio == constants.IEIO_FILE:
3542
    (filename, ) = ieargs
3543

    
3544
    if not utils.IsNormAbsPath(filename):
3545
      _Fail("Path '%s' is not normalized or absolute", filename)
3546

    
3547
    real_filename = os.path.realpath(filename)
3548
    directory = os.path.dirname(real_filename)
3549

    
3550
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3551
      _Fail("File '%s' is not under exports directory '%s': %s",
3552
            filename, pathutils.EXPORT_DIR, real_filename)
3553

    
3554
    # Create directory
3555
    utils.Makedirs(directory, mode=0750)
3556

    
3557
    quoted_filename = utils.ShellQuote(filename)
3558

    
3559
    if mode == constants.IEM_IMPORT:
3560
      suffix = "> %s" % quoted_filename
3561
    elif mode == constants.IEM_EXPORT:
3562
      suffix = "< %s" % quoted_filename
3563

    
3564
      # Retrieve file size
3565
      try:
3566
        st = os.stat(filename)
3567
      except EnvironmentError, err:
3568
        logging.error("Can't stat(2) %s: %s", filename, err)
3569
      else:
3570
        exp_size = utils.BytesToMebibyte(st.st_size)
3571

    
3572
  elif ieio == constants.IEIO_RAW_DISK:
3573
    (disk, ) = ieargs
3574

    
3575
    real_disk = _OpenRealBD(disk)
3576

    
3577
    if mode == constants.IEM_IMPORT:
3578
      # we set here a smaller block size as, due to transport buffering, more
3579
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3580
      # is not already there or we pass a wrong path; we use notrunc to no
3581
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3582
      # much memory; this means that at best, we flush every 64k, which will
3583
      # not be very fast
3584
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3585
                                    " bs=%s oflag=dsync"),
3586
                                    real_disk.dev_path,
3587
                                    str(64 * 1024))
3588

    
3589
    elif mode == constants.IEM_EXPORT:
3590
      # the block size on the read dd is 1MiB to match our units
3591
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3592
                                   real_disk.dev_path,
3593
                                   str(1024 * 1024), # 1 MB
3594
                                   str(disk.size))
3595
      exp_size = disk.size
3596

    
3597
  elif ieio == constants.IEIO_SCRIPT:
3598
    (disk, disk_index, ) = ieargs
3599

    
3600
    assert isinstance(disk_index, (int, long))
3601

    
3602
    real_disk = _OpenRealBD(disk)
3603

    
3604
    inst_os = OSFromDisk(instance.os)
3605
    env = OSEnvironment(instance, inst_os)
3606

    
3607
    if mode == constants.IEM_IMPORT:
3608
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3609
      env["IMPORT_INDEX"] = str(disk_index)
3610
      script = inst_os.import_script
3611

    
3612
    elif mode == constants.IEM_EXPORT:
3613
      env["EXPORT_DEVICE"] = real_disk.dev_path
3614
      env["EXPORT_INDEX"] = str(disk_index)
3615
      script = inst_os.export_script
3616

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

    
3620
    if mode == constants.IEM_IMPORT:
3621
      suffix = "| %s" % script_cmd
3622

    
3623
    elif mode == constants.IEM_EXPORT:
3624
      prefix = "%s |" % script_cmd
3625

    
3626
    # Let script predict size
3627
    exp_size = constants.IE_CUSTOM_SIZE
3628

    
3629
  else:
3630
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3631

    
3632
  return (env, prefix, suffix, exp_size)
3633

    
3634

    
3635
def _CreateImportExportStatusDir(prefix):
3636
  """Creates status directory for import/export.
3637

3638
  """
3639
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3640
                          prefix=("%s-%s-" %
3641
                                  (prefix, utils.TimestampForFilename())))
3642

    
3643

    
3644
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3645
                            ieio, ieioargs):
3646
  """Starts an import or export daemon.
3647

3648
  @param mode: Import/output mode
3649
  @type opts: L{objects.ImportExportOptions}
3650
  @param opts: Daemon options
3651
  @type host: string
3652
  @param host: Remote host for export (None for import)
3653
  @type port: int
3654
  @param port: Remote port for export (None for import)
3655
  @type instance: L{objects.Instance}
3656
  @param instance: Instance object
3657
  @type component: string
3658
  @param component: which part of the instance is transferred now,
3659
      e.g. 'disk/0'
3660
  @param ieio: Input/output type
3661
  @param ieioargs: Input/output arguments
3662

3663
  """
3664
  if mode == constants.IEM_IMPORT:
3665
    prefix = "import"
3666

    
3667
    if not (host is None and port is None):
3668
      _Fail("Can not specify host or port on import")
3669

    
3670
  elif mode == constants.IEM_EXPORT:
3671
    prefix = "export"
3672

    
3673
    if host is None or port is None:
3674
      _Fail("Host and port must be specified for an export")
3675

    
3676
  else:
3677
    _Fail("Invalid mode %r", mode)
3678

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

    
3682
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3683
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3684

    
3685
  if opts.key_name is None:
3686
    # Use server.pem
3687
    key_path = pathutils.NODED_CERT_FILE
3688
    cert_path = pathutils.NODED_CERT_FILE
3689
    assert opts.ca_pem is None
3690
  else:
3691
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3692
                                                 opts.key_name)
3693
    assert opts.ca_pem is not None
3694

    
3695
  for i in [key_path, cert_path]:
3696
    if not os.path.exists(i):
3697
      _Fail("File '%s' does not exist" % i)
3698

    
3699
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3700
  try:
3701
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3702
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3703
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3704

    
3705
    if opts.ca_pem is None:
3706
      # Use server.pem
3707
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3708
    else:
3709
      ca = opts.ca_pem
3710

    
3711
    # Write CA file
3712
    utils.WriteFile(ca_file, data=ca, mode=0400)
3713

    
3714
    cmd = [
3715
      pathutils.IMPORT_EXPORT_DAEMON,
3716
      status_file, mode,
3717
      "--key=%s" % key_path,
3718
      "--cert=%s" % cert_path,
3719
      "--ca=%s" % ca_file,
3720
      ]
3721

    
3722
    if host:
3723
      cmd.append("--host=%s" % host)
3724

    
3725
    if port:
3726
      cmd.append("--port=%s" % port)
3727

    
3728
    if opts.ipv6:
3729
      cmd.append("--ipv6")
3730
    else:
3731
      cmd.append("--ipv4")
3732

    
3733
    if opts.compress:
3734
      cmd.append("--compress=%s" % opts.compress)
3735

    
3736
    if opts.magic:
3737
      cmd.append("--magic=%s" % opts.magic)
3738

    
3739
    if exp_size is not None:
3740
      cmd.append("--expected-size=%s" % exp_size)
3741

    
3742
    if cmd_prefix:
3743
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3744

    
3745
    if cmd_suffix:
3746
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3747

    
3748
    if mode == constants.IEM_EXPORT:
3749
      # Retry connection a few times when connecting to remote peer
3750
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3751
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3752
    elif opts.connect_timeout is not None:
3753
      assert mode == constants.IEM_IMPORT
3754
      # Overall timeout for establishing connection while listening
3755
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3756

    
3757
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3758

    
3759
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3760
    # support for receiving a file descriptor for output
3761
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3762
                      output=logfile)
3763

    
3764
    # The import/export name is simply the status directory name
3765
    return os.path.basename(status_dir)
3766

    
3767
  except Exception:
3768
    shutil.rmtree(status_dir, ignore_errors=True)
3769
    raise
3770

    
3771

    
3772
def GetImportExportStatus(names):
3773
  """Returns import/export daemon status.
3774

3775
  @type names: sequence
3776
  @param names: List of names
3777
  @rtype: List of dicts
3778
  @return: Returns a list of the state of each named import/export or None if a
3779
           status couldn't be read
3780

3781
  """
3782
  result = []
3783

    
3784
  for name in names:
3785
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3786
                                 _IES_STATUS_FILE)
3787

    
3788
    try:
3789
      data = utils.ReadFile(status_file)
3790
    except EnvironmentError, err:
3791
      if err.errno != errno.ENOENT:
3792
        raise
3793
      data = None
3794

    
3795
    if not data:
3796
      result.append(None)
3797
      continue
3798

    
3799
    result.append(serializer.LoadJson(data))
3800

    
3801
  return result
3802

    
3803

    
3804
def AbortImportExport(name):
3805
  """Sends SIGTERM to a running import/export daemon.
3806

3807
  """
3808
  logging.info("Abort import/export %s", name)
3809

    
3810
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3811
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3812

    
3813
  if pid:
3814
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3815
                 name, pid)
3816
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3817

    
3818

    
3819
def CleanupImportExport(name):
3820
  """Cleanup after an import or export.
3821

3822
  If the import/export daemon is still running it's killed. Afterwards the
3823
  whole status directory is removed.
3824

3825
  """
3826
  logging.info("Finalizing import/export %s", name)
3827

    
3828
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3829

    
3830
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3831

    
3832
  if pid:
3833
    logging.info("Import/export %s is still running with PID %s",
3834
                 name, pid)
3835
    utils.KillProcess(pid, waitpid=False)
3836

    
3837
  shutil.rmtree(status_dir, ignore_errors=True)
3838

    
3839

    
3840
def _SetPhysicalId(target_node_uuid, nodes_ip, disks):
3841
  """Sets the correct physical ID on all passed disks.
3842

3843
  """
3844
  for cf in disks:
3845
    cf.SetPhysicalID(target_node_uuid, nodes_ip)
3846

    
3847

    
3848
def _FindDisks(target_node_uuid, nodes_ip, disks):
3849
  """Sets the physical ID on disks and returns the block devices.
3850

3851
  """
3852
  _SetPhysicalId(target_node_uuid, nodes_ip, disks)
3853

    
3854
  bdevs = []
3855

    
3856
  for cf in disks:
3857
    rd = _RecursiveFindBD(cf)
3858
    if rd is None:
3859
      _Fail("Can't find device %s", cf)
3860
    bdevs.append(rd)
3861
  return bdevs
3862

    
3863

    
3864
def DrbdDisconnectNet(target_node_uuid, nodes_ip, disks):
3865
  """Disconnects the network on a list of drbd devices.
3866

3867
  """
3868
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3869

    
3870
  # disconnect disks
3871
  for rd in bdevs:
3872
    try:
3873
      rd.DisconnectNet()
3874
    except errors.BlockDeviceError, err:
3875
      _Fail("Can't change network configuration to standalone mode: %s",
3876
            err, exc=True)
3877

    
3878

    
3879
def DrbdAttachNet(target_node_uuid, nodes_ip, disks, instance_name,
3880
                  multimaster):
3881
  """Attaches the network on a list of drbd devices.
3882

3883
  """
3884
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3885

    
3886
  if multimaster:
3887
    for idx, rd in enumerate(bdevs):
3888
      try:
3889
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3890
      except EnvironmentError, err:
3891
        _Fail("Can't create symlink: %s", err)
3892
  # reconnect disks, switch to new master configuration and if
3893
  # needed primary mode
3894
  for rd in bdevs:
3895
    try:
3896
      rd.AttachNet(multimaster)
3897
    except errors.BlockDeviceError, err:
3898
      _Fail("Can't change network configuration: %s", err)
3899

    
3900
  # wait until the disks are connected; we need to retry the re-attach
3901
  # if the device becomes standalone, as this might happen if the one
3902
  # node disconnects and reconnects in a different mode before the
3903
  # other node reconnects; in this case, one or both of the nodes will
3904
  # decide it has wrong configuration and switch to standalone
3905

    
3906
  def _Attach():
3907
    all_connected = True
3908

    
3909
    for rd in bdevs:
3910
      stats = rd.GetProcStatus()
3911

    
3912
      all_connected = (all_connected and
3913
                       (stats.is_connected or stats.is_in_resync))
3914

    
3915
      if stats.is_standalone:
3916
        # peer had different config info and this node became
3917
        # standalone, even though this should not happen with the
3918
        # new staged way of changing disk configs
3919
        try:
3920
          rd.AttachNet(multimaster)
3921
        except errors.BlockDeviceError, err:
3922
          _Fail("Can't change network configuration: %s", err)
3923

    
3924
    if not all_connected:
3925
      raise utils.RetryAgain()
3926

    
3927
  try:
3928
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3929
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3930
  except utils.RetryTimeout:
3931
    _Fail("Timeout in disk reconnecting")
3932

    
3933
  if multimaster:
3934
    # change to primary mode
3935
    for rd in bdevs:
3936
      try:
3937
        rd.Open()
3938
      except errors.BlockDeviceError, err:
3939
        _Fail("Can't change to primary mode: %s", err)
3940

    
3941

    
3942
def DrbdWaitSync(target_node_uuid, nodes_ip, disks):
3943
  """Wait until DRBDs have synchronized.
3944

3945
  """
3946
  def _helper(rd):
3947
    stats = rd.GetProcStatus()
3948
    if not (stats.is_connected or stats.is_in_resync):
3949
      raise utils.RetryAgain()
3950
    return stats
3951

    
3952
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3953

    
3954
  min_resync = 100
3955
  alldone = True
3956
  for rd in bdevs:
3957
    try:
3958
      # poll each second for 15 seconds
3959
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3960
    except utils.RetryTimeout:
3961
      stats = rd.GetProcStatus()
3962
      # last check
3963
      if not (stats.is_connected or stats.is_in_resync):
3964
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3965
    alldone = alldone and (not stats.is_in_resync)
3966
    if stats.sync_percent is not None:
3967
      min_resync = min(min_resync, stats.sync_percent)
3968

    
3969
  return (alldone, min_resync)
3970

    
3971

    
3972
def DrbdNeedsActivation(target_node_uuid, nodes_ip, disks):
3973
  """Checks which of the passed disks needs activation and returns their UUIDs.
3974

3975
  """
3976
  _SetPhysicalId(target_node_uuid, nodes_ip, disks)
3977
  faulty_disks = []
3978

    
3979
  for disk in disks:
3980
    rd = _RecursiveFindBD(disk)
3981
    if rd is None:
3982
      faulty_disks.append(disk)
3983
      continue
3984

    
3985
    stats = rd.GetProcStatus()
3986
    if stats.is_standalone or stats.is_diskless:
3987
      faulty_disks.append(disk)
3988

    
3989
  return [disk.uuid for disk in faulty_disks]
3990

    
3991

    
3992
def GetDrbdUsermodeHelper():
3993
  """Returns DRBD usermode helper currently configured.
3994

3995
  """
3996
  try:
3997
    return drbd.DRBD8.GetUsermodeHelper()
3998
  except errors.BlockDeviceError, err:
3999
    _Fail(str(err))
4000

    
4001

    
4002
def PowercycleNode(hypervisor_type, hvparams=None):
4003
  """Hard-powercycle the node.
4004

4005
  Because we need to return first, and schedule the powercycle in the
4006
  background, we won't be able to report failures nicely.
4007

4008
  """
4009
  hyper = hypervisor.GetHypervisor(hypervisor_type)
4010
  try:
4011
    pid = os.fork()
4012
  except OSError:
4013
    # if we can't fork, we'll pretend that we're in the child process
4014
    pid = 0
4015
  if pid > 0:
4016
    return "Reboot scheduled in 5 seconds"
4017
  # ensure the child is running on ram
4018
  try:
4019
    utils.Mlockall()
4020
  except Exception: # pylint: disable=W0703
4021
    pass
4022
  time.sleep(5)
4023
  hyper.PowercycleNode(hvparams=hvparams)
4024

    
4025

    
4026
def _VerifyRestrictedCmdName(cmd):
4027
  """Verifies a restricted command name.
4028

4029
  @type cmd: string
4030
  @param cmd: Command name
4031
  @rtype: tuple; (boolean, string or None)
4032
  @return: The tuple's first element is the status; if C{False}, the second
4033
    element is an error message string, otherwise it's C{None}
4034

4035
  """
4036
  if not cmd.strip():
4037
    return (False, "Missing command name")
4038

    
4039
  if os.path.basename(cmd) != cmd:
4040
    return (False, "Invalid command name")
4041

    
4042
  if not constants.EXT_PLUGIN_MASK.match(cmd):
4043
    return (False, "Command name contains forbidden characters")
4044

    
4045
  return (True, None)
4046

    
4047

    
4048
def _CommonRestrictedCmdCheck(path, owner):
4049
  """Common checks for restricted command file system directories and files.
4050

4051
  @type path: string
4052
  @param path: Path to check
4053
  @param owner: C{None} or tuple containing UID and GID
4054
  @rtype: tuple; (boolean, string or C{os.stat} result)
4055
  @return: The tuple's first element is the status; if C{False}, the second
4056
    element is an error message string, otherwise it's the result of C{os.stat}
4057

4058
  """
4059
  if owner is None:
4060
    # Default to root as owner
4061
    owner = (0, 0)
4062

    
4063
  try:
4064
    st = os.stat(path)
4065
  except EnvironmentError, err:
4066
    return (False, "Can't stat(2) '%s': %s" % (path, err))
4067

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

    
4071
  if (st.st_uid, st.st_gid) != owner:
4072
    (owner_uid, owner_gid) = owner
4073
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
4074

    
4075
  return (True, st)
4076

    
4077

    
4078
def _VerifyRestrictedCmdDirectory(path, _owner=None):
4079
  """Verifies restricted command directory.
4080

4081
  @type path: string
4082
  @param path: Path to check
4083
  @rtype: tuple; (boolean, string or None)
4084
  @return: The tuple's first element is the status; if C{False}, the second
4085
    element is an error message string, otherwise it's C{None}
4086

4087
  """
4088
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
4089

    
4090
  if not status:
4091
    return (False, value)
4092

    
4093
  if not stat.S_ISDIR(value.st_mode):
4094
    return (False, "Path '%s' is not a directory" % path)
4095

    
4096
  return (True, None)
4097

    
4098

    
4099
def _VerifyRestrictedCmd(path, cmd, _owner=None):
4100
  """Verifies a whole restricted command and returns its executable filename.
4101

4102
  @type path: string
4103
  @param path: Directory containing restricted commands
4104
  @type cmd: string
4105
  @param cmd: Command name
4106
  @rtype: tuple; (boolean, string)
4107
  @return: The tuple's first element is the status; if C{False}, the second
4108
    element is an error message string, otherwise the second element is the
4109
    absolute path to the executable
4110

4111
  """
4112
  executable = utils.PathJoin(path, cmd)
4113

    
4114
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
4115

    
4116
  if not status:
4117
    return (False, msg)
4118

    
4119
  if not utils.IsExecutable(executable):
4120
    return (False, "access(2) thinks '%s' can't be executed" % executable)
4121

    
4122
  return (True, executable)
4123

    
4124

    
4125
def _PrepareRestrictedCmd(path, cmd,
4126
                          _verify_dir=_VerifyRestrictedCmdDirectory,
4127
                          _verify_name=_VerifyRestrictedCmdName,
4128
                          _verify_cmd=_VerifyRestrictedCmd):
4129
  """Performs a number of tests on a restricted command.
4130

4131
  @type path: string
4132
  @param path: Directory containing restricted commands
4133
  @type cmd: string
4134
  @param cmd: Command name
4135
  @return: Same as L{_VerifyRestrictedCmd}
4136

4137
  """
4138
  # Verify the directory first
4139
  (status, msg) = _verify_dir(path)
4140
  if status:
4141
    # Check command if everything was alright
4142
    (status, msg) = _verify_name(cmd)
4143

    
4144
  if not status:
4145
    return (False, msg)
4146

    
4147
  # Check actual executable
4148
  return _verify_cmd(path, cmd)
4149

    
4150

    
4151
def RunRestrictedCmd(cmd,
4152
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
4153
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
4154
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
4155
                     _sleep_fn=time.sleep,
4156
                     _prepare_fn=_PrepareRestrictedCmd,
4157
                     _runcmd_fn=utils.RunCmd,
4158
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
4159
  """Executes a restricted command after performing strict tests.
4160

4161
  @type cmd: string
4162
  @param cmd: Command name
4163
  @rtype: string
4164
  @return: Command output
4165
  @raise RPCFail: In case of an error
4166

4167
  """
4168
  logging.info("Preparing to run restricted command '%s'", cmd)
4169

    
4170
  if not _enabled:
4171
    _Fail("Restricted commands disabled at configure time")
4172

    
4173
  lock = None
4174
  try:
4175
    cmdresult = None
4176
    try:
4177
      lock = utils.FileLock.Open(_lock_file)
4178
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
4179

    
4180
      (status, value) = _prepare_fn(_path, cmd)
4181

    
4182
      if status:
4183
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
4184
                               postfork_fn=lambda _: lock.Unlock())
4185
      else:
4186
        logging.error(value)
4187
    except Exception: # pylint: disable=W0703
4188
      # Keep original error in log
4189
      logging.exception("Caught exception")
4190

    
4191
    if cmdresult is None:
4192
      logging.info("Sleeping for %0.1f seconds before returning",
4193
                   _RCMD_INVALID_DELAY)
4194
      _sleep_fn(_RCMD_INVALID_DELAY)
4195

    
4196
      # Do not include original error message in returned error
4197
      _Fail("Executing command '%s' failed" % cmd)
4198
    elif cmdresult.failed or cmdresult.fail_reason:
4199
      _Fail("Restricted command '%s' failed: %s; output: %s",
4200
            cmd, cmdresult.fail_reason, cmdresult.output)
4201
    else:
4202
      return cmdresult.output
4203
  finally:
4204
    if lock is not None:
4205
      # Release lock at last
4206
      lock.Close()
4207
      lock = None
4208

    
4209

    
4210
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
4211
  """Creates or removes the watcher pause file.
4212

4213
  @type until: None or number
4214
  @param until: Unix timestamp saying until when the watcher shouldn't run
4215

4216
  """
4217
  if until is None:
4218
    logging.info("Received request to no longer pause watcher")
4219
    utils.RemoveFile(_filename)
4220
  else:
4221
    logging.info("Received request to pause watcher until %s", until)
4222

    
4223
    if not ht.TNumber(until):
4224
      _Fail("Duration must be numeric")
4225

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

    
4228

    
4229
class HooksRunner(object):
4230
  """Hook runner.
4231

4232
  This class is instantiated on the node side (ganeti-noded) and not
4233
  on the master side.
4234

4235
  """
4236
  def __init__(self, hooks_base_dir=None):
4237
    """Constructor for hooks runner.
4238

4239
    @type hooks_base_dir: str or None
4240
    @param hooks_base_dir: if not None, this overrides the
4241
        L{pathutils.HOOKS_BASE_DIR} (useful for unittests)
4242

4243
    """
4244
    if hooks_base_dir is None:
4245
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
4246
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
4247
    # constant
4248
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
4249

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

4253
    """
4254
    assert len(node_list) == 1
4255
    node = node_list[0]
4256
    _, myself = ssconf.GetMasterAndMyself()
4257
    assert node == myself
4258

    
4259
    results = self.RunHooks(hpath, phase, env)
4260

    
4261
    # Return values in the form expected by HooksMaster
4262
    return {node: (None, False, results)}
4263

    
4264
  def RunHooks(self, hpath, phase, env):
4265
    """Run the scripts in the hooks directory.
4266

4267
    @type hpath: str
4268
    @param hpath: the path to the hooks directory which
4269
        holds the scripts
4270
    @type phase: str
4271
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
4272
        L{constants.HOOKS_PHASE_POST}
4273
    @type env: dict
4274
    @param env: dictionary with the environment for the hook
4275
    @rtype: list
4276
    @return: list of 3-element tuples:
4277
      - script path
4278
      - script result, either L{constants.HKR_SUCCESS} or
4279
        L{constants.HKR_FAIL}
4280
      - output of the script
4281

4282
    @raise errors.ProgrammerError: for invalid input
4283
        parameters
4284

4285
    """
4286
    if phase == constants.HOOKS_PHASE_PRE:
4287
      suffix = "pre"
4288
    elif phase == constants.HOOKS_PHASE_POST:
4289
      suffix = "post"
4290
    else:
4291
      _Fail("Unknown hooks phase '%s'", phase)
4292

    
4293
    subdir = "%s-%s.d" % (hpath, suffix)
4294
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
4295

    
4296
    results = []
4297

    
4298
    if not os.path.isdir(dir_name):
4299
      # for non-existing/non-dirs, we simply exit instead of logging a
4300
      # warning at every operation
4301
      return results
4302

    
4303
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
4304

    
4305
    for (relname, relstatus, runresult) in runparts_results:
4306
      if relstatus == constants.RUNPARTS_SKIP:
4307
        rrval = constants.HKR_SKIP
4308
        output = ""
4309
      elif relstatus == constants.RUNPARTS_ERR:
4310
        rrval = constants.HKR_FAIL
4311
        output = "Hook script execution error: %s" % runresult
4312
      elif relstatus == constants.RUNPARTS_RUN:
4313
        if runresult.failed:
4314
          rrval = constants.HKR_FAIL
4315
        else:
4316
          rrval = constants.HKR_SUCCESS
4317
        output = utils.SafeEncode(runresult.output.strip())
4318
      results.append(("%s/%s" % (subdir, relname), rrval, output))
4319

    
4320
    return results
4321

    
4322

    
4323
class IAllocatorRunner(object):
4324
  """IAllocator runner.
4325

4326
  This class is instantiated on the node side (ganeti-noded) and not on
4327
  the master side.
4328

4329
  """
4330
  @staticmethod
4331
  def Run(name, idata):
4332
    """Run an iallocator script.
4333

4334
    @type name: str
4335
    @param name: the iallocator script name
4336
    @type idata: str
4337
    @param idata: the allocator input data
4338

4339
    @rtype: tuple
4340
    @return: two element tuple of:
4341
       - status
4342
       - either error message or stdout of allocator (for success)
4343

4344
    """
4345
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
4346
                                  os.path.isfile)
4347
    if alloc_script is None:
4348
      _Fail("iallocator module '%s' not found in the search path", name)
4349

    
4350
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
4351
    try:
4352
      os.write(fd, idata)
4353
      os.close(fd)
4354
      result = utils.RunCmd([alloc_script, fin_name])
4355
      if result.failed:
4356
        _Fail("iallocator module '%s' failed: %s, output '%s'",
4357
              name, result.fail_reason, result.output)
4358
    finally:
4359
      os.unlink(fin_name)
4360

    
4361
    return result.stdout
4362

    
4363

    
4364
class DevCacheManager(object):
4365
  """Simple class for managing a cache of block device information.
4366

4367
  """
4368
  _DEV_PREFIX = "/dev/"
4369
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4370

    
4371
  @classmethod
4372
  def _ConvertPath(cls, dev_path):
4373
    """Converts a /dev/name path to the cache file name.
4374

4375
    This replaces slashes with underscores and strips the /dev
4376
    prefix. It then returns the full path to the cache file.
4377

4378
    @type dev_path: str
4379
    @param dev_path: the C{/dev/} path name
4380
    @rtype: str
4381
    @return: the converted path name
4382

4383
    """
4384
    if dev_path.startswith(cls._DEV_PREFIX):
4385
      dev_path = dev_path[len(cls._DEV_PREFIX):]
4386
    dev_path = dev_path.replace("/", "_")
4387
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4388
    return fpath
4389

    
4390
  @classmethod
4391
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4392
    """Updates the cache information for a given device.
4393

4394
    @type dev_path: str
4395
    @param dev_path: the pathname of the device
4396
    @type owner: str
4397
    @param owner: the owner (instance name) of the device
4398
    @type on_primary: bool
4399
    @param on_primary: whether this is the primary
4400
        node nor not
4401
    @type iv_name: str
4402
    @param iv_name: the instance-visible name of the
4403
        device, as in objects.Disk.iv_name
4404

4405
    @rtype: None
4406

4407
    """
4408
    if dev_path is None:
4409
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
4410
      return
4411
    fpath = cls._ConvertPath(dev_path)
4412
    if on_primary:
4413
      state = "primary"
4414
    else:
4415
      state = "secondary"
4416
    if iv_name is None:
4417
      iv_name = "not_visible"
4418
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4419
    try:
4420
      utils.WriteFile(fpath, data=fdata)
4421
    except EnvironmentError, err:
4422
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4423

    
4424
  @classmethod
4425
  def RemoveCache(cls, dev_path):
4426
    """Remove data for a dev_path.
4427

4428
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
4429
    path name and logging.
4430

4431
    @type dev_path: str
4432
    @param dev_path: the pathname of the device
4433

4434
    @rtype: None
4435

4436
    """
4437
    if dev_path is None:
4438
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
4439
      return
4440
    fpath = cls._ConvertPath(dev_path)
4441
    try:
4442
      utils.RemoveFile(fpath)
4443
    except EnvironmentError, err:
4444
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)