Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ a18ab868

History | View | Annotate | Download (137.1 kB)

1
#
2
#
3

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

    
21

    
22
"""Functions used by the node daemon
23

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

29
"""
30

    
31
# pylint: disable=E1103
32

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

    
37

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

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

    
73

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

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

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

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

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

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

    
108

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

112
  Its argument is the error message.
113

114
  """
115

    
116

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

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

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

    
128

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

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

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

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

    
144

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

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

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

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

    
167

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

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

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

    
177

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

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

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

    
190

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

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

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

    
210

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

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

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

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

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

    
240

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

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

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

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

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

    
267
  return frozenset(allowed_files)
268

    
269

    
270
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
271

    
272

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

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

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

    
283

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

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

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

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

    
308

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

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

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

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

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

    
340
      return result
341
    return wrapper
342
  return decorator
343

    
344

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

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

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

    
365
  return env
366

    
367

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

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

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

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

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

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

    
396

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

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

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

    
413

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

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

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

424
  """
425

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

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

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

    
441

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

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

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

    
458

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

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

464
  @rtype: None
465

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

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

    
476

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

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

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

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

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

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

    
507

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

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

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

    
529

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

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

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

540
  @param modify_ssh_setup: boolean
541

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

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

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

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

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

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

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

    
575

    
576
def _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 _CheckLvmStorageParams(params):
598
  """Performs sanity check for the 'exclusive storage' flag.
599

600
  @see: C{_CheckStorageParams}
601

602
  """
603
  _CheckStorageParams(params, 1)
604
  excl_stor = params[0]
605
  if not isinstance(params[0], bool):
606
    raise errors.ProgrammerError("Exclusive storage parameter is not"
607
                                 " boolean: '%s'." % excl_stor)
608
  return excl_stor
609

    
610

    
611
def _GetLvmVgSpaceInfo(name, params):
612
  """Wrapper around C{_GetVgInfo} which checks the storage parameters.
613

614
  @type name: string
615
  @param name: name of the volume group
616
  @type params: list
617
  @param params: list of storage parameters, which in this case should be
618
    containing only one for exclusive storage
619

620
  """
621
  excl_stor = _CheckLvmStorageParams(params)
622
  return _GetVgInfo(name, excl_stor)
623

    
624

    
625
def _GetVgInfo(name, excl_stor):
626
  """Retrieves information about a LVM volume group.
627

628
  """
629
  # TODO: GetVGInfo supports returning information for multiple VGs at once
630
  vginfo = bdev.LogicalVolume.GetVGInfo([name], excl_stor)
631
  if vginfo:
632
    vg_free = int(round(vginfo[0][0], 0))
633
    vg_size = int(round(vginfo[0][1], 0))
634
  else:
635
    vg_free = None
636
    vg_size = None
637

    
638
  return {
639
    "type": constants.ST_LVM_VG,
640
    "name": name,
641
    "storage_free": vg_free,
642
    "storage_size": vg_size,
643
    }
644

    
645

    
646
def _GetLvmPvSpaceInfo(name, params):
647
  """Wrapper around C{_GetVgSpindlesInfo} with sanity checks.
648

649
  @see: C{_GetLvmVgSpaceInfo}
650

651
  """
652
  excl_stor = _CheckLvmStorageParams(params)
653
  return _GetVgSpindlesInfo(name, excl_stor)
654
 
655

    
656
def _GetVgSpindlesInfo(
657
    name, excl_stor, info_fn=bdev.LogicalVolume.GetVgSpindlesInfo):
658
  """Retrieves information about spindles in an LVM volume group.
659

660
  @type name: string
661
  @param name: VG name
662
  @type excl_stor: bool
663
  @param excl_stor: exclusive storage
664
  @rtype: dict
665
  @return: dictionary whose keys are "name", "vg_free", "vg_size" for VG name,
666
      free spindles, total spindles respectively
667

668
  """
669
  if excl_stor:
670
    (vg_free, vg_size) = info_fn(name)
671
  else:
672
    vg_free = 0
673
    vg_size = 0
674
  return {
675
    "type": constants.ST_LVM_PV,
676
    "name": name,
677
    "storage_free": vg_free,
678
    "storage_size": vg_size,
679
    }
680

    
681

    
682
def _GetHvInfo(name, hvparams, get_hv_fn=hypervisor.GetHypervisor):
683
  """Retrieves node information from a hypervisor.
684

685
  The information returned depends on the hypervisor. Common items:
686

687
    - vg_size is the size of the configured volume group in MiB
688
    - vg_free is the free size of the volume group in MiB
689
    - memory_dom0 is the memory allocated for domain0 in MiB
690
    - memory_free is the currently available (free) ram in MiB
691
    - memory_total is the total number of ram in MiB
692
    - hv_version: the hypervisor version, if available
693

694
  @type hvparams: dict of string
695
  @param hvparams: the hypervisor's hvparams
696

697
  """
698
  return get_hv_fn(name).GetNodeInfo(hvparams=hvparams)
699

    
700

    
701
def _GetHvInfoAll(hv_specs, get_hv_fn=hypervisor.GetHypervisor):
702
  """Retrieves node information for all hypervisors.
703

704
  See C{_GetHvInfo} for information on the output.
705

706
  @type hv_specs: list of pairs (string, dict of strings)
707
  @param hv_specs: list of pairs of a hypervisor's name and its hvparams
708

709
  """
710
  if hv_specs is None:
711
    return None
712

    
713
  result = []
714
  for hvname, hvparams in hv_specs:
715
    result.append(_GetHvInfo(hvname, hvparams, get_hv_fn))
716
  return result
717

    
718

    
719
def _GetNamedNodeInfo(names, fn):
720
  """Calls C{fn} for all names in C{names} and returns a dictionary.
721

722
  @rtype: None or dict
723

724
  """
725
  if names is None:
726
    return None
727
  else:
728
    return map(fn, names)
729

    
730

    
731
def GetNodeInfo(storage_units, hv_specs):
732
  """Gives back a hash with different information about the node.
733

734
  @type storage_units: list of tuples (string, string, list)
735
  @param storage_units: List of tuples (storage unit, identifier, parameters) to
736
    ask for disk space information. In case of lvm-vg, the identifier is
737
    the VG name. The parameters can contain additional, storage-type-specific
738
    parameters, for example exclusive storage for lvm storage.
739
  @type hv_specs: list of pairs (string, dict of strings)
740
  @param hv_specs: list of pairs of a hypervisor's name and its hvparams
741
  @rtype: tuple; (string, None/dict, None/dict)
742
  @return: Tuple containing boot ID, volume group information and hypervisor
743
    information
744

745
  """
746
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
747
  storage_info = _GetNamedNodeInfo(
748
    storage_units,
749
    (lambda (storage_type, storage_key, storage_params):
750
        _ApplyStorageInfoFunction(storage_type, storage_key, storage_params)))
751
  hv_info = _GetHvInfoAll(hv_specs)
752
  return (bootid, storage_info, hv_info)
753

    
754

    
755
def _GetFileStorageSpaceInfo(path, params):
756
  """Wrapper around filestorage.GetSpaceInfo.
757

758
  The purpose of this wrapper is to call filestorage.GetFileStorageSpaceInfo
759
  and ignore the *args parameter to not leak it into the filestorage
760
  module's code.
761

762
  @see: C{filestorage.GetFileStorageSpaceInfo} for description of the
763
    parameters.
764

765
  """
766
  _CheckStorageParams(params, 0)
767
  return filestorage.GetFileStorageSpaceInfo(path)
768

    
769

    
770
# FIXME: implement storage reporting for all missing storage types.
771
_STORAGE_TYPE_INFO_FN = {
772
  constants.ST_BLOCK: None,
773
  constants.ST_DISKLESS: None,
774
  constants.ST_EXT: None,
775
  constants.ST_FILE: _GetFileStorageSpaceInfo,
776
  constants.ST_LVM_PV: _GetLvmPvSpaceInfo,
777
  constants.ST_LVM_VG: _GetLvmVgSpaceInfo,
778
  constants.ST_RADOS: None,
779
}
780

    
781

    
782
def _ApplyStorageInfoFunction(storage_type, storage_key, *args):
783
  """Looks up and applies the correct function to calculate free and total
784
  storage for the given storage type.
785

786
  @type storage_type: string
787
  @param storage_type: the storage type for which the storage shall be reported.
788
  @type storage_key: string
789
  @param storage_key: identifier of a storage unit, e.g. the volume group name
790
    of an LVM storage unit
791
  @type args: any
792
  @param args: various parameters that can be used for storage reporting. These
793
    parameters and their semantics vary from storage type to storage type and
794
    are just propagated in this function.
795
  @return: the results of the application of the storage space function (see
796
    _STORAGE_TYPE_INFO_FN) if storage space reporting is implemented for that
797
    storage type
798
  @raises NotImplementedError: for storage types who don't support space
799
    reporting yet
800
  """
801
  fn = _STORAGE_TYPE_INFO_FN[storage_type]
802
  if fn is not None:
803
    return fn(storage_key, *args)
804
  else:
805
    raise NotImplementedError
806

    
807

    
808
def _CheckExclusivePvs(pvi_list):
809
  """Check that PVs are not shared among LVs
810

811
  @type pvi_list: list of L{objects.LvmPvInfo} objects
812
  @param pvi_list: information about the PVs
813

814
  @rtype: list of tuples (string, list of strings)
815
  @return: offending volumes, as tuples: (pv_name, [lv1_name, lv2_name...])
816

817
  """
818
  res = []
819
  for pvi in pvi_list:
820
    if len(pvi.lv_list) > 1:
821
      res.append((pvi.name, pvi.lv_list))
822
  return res
823

    
824

    
825
def _VerifyHypervisors(what, vm_capable, result, all_hvparams,
826
                       get_hv_fn=hypervisor.GetHypervisor):
827
  """Verifies the hypervisor. Appends the results to the 'results' list.
828

829
  @type what: C{dict}
830
  @param what: a dictionary of things to check
831
  @type vm_capable: boolean
832
  @param vm_capable: whether or not this node is vm capable
833
  @type result: dict
834
  @param result: dictionary of verification results; results of the
835
    verifications in this function will be added here
836
  @type all_hvparams: dict of dict of string
837
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
838
  @type get_hv_fn: function
839
  @param get_hv_fn: function to retrieve the hypervisor, to improve testability
840

841
  """
842
  if not vm_capable:
843
    return
844

    
845
  if constants.NV_HYPERVISOR in what:
846
    result[constants.NV_HYPERVISOR] = {}
847
    for hv_name in what[constants.NV_HYPERVISOR]:
848
      hvparams = all_hvparams[hv_name]
849
      try:
850
        val = get_hv_fn(hv_name).Verify(hvparams=hvparams)
851
      except errors.HypervisorError, err:
852
        val = "Error while checking hypervisor: %s" % str(err)
853
      result[constants.NV_HYPERVISOR][hv_name] = val
854

    
855

    
856
def _VerifyHvparams(what, vm_capable, result,
857
                    get_hv_fn=hypervisor.GetHypervisor):
858
  """Verifies the hvparams. Appends the results to the 'results' list.
859

860
  @type what: C{dict}
861
  @param what: a dictionary of things to check
862
  @type vm_capable: boolean
863
  @param vm_capable: whether or not this node is vm capable
864
  @type result: dict
865
  @param result: dictionary of verification results; results of the
866
    verifications in this function will be added here
867
  @type get_hv_fn: function
868
  @param get_hv_fn: function to retrieve the hypervisor, to improve testability
869

870
  """
871
  if not vm_capable:
872
    return
873

    
874
  if constants.NV_HVPARAMS in what:
875
    result[constants.NV_HVPARAMS] = []
876
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
877
      try:
878
        logging.info("Validating hv %s, %s", hv_name, hvparms)
879
        get_hv_fn(hv_name).ValidateParameters(hvparms)
880
      except errors.HypervisorError, err:
881
        result[constants.NV_HVPARAMS].append((source, hv_name, str(err)))
882

    
883

    
884
def _VerifyInstanceList(what, vm_capable, result, all_hvparams):
885
  """Verifies the instance list.
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_INSTANCELIST in what and vm_capable:
899
    # GetInstanceList can fail
900
    try:
901
      val = GetInstanceList(what[constants.NV_INSTANCELIST],
902
                            all_hvparams=all_hvparams)
903
    except RPCFail, err:
904
      val = str(err)
905
    result[constants.NV_INSTANCELIST] = val
906

    
907

    
908
def _VerifyNodeInfo(what, vm_capable, result, all_hvparams):
909
  """Verifies the node info.
910

911
  @type what: C{dict}
912
  @param what: a dictionary of things to check
913
  @type vm_capable: boolean
914
  @param vm_capable: whether or not this node is vm capable
915
  @type result: dict
916
  @param result: dictionary of verification results; results of the
917
    verifications in this function will be added here
918
  @type all_hvparams: dict of dict of string
919
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
920

921
  """
922
  if constants.NV_HVINFO in what and vm_capable:
923
    hvname = what[constants.NV_HVINFO]
924
    hyper = hypervisor.GetHypervisor(hvname)
925
    hvparams = all_hvparams[hvname]
926
    result[constants.NV_HVINFO] = hyper.GetNodeInfo(hvparams=hvparams)
927

    
928

    
929
def VerifyNode(what, cluster_name, all_hvparams):
930
  """Verify the status of the local node.
931

932
  Based on the input L{what} parameter, various checks are done on the
933
  local node.
934

935
  If the I{filelist} key is present, this list of
936
  files is checksummed and the file/checksum pairs are returned.
937

938
  If the I{nodelist} key is present, we check that we have
939
  connectivity via ssh with the target nodes (and check the hostname
940
  report).
941

942
  If the I{node-net-test} key is present, we check that we have
943
  connectivity to the given nodes via both primary IP and, if
944
  applicable, secondary IPs.
945

946
  @type what: C{dict}
947
  @param what: a dictionary of things to check:
948
      - filelist: list of files for which to compute checksums
949
      - nodelist: list of nodes we should check ssh communication with
950
      - node-net-test: list of nodes we should check node daemon port
951
        connectivity with
952
      - hypervisor: list with hypervisors to run the verify for
953
  @type cluster_name: string
954
  @param cluster_name: the cluster's name
955
  @type all_hvparams: dict of dict of strings
956
  @param all_hvparams: a dictionary mapping hypervisor names to hvparams
957
  @rtype: dict
958
  @return: a dictionary with the same keys as the input dict, and
959
      values representing the result of the checks
960

961
  """
962
  result = {}
963
  my_name = netutils.Hostname.GetSysName()
964
  port = netutils.GetDaemonPort(constants.NODED)
965
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
966

    
967
  _VerifyHypervisors(what, vm_capable, result, all_hvparams)
968
  _VerifyHvparams(what, vm_capable, result)
969

    
970
  if constants.NV_FILELIST in what:
971
    fingerprints = utils.FingerprintFiles(map(vcluster.LocalizeVirtualPath,
972
                                              what[constants.NV_FILELIST]))
973
    result[constants.NV_FILELIST] = \
974
      dict((vcluster.MakeVirtualPath(key), value)
975
           for (key, value) in fingerprints.items())
976

    
977
  if constants.NV_NODELIST in what:
978
    (nodes, bynode) = what[constants.NV_NODELIST]
979

    
980
    # Add nodes from other groups (different for each node)
981
    try:
982
      nodes.extend(bynode[my_name])
983
    except KeyError:
984
      pass
985

    
986
    # Use a random order
987
    random.shuffle(nodes)
988

    
989
    # Try to contact all nodes
990
    val = {}
991
    for node in nodes:
992
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
993
      if not success:
994
        val[node] = message
995

    
996
    result[constants.NV_NODELIST] = val
997

    
998
  if constants.NV_NODENETTEST in what:
999
    result[constants.NV_NODENETTEST] = tmp = {}
1000
    my_pip = my_sip = None
1001
    for name, pip, sip in what[constants.NV_NODENETTEST]:
1002
      if name == my_name:
1003
        my_pip = pip
1004
        my_sip = sip
1005
        break
1006
    if not my_pip:
1007
      tmp[my_name] = ("Can't find my own primary/secondary IP"
1008
                      " in the node list")
1009
    else:
1010
      for name, pip, sip in what[constants.NV_NODENETTEST]:
1011
        fail = []
1012
        if not netutils.TcpPing(pip, port, source=my_pip):
1013
          fail.append("primary")
1014
        if sip != pip:
1015
          if not netutils.TcpPing(sip, port, source=my_sip):
1016
            fail.append("secondary")
1017
        if fail:
1018
          tmp[name] = ("failure using the %s interface(s)" %
1019
                       " and ".join(fail))
1020

    
1021
  if constants.NV_MASTERIP in what:
1022
    # FIXME: add checks on incoming data structures (here and in the
1023
    # rest of the function)
1024
    master_name, master_ip = what[constants.NV_MASTERIP]
1025
    if master_name == my_name:
1026
      source = constants.IP4_ADDRESS_LOCALHOST
1027
    else:
1028
      source = None
1029
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
1030
                                                     source=source)
1031

    
1032
  if constants.NV_USERSCRIPTS in what:
1033
    result[constants.NV_USERSCRIPTS] = \
1034
      [script for script in what[constants.NV_USERSCRIPTS]
1035
       if not utils.IsExecutable(script)]
1036

    
1037
  if constants.NV_OOB_PATHS in what:
1038
    result[constants.NV_OOB_PATHS] = tmp = []
1039
    for path in what[constants.NV_OOB_PATHS]:
1040
      try:
1041
        st = os.stat(path)
1042
      except OSError, err:
1043
        tmp.append("error stating out of band helper: %s" % err)
1044
      else:
1045
        if stat.S_ISREG(st.st_mode):
1046
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
1047
            tmp.append(None)
1048
          else:
1049
            tmp.append("out of band helper %s is not executable" % path)
1050
        else:
1051
          tmp.append("out of band helper %s is not a file" % path)
1052

    
1053
  if constants.NV_LVLIST in what and vm_capable:
1054
    try:
1055
      val = GetVolumeList(utils.ListVolumeGroups().keys())
1056
    except RPCFail, err:
1057
      val = str(err)
1058
    result[constants.NV_LVLIST] = val
1059

    
1060
  _VerifyInstanceList(what, vm_capable, result, all_hvparams)
1061

    
1062
  if constants.NV_VGLIST in what and vm_capable:
1063
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
1064

    
1065
  if constants.NV_PVLIST in what and vm_capable:
1066
    check_exclusive_pvs = constants.NV_EXCLUSIVEPVS in what
1067
    val = bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
1068
                                       filter_allocatable=False,
1069
                                       include_lvs=check_exclusive_pvs)
1070
    if check_exclusive_pvs:
1071
      result[constants.NV_EXCLUSIVEPVS] = _CheckExclusivePvs(val)
1072
      for pvi in val:
1073
        # Avoid sending useless data on the wire
1074
        pvi.lv_list = []
1075
    result[constants.NV_PVLIST] = map(objects.LvmPvInfo.ToDict, val)
1076

    
1077
  if constants.NV_VERSION in what:
1078
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
1079
                                    constants.RELEASE_VERSION)
1080

    
1081
  _VerifyNodeInfo(what, vm_capable, result, all_hvparams)
1082

    
1083
  if constants.NV_DRBDVERSION in what and vm_capable:
1084
    try:
1085
      drbd_version = DRBD8.GetProcInfo().GetVersionString()
1086
    except errors.BlockDeviceError, err:
1087
      logging.warning("Can't get DRBD version", exc_info=True)
1088
      drbd_version = str(err)
1089
    result[constants.NV_DRBDVERSION] = drbd_version
1090

    
1091
  if constants.NV_DRBDLIST in what and vm_capable:
1092
    try:
1093
      used_minors = drbd.DRBD8.GetUsedDevs()
1094
    except errors.BlockDeviceError, err:
1095
      logging.warning("Can't get used minors list", exc_info=True)
1096
      used_minors = str(err)
1097
    result[constants.NV_DRBDLIST] = used_minors
1098

    
1099
  if constants.NV_DRBDHELPER in what and vm_capable:
1100
    status = True
1101
    try:
1102
      payload = drbd.DRBD8.GetUsermodeHelper()
1103
    except errors.BlockDeviceError, err:
1104
      logging.error("Can't get DRBD usermode helper: %s", str(err))
1105
      status = False
1106
      payload = str(err)
1107
    result[constants.NV_DRBDHELPER] = (status, payload)
1108

    
1109
  if constants.NV_NODESETUP in what:
1110
    result[constants.NV_NODESETUP] = tmpr = []
1111
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
1112
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
1113
                  " under /sys, missing required directories /sys/block"
1114
                  " and /sys/class/net")
1115
    if (not os.path.isdir("/proc/sys") or
1116
        not os.path.isfile("/proc/sysrq-trigger")):
1117
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
1118
                  " under /proc, missing required directory /proc/sys and"
1119
                  " the file /proc/sysrq-trigger")
1120

    
1121
  if constants.NV_TIME in what:
1122
    result[constants.NV_TIME] = utils.SplitTime(time.time())
1123

    
1124
  if constants.NV_OSLIST in what and vm_capable:
1125
    result[constants.NV_OSLIST] = DiagnoseOS()
1126

    
1127
  if constants.NV_BRIDGES in what and vm_capable:
1128
    result[constants.NV_BRIDGES] = [bridge
1129
                                    for bridge in what[constants.NV_BRIDGES]
1130
                                    if not utils.BridgeExists(bridge)]
1131

    
1132
  if what.get(constants.NV_FILE_STORAGE_PATHS) == my_name:
1133
    result[constants.NV_FILE_STORAGE_PATHS] = \
1134
      bdev.ComputeWrongFileStoragePaths()
1135

    
1136
  return result
1137

    
1138

    
1139
def GetBlockDevSizes(devices):
1140
  """Return the size of the given block devices
1141

1142
  @type devices: list
1143
  @param devices: list of block device nodes to query
1144
  @rtype: dict
1145
  @return:
1146
    dictionary of all block devices under /dev (key). The value is their
1147
    size in MiB.
1148

1149
    {'/dev/disk/by-uuid/123456-12321231-312312-312': 124}
1150

1151
  """
1152
  DEV_PREFIX = "/dev/"
1153
  blockdevs = {}
1154

    
1155
  for devpath in devices:
1156
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
1157
      continue
1158

    
1159
    try:
1160
      st = os.stat(devpath)
1161
    except EnvironmentError, err:
1162
      logging.warning("Error stat()'ing device %s: %s", devpath, str(err))
1163
      continue
1164

    
1165
    if stat.S_ISBLK(st.st_mode):
1166
      result = utils.RunCmd(["blockdev", "--getsize64", devpath])
1167
      if result.failed:
1168
        # We don't want to fail, just do not list this device as available
1169
        logging.warning("Cannot get size for block device %s", devpath)
1170
        continue
1171

    
1172
      size = int(result.stdout) / (1024 * 1024)
1173
      blockdevs[devpath] = size
1174
  return blockdevs
1175

    
1176

    
1177
def GetVolumeList(vg_names):
1178
  """Compute list of logical volumes and their size.
1179

1180
  @type vg_names: list
1181
  @param vg_names: the volume groups whose LVs we should list, or
1182
      empty for all volume groups
1183
  @rtype: dict
1184
  @return:
1185
      dictionary of all partions (key) with value being a tuple of
1186
      their size (in MiB), inactive and online status::
1187

1188
        {'xenvg/test1': ('20.06', True, True)}
1189

1190
      in case of errors, a string is returned with the error
1191
      details.
1192

1193
  """
1194
  lvs = {}
1195
  sep = "|"
1196
  if not vg_names:
1197
    vg_names = []
1198
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1199
                         "--separator=%s" % sep,
1200
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
1201
  if result.failed:
1202
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
1203

    
1204
  for line in result.stdout.splitlines():
1205
    line = line.strip()
1206
    match = _LVSLINE_REGEX.match(line)
1207
    if not match:
1208
      logging.error("Invalid line returned from lvs output: '%s'", line)
1209
      continue
1210
    vg_name, name, size, attr = match.groups()
1211
    inactive = attr[4] == "-"
1212
    online = attr[5] == "o"
1213
    virtual = attr[0] == "v"
1214
    if virtual:
1215
      # we don't want to report such volumes as existing, since they
1216
      # don't really hold data
1217
      continue
1218
    lvs[vg_name + "/" + name] = (size, inactive, online)
1219

    
1220
  return lvs
1221

    
1222

    
1223
def ListVolumeGroups():
1224
  """List the volume groups and their size.
1225

1226
  @rtype: dict
1227
  @return: dictionary with keys volume name and values the
1228
      size of the volume
1229

1230
  """
1231
  return utils.ListVolumeGroups()
1232

    
1233

    
1234
def NodeVolumes():
1235
  """List all volumes on this node.
1236

1237
  @rtype: list
1238
  @return:
1239
    A list of dictionaries, each having four keys:
1240
      - name: the logical volume name,
1241
      - size: the size of the logical volume
1242
      - dev: the physical device on which the LV lives
1243
      - vg: the volume group to which it belongs
1244

1245
    In case of errors, we return an empty list and log the
1246
    error.
1247

1248
    Note that since a logical volume can live on multiple physical
1249
    volumes, the resulting list might include a logical volume
1250
    multiple times.
1251

1252
  """
1253
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
1254
                         "--separator=|",
1255
                         "--options=lv_name,lv_size,devices,vg_name"])
1256
  if result.failed:
1257
    _Fail("Failed to list logical volumes, lvs output: %s",
1258
          result.output)
1259

    
1260
  def parse_dev(dev):
1261
    return dev.split("(")[0]
1262

    
1263
  def handle_dev(dev):
1264
    return [parse_dev(x) for x in dev.split(",")]
1265

    
1266
  def map_line(line):
1267
    line = [v.strip() for v in line]
1268
    return [{"name": line[0], "size": line[1],
1269
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
1270

    
1271
  all_devs = []
1272
  for line in result.stdout.splitlines():
1273
    if line.count("|") >= 3:
1274
      all_devs.extend(map_line(line.split("|")))
1275
    else:
1276
      logging.warning("Strange line in the output from lvs: '%s'", line)
1277
  return all_devs
1278

    
1279

    
1280
def BridgesExist(bridges_list):
1281
  """Check if a list of bridges exist on the current node.
1282

1283
  @rtype: boolean
1284
  @return: C{True} if all of them exist, C{False} otherwise
1285

1286
  """
1287
  missing = []
1288
  for bridge in bridges_list:
1289
    if not utils.BridgeExists(bridge):
1290
      missing.append(bridge)
1291

    
1292
  if missing:
1293
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
1294

    
1295

    
1296
def GetInstanceListForHypervisor(hname, hvparams=None,
1297
                                 get_hv_fn=hypervisor.GetHypervisor):
1298
  """Provides a list of instances of the given hypervisor.
1299

1300
  @type hname: string
1301
  @param hname: name of the hypervisor
1302
  @type hvparams: dict of strings
1303
  @param hvparams: hypervisor parameters for the given hypervisor
1304
  @type get_hv_fn: function
1305
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1306
    name; optional parameter to increase testability
1307

1308
  @rtype: list
1309
  @return: a list of all running instances on the current node
1310
    - instance1.example.com
1311
    - instance2.example.com
1312

1313
  """
1314
  results = []
1315
  try:
1316
    hv = get_hv_fn(hname)
1317
    names = hv.ListInstances(hvparams=hvparams)
1318
    results.extend(names)
1319
  except errors.HypervisorError, err:
1320
    _Fail("Error enumerating instances (hypervisor %s): %s",
1321
          hname, err, exc=True)
1322
  return results
1323

    
1324

    
1325
def GetInstanceList(hypervisor_list, all_hvparams=None,
1326
                    get_hv_fn=hypervisor.GetHypervisor):
1327
  """Provides a list of instances.
1328

1329
  @type hypervisor_list: list
1330
  @param hypervisor_list: the list of hypervisors to query information
1331
  @type all_hvparams: dict of dict of strings
1332
  @param all_hvparams: a dictionary mapping hypervisor types to respective
1333
    cluster-wide hypervisor parameters
1334
  @type get_hv_fn: function
1335
  @param get_hv_fn: function that returns a hypervisor for the given hypervisor
1336
    name; optional parameter to increase testability
1337

1338
  @rtype: list
1339
  @return: a list of all running instances on the current node
1340
    - instance1.example.com
1341
    - instance2.example.com
1342

1343
  """
1344
  results = []
1345
  for hname in hypervisor_list:
1346
    hvparams = all_hvparams[hname]
1347
    results.extend(GetInstanceListForHypervisor(hname, hvparams=hvparams,
1348
                                                get_hv_fn=get_hv_fn))
1349
  return results
1350

    
1351

    
1352
def GetInstanceInfo(instance, hname, hvparams=None):
1353
  """Gives back the information about an instance as a dictionary.
1354

1355
  @type instance: string
1356
  @param instance: the instance name
1357
  @type hname: string
1358
  @param hname: the hypervisor type of the instance
1359
  @type hvparams: dict of strings
1360
  @param hvparams: the instance's hvparams
1361

1362
  @rtype: dict
1363
  @return: dictionary with the following keys:
1364
      - memory: memory size of instance (int)
1365
      - state: xen state of instance (string)
1366
      - time: cpu time of instance (float)
1367
      - vcpus: the number of vcpus (int)
1368

1369
  """
1370
  output = {}
1371

    
1372
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance,
1373
                                                          hvparams=hvparams)
1374
  if iinfo is not None:
1375
    output["memory"] = iinfo[2]
1376
    output["vcpus"] = iinfo[3]
1377
    output["state"] = iinfo[4]
1378
    output["time"] = iinfo[5]
1379

    
1380
  return output
1381

    
1382

    
1383
def GetInstanceMigratable(instance):
1384
  """Computes whether an instance can be migrated.
1385

1386
  @type instance: L{objects.Instance}
1387
  @param instance: object representing the instance to be checked.
1388

1389
  @rtype: tuple
1390
  @return: tuple of (result, description) where:
1391
      - result: whether the instance can be migrated or not
1392
      - description: a description of the issue, if relevant
1393

1394
  """
1395
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1396
  iname = instance.name
1397
  if iname not in hyper.ListInstances(instance.hvparams):
1398
    _Fail("Instance %s is not running", iname)
1399

    
1400
  for idx in range(len(instance.disks)):
1401
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1402
    if not os.path.islink(link_name):
1403
      logging.warning("Instance %s is missing symlink %s for disk %d",
1404
                      iname, link_name, idx)
1405

    
1406

    
1407
def GetAllInstancesInfo(hypervisor_list, all_hvparams):
1408
  """Gather data about all instances.
1409

1410
  This is the equivalent of L{GetInstanceInfo}, except that it
1411
  computes data for all instances at once, thus being faster if one
1412
  needs data about more than one instance.
1413

1414
  @type hypervisor_list: list
1415
  @param hypervisor_list: list of hypervisors to query for instance data
1416
  @type all_hvparams: dict of dict of strings
1417
  @param all_hvparams: mapping of hypervisor names to hvparams
1418

1419
  @rtype: dict
1420
  @return: dictionary of instance: data, with data having the following keys:
1421
      - memory: memory size of instance (int)
1422
      - state: xen state of instance (string)
1423
      - time: cpu time of instance (float)
1424
      - vcpus: the number of vcpus
1425

1426
  """
1427
  output = {}
1428

    
1429
  for hname in hypervisor_list:
1430
    hvparams = all_hvparams[hname]
1431
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo(hvparams)
1432
    if iinfo:
1433
      for name, _, memory, vcpus, state, times in iinfo:
1434
        value = {
1435
          "memory": memory,
1436
          "vcpus": vcpus,
1437
          "state": state,
1438
          "time": times,
1439
          }
1440
        if name in output:
1441
          # we only check static parameters, like memory and vcpus,
1442
          # and not state and time which can change between the
1443
          # invocations of the different hypervisors
1444
          for key in "memory", "vcpus":
1445
            if value[key] != output[name][key]:
1446
              _Fail("Instance %s is running twice"
1447
                    " with different parameters", name)
1448
        output[name] = value
1449

    
1450
  return output
1451

    
1452

    
1453
def _InstanceLogName(kind, os_name, instance, component):
1454
  """Compute the OS log filename for a given instance and operation.
1455

1456
  The instance name and os name are passed in as strings since not all
1457
  operations have these as part of an instance object.
1458

1459
  @type kind: string
1460
  @param kind: the operation type (e.g. add, import, etc.)
1461
  @type os_name: string
1462
  @param os_name: the os name
1463
  @type instance: string
1464
  @param instance: the name of the instance being imported/added/etc.
1465
  @type component: string or None
1466
  @param component: the name of the component of the instance being
1467
      transferred
1468

1469
  """
1470
  # TODO: Use tempfile.mkstemp to create unique filename
1471
  if component:
1472
    assert "/" not in component
1473
    c_msg = "-%s" % component
1474
  else:
1475
    c_msg = ""
1476
  base = ("%s-%s-%s%s-%s.log" %
1477
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1478
  return utils.PathJoin(pathutils.LOG_OS_DIR, base)
1479

    
1480

    
1481
def InstanceOsAdd(instance, reinstall, debug):
1482
  """Add an OS to an instance.
1483

1484
  @type instance: L{objects.Instance}
1485
  @param instance: Instance whose OS is to be installed
1486
  @type reinstall: boolean
1487
  @param reinstall: whether this is an instance reinstall
1488
  @type debug: integer
1489
  @param debug: debug level, passed to the OS scripts
1490
  @rtype: None
1491

1492
  """
1493
  inst_os = OSFromDisk(instance.os)
1494

    
1495
  create_env = OSEnvironment(instance, inst_os, debug)
1496
  if reinstall:
1497
    create_env["INSTANCE_REINSTALL"] = "1"
1498

    
1499
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1500

    
1501
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1502
                        cwd=inst_os.path, output=logfile, reset_env=True)
1503
  if result.failed:
1504
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1505
                  " output: %s", result.cmd, result.fail_reason, logfile,
1506
                  result.output)
1507
    lines = [utils.SafeEncode(val)
1508
             for val in utils.TailFile(logfile, lines=20)]
1509
    _Fail("OS create script failed (%s), last lines in the"
1510
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1511

    
1512

    
1513
def RunRenameInstance(instance, old_name, debug):
1514
  """Run the OS rename script for an instance.
1515

1516
  @type instance: L{objects.Instance}
1517
  @param instance: Instance whose OS is to be installed
1518
  @type old_name: string
1519
  @param old_name: previous instance name
1520
  @type debug: integer
1521
  @param debug: debug level, passed to the OS scripts
1522
  @rtype: boolean
1523
  @return: the success of the operation
1524

1525
  """
1526
  inst_os = OSFromDisk(instance.os)
1527

    
1528
  rename_env = OSEnvironment(instance, inst_os, debug)
1529
  rename_env["OLD_INSTANCE_NAME"] = old_name
1530

    
1531
  logfile = _InstanceLogName("rename", instance.os,
1532
                             "%s-%s" % (old_name, instance.name), None)
1533

    
1534
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1535
                        cwd=inst_os.path, output=logfile, reset_env=True)
1536

    
1537
  if result.failed:
1538
    logging.error("os create command '%s' returned error: %s output: %s",
1539
                  result.cmd, result.fail_reason, result.output)
1540
    lines = [utils.SafeEncode(val)
1541
             for val in utils.TailFile(logfile, lines=20)]
1542
    _Fail("OS rename script failed (%s), last lines in the"
1543
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1544

    
1545

    
1546
def _GetBlockDevSymlinkPath(instance_name, idx, _dir=None):
1547
  """Returns symlink path for block device.
1548

1549
  """
1550
  if _dir is None:
1551
    _dir = pathutils.DISK_LINKS_DIR
1552

    
1553
  return utils.PathJoin(_dir,
1554
                        ("%s%s%s" %
1555
                         (instance_name, constants.DISK_SEPARATOR, idx)))
1556

    
1557

    
1558
def _SymlinkBlockDev(instance_name, device_path, idx):
1559
  """Set up symlinks to a instance's block device.
1560

1561
  This is an auxiliary function run when an instance is start (on the primary
1562
  node) or when an instance is migrated (on the target node).
1563

1564

1565
  @param instance_name: the name of the target instance
1566
  @param device_path: path of the physical block device, on the node
1567
  @param idx: the disk index
1568
  @return: absolute path to the disk's symlink
1569

1570
  """
1571
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1572
  try:
1573
    os.symlink(device_path, link_name)
1574
  except OSError, err:
1575
    if err.errno == errno.EEXIST:
1576
      if (not os.path.islink(link_name) or
1577
          os.readlink(link_name) != device_path):
1578
        os.remove(link_name)
1579
        os.symlink(device_path, link_name)
1580
    else:
1581
      raise
1582

    
1583
  return link_name
1584

    
1585

    
1586
def _RemoveBlockDevLinks(instance_name, disks):
1587
  """Remove the block device symlinks belonging to the given instance.
1588

1589
  """
1590
  for idx, _ in enumerate(disks):
1591
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1592
    if os.path.islink(link_name):
1593
      try:
1594
        os.remove(link_name)
1595
      except OSError:
1596
        logging.exception("Can't remove symlink '%s'", link_name)
1597

    
1598

    
1599
def _GatherAndLinkBlockDevs(instance):
1600
  """Set up an instance's block device(s).
1601

1602
  This is run on the primary node at instance startup. The block
1603
  devices must be already assembled.
1604

1605
  @type instance: L{objects.Instance}
1606
  @param instance: the instance whose disks we shoul assemble
1607
  @rtype: list
1608
  @return: list of (disk_object, device_path)
1609

1610
  """
1611
  block_devices = []
1612
  for idx, disk in enumerate(instance.disks):
1613
    device = _RecursiveFindBD(disk)
1614
    if device is None:
1615
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1616
                                    str(disk))
1617
    device.Open()
1618
    try:
1619
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1620
    except OSError, e:
1621
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1622
                                    e.strerror)
1623

    
1624
    block_devices.append((disk, link_name))
1625

    
1626
  return block_devices
1627

    
1628

    
1629
def StartInstance(instance, startup_paused, reason, store_reason=True):
1630
  """Start an instance.
1631

1632
  @type instance: L{objects.Instance}
1633
  @param instance: the instance object
1634
  @type startup_paused: bool
1635
  @param instance: pause instance at startup?
1636
  @type reason: list of reasons
1637
  @param reason: the reason trail for this startup
1638
  @type store_reason: boolean
1639
  @param store_reason: whether to store the shutdown reason trail on file
1640
  @rtype: None
1641

1642
  """
1643
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1644
                                                   instance.hvparams)
1645

    
1646
  if instance.name in running_instances:
1647
    logging.info("Instance %s already running, not starting", instance.name)
1648
    return
1649

    
1650
  try:
1651
    block_devices = _GatherAndLinkBlockDevs(instance)
1652
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1653
    hyper.StartInstance(instance, block_devices, startup_paused)
1654
    if store_reason:
1655
      _StoreInstReasonTrail(instance.name, reason)
1656
  except errors.BlockDeviceError, err:
1657
    _Fail("Block device error: %s", err, exc=True)
1658
  except errors.HypervisorError, err:
1659
    _RemoveBlockDevLinks(instance.name, instance.disks)
1660
    _Fail("Hypervisor error: %s", err, exc=True)
1661

    
1662

    
1663
def InstanceShutdown(instance, timeout, reason, store_reason=True):
1664
  """Shut an instance down.
1665

1666
  @note: this functions uses polling with a hardcoded timeout.
1667

1668
  @type instance: L{objects.Instance}
1669
  @param instance: the instance object
1670
  @type timeout: integer
1671
  @param timeout: maximum timeout for soft shutdown
1672
  @type reason: list of reasons
1673
  @param reason: the reason trail for this shutdown
1674
  @type store_reason: boolean
1675
  @param store_reason: whether to store the shutdown reason trail on file
1676
  @rtype: None
1677

1678
  """
1679
  hv_name = instance.hypervisor
1680
  hyper = hypervisor.GetHypervisor(hv_name)
1681
  iname = instance.name
1682

    
1683
  if instance.name not in hyper.ListInstances(instance.hvparams):
1684
    logging.info("Instance %s not running, doing nothing", iname)
1685
    return
1686

    
1687
  class _TryShutdown:
1688
    def __init__(self):
1689
      self.tried_once = False
1690

    
1691
    def __call__(self):
1692
      if iname not in hyper.ListInstances(instance.hvparams):
1693
        return
1694

    
1695
      try:
1696
        hyper.StopInstance(instance, retry=self.tried_once)
1697
        if store_reason:
1698
          _StoreInstReasonTrail(instance.name, reason)
1699
      except errors.HypervisorError, err:
1700
        if iname not in hyper.ListInstances(instance.hvparams):
1701
          # if the instance is no longer existing, consider this a
1702
          # success and go to cleanup
1703
          return
1704

    
1705
        _Fail("Failed to stop instance %s: %s", iname, err)
1706

    
1707
      self.tried_once = True
1708

    
1709
      raise utils.RetryAgain()
1710

    
1711
  try:
1712
    utils.Retry(_TryShutdown(), 5, timeout)
1713
  except utils.RetryTimeout:
1714
    # the shutdown did not succeed
1715
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1716

    
1717
    try:
1718
      hyper.StopInstance(instance, force=True)
1719
    except errors.HypervisorError, err:
1720
      if iname in hyper.ListInstances(instance.hvparams):
1721
        # only raise an error if the instance still exists, otherwise
1722
        # the error could simply be "instance ... unknown"!
1723
        _Fail("Failed to force stop instance %s: %s", iname, err)
1724

    
1725
    time.sleep(1)
1726

    
1727
    if iname in hyper.ListInstances(instance.hvparams):
1728
      _Fail("Could not shutdown instance %s even by destroy", iname)
1729

    
1730
  try:
1731
    hyper.CleanupInstance(instance.name)
1732
  except errors.HypervisorError, err:
1733
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1734

    
1735
  _RemoveBlockDevLinks(iname, instance.disks)
1736

    
1737

    
1738
def InstanceReboot(instance, reboot_type, shutdown_timeout, reason):
1739
  """Reboot an instance.
1740

1741
  @type instance: L{objects.Instance}
1742
  @param instance: the instance object to reboot
1743
  @type reboot_type: str
1744
  @param reboot_type: the type of reboot, one the following
1745
    constants:
1746
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1747
        instance OS, do not recreate the VM
1748
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1749
        restart the VM (at the hypervisor level)
1750
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1751
        not accepted here, since that mode is handled differently, in
1752
        cmdlib, and translates into full stop and start of the
1753
        instance (instead of a call_instance_reboot RPC)
1754
  @type shutdown_timeout: integer
1755
  @param shutdown_timeout: maximum timeout for soft shutdown
1756
  @type reason: list of reasons
1757
  @param reason: the reason trail for this reboot
1758
  @rtype: None
1759

1760
  """
1761
  running_instances = GetInstanceListForHypervisor(instance.hypervisor,
1762
                                                   instance.hvparams)
1763

    
1764
  if instance.name not in running_instances:
1765
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1766

    
1767
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1768
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1769
    try:
1770
      hyper.RebootInstance(instance)
1771
    except errors.HypervisorError, err:
1772
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1773
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1774
    try:
1775
      InstanceShutdown(instance, shutdown_timeout, reason, store_reason=False)
1776
      result = StartInstance(instance, False, reason, store_reason=False)
1777
      _StoreInstReasonTrail(instance.name, reason)
1778
      return result
1779
    except errors.HypervisorError, err:
1780
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1781
  else:
1782
    _Fail("Invalid reboot_type received: %s", reboot_type)
1783

    
1784

    
1785
def InstanceBalloonMemory(instance, memory):
1786
  """Resize an instance's memory.
1787

1788
  @type instance: L{objects.Instance}
1789
  @param instance: the instance object
1790
  @type memory: int
1791
  @param memory: new memory amount in MB
1792
  @rtype: None
1793

1794
  """
1795
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1796
  running = hyper.ListInstances(instance.hvparams)
1797
  if instance.name not in running:
1798
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1799
    return
1800
  try:
1801
    hyper.BalloonInstanceMemory(instance, memory)
1802
  except errors.HypervisorError, err:
1803
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1804

    
1805

    
1806
def MigrationInfo(instance):
1807
  """Gather information about an instance to be migrated.
1808

1809
  @type instance: L{objects.Instance}
1810
  @param instance: the instance definition
1811

1812
  """
1813
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1814
  try:
1815
    info = hyper.MigrationInfo(instance)
1816
  except errors.HypervisorError, err:
1817
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1818
  return info
1819

    
1820

    
1821
def AcceptInstance(instance, info, target):
1822
  """Prepare the node to accept an instance.
1823

1824
  @type instance: L{objects.Instance}
1825
  @param instance: the instance definition
1826
  @type info: string/data (opaque)
1827
  @param info: migration information, from the source node
1828
  @type target: string
1829
  @param target: target host (usually ip), on this node
1830

1831
  """
1832
  # TODO: why is this required only for DTS_EXT_MIRROR?
1833
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1834
    # Create the symlinks, as the disks are not active
1835
    # in any way
1836
    try:
1837
      _GatherAndLinkBlockDevs(instance)
1838
    except errors.BlockDeviceError, err:
1839
      _Fail("Block device error: %s", err, exc=True)
1840

    
1841
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1842
  try:
1843
    hyper.AcceptInstance(instance, info, target)
1844
  except errors.HypervisorError, err:
1845
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1846
      _RemoveBlockDevLinks(instance.name, instance.disks)
1847
    _Fail("Failed to accept instance: %s", err, exc=True)
1848

    
1849

    
1850
def FinalizeMigrationDst(instance, info, success):
1851
  """Finalize any preparation to accept an instance.
1852

1853
  @type instance: L{objects.Instance}
1854
  @param instance: the instance definition
1855
  @type info: string/data (opaque)
1856
  @param info: migration information, from the source node
1857
  @type success: boolean
1858
  @param success: whether the migration was a success or a failure
1859

1860
  """
1861
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1862
  try:
1863
    hyper.FinalizeMigrationDst(instance, info, success)
1864
  except errors.HypervisorError, err:
1865
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1866

    
1867

    
1868
def MigrateInstance(cluster_name, instance, target, live):
1869
  """Migrates an instance to another node.
1870

1871
  @type cluster_name: string
1872
  @param cluster_name: name of the cluster
1873
  @type instance: L{objects.Instance}
1874
  @param instance: the instance definition
1875
  @type target: string
1876
  @param target: the target node name
1877
  @type live: boolean
1878
  @param live: whether the migration should be done live or not (the
1879
      interpretation of this parameter is left to the hypervisor)
1880
  @raise RPCFail: if migration fails for some reason
1881

1882
  """
1883
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1884

    
1885
  try:
1886
    hyper.MigrateInstance(cluster_name, instance, target, live)
1887
  except errors.HypervisorError, err:
1888
    _Fail("Failed to migrate instance: %s", err, exc=True)
1889

    
1890

    
1891
def FinalizeMigrationSource(instance, success, live):
1892
  """Finalize the instance migration on the source node.
1893

1894
  @type instance: L{objects.Instance}
1895
  @param instance: the instance definition of the migrated instance
1896
  @type success: bool
1897
  @param success: whether the migration succeeded or not
1898
  @type live: bool
1899
  @param live: whether the user requested a live migration or not
1900
  @raise RPCFail: If the execution fails for some reason
1901

1902
  """
1903
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1904

    
1905
  try:
1906
    hyper.FinalizeMigrationSource(instance, success, live)
1907
  except Exception, err:  # pylint: disable=W0703
1908
    _Fail("Failed to finalize the migration on the source node: %s", err,
1909
          exc=True)
1910

    
1911

    
1912
def GetMigrationStatus(instance):
1913
  """Get the migration status
1914

1915
  @type instance: L{objects.Instance}
1916
  @param instance: the instance that is being migrated
1917
  @rtype: L{objects.MigrationStatus}
1918
  @return: the status of the current migration (one of
1919
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1920
           progress info that can be retrieved from the hypervisor
1921
  @raise RPCFail: If the migration status cannot be retrieved
1922

1923
  """
1924
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1925
  try:
1926
    return hyper.GetMigrationStatus(instance)
1927
  except Exception, err:  # pylint: disable=W0703
1928
    _Fail("Failed to get migration status: %s", err, exc=True)
1929

    
1930

    
1931
def BlockdevCreate(disk, size, owner, on_primary, info, excl_stor):
1932
  """Creates a block device for an instance.
1933

1934
  @type disk: L{objects.Disk}
1935
  @param disk: the object describing the disk we should create
1936
  @type size: int
1937
  @param size: the size of the physical underlying device, in MiB
1938
  @type owner: str
1939
  @param owner: the name of the instance for which disk is created,
1940
      used for device cache data
1941
  @type on_primary: boolean
1942
  @param on_primary:  indicates if it is the primary node or not
1943
  @type info: string
1944
  @param info: string that will be sent to the physical device
1945
      creation, used for example to set (LVM) tags on LVs
1946
  @type excl_stor: boolean
1947
  @param excl_stor: Whether exclusive_storage is active
1948

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

1953
  """
1954
  # TODO: remove the obsolete "size" argument
1955
  # pylint: disable=W0613
1956
  clist = []
1957
  if disk.children:
1958
    for child in disk.children:
1959
      try:
1960
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1961
      except errors.BlockDeviceError, err:
1962
        _Fail("Can't assemble device %s: %s", child, err)
1963
      if on_primary or disk.AssembleOnSecondary():
1964
        # we need the children open in case the device itself has to
1965
        # be assembled
1966
        try:
1967
          # pylint: disable=E1103
1968
          crdev.Open()
1969
        except errors.BlockDeviceError, err:
1970
          _Fail("Can't make child '%s' read-write: %s", child, err)
1971
      clist.append(crdev)
1972

    
1973
  try:
1974
    device = bdev.Create(disk, clist, excl_stor)
1975
  except errors.BlockDeviceError, err:
1976
    _Fail("Can't create block device: %s", err)
1977

    
1978
  if on_primary or disk.AssembleOnSecondary():
1979
    try:
1980
      device.Assemble()
1981
    except errors.BlockDeviceError, err:
1982
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1983
    if on_primary or disk.OpenOnSecondary():
1984
      try:
1985
        device.Open(force=True)
1986
      except errors.BlockDeviceError, err:
1987
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1988
    DevCacheManager.UpdateCache(device.dev_path, owner,
1989
                                on_primary, disk.iv_name)
1990

    
1991
  device.SetInfo(info)
1992

    
1993
  return device.unique_id
1994

    
1995

    
1996
def _WipeDevice(path, offset, size):
1997
  """This function actually wipes the device.
1998

1999
  @param path: The path to the device to wipe
2000
  @param offset: The offset in MiB in the file
2001
  @param size: The size in MiB to write
2002

2003
  """
2004
  # Internal sizes are always in Mebibytes; if the following "dd" command
2005
  # should use a different block size the offset and size given to this
2006
  # function must be adjusted accordingly before being passed to "dd".
2007
  block_size = 1024 * 1024
2008

    
2009
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
2010
         "bs=%s" % block_size, "oflag=direct", "of=%s" % path,
2011
         "count=%d" % size]
2012
  result = utils.RunCmd(cmd)
2013

    
2014
  if result.failed:
2015
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
2016
          result.fail_reason, result.output)
2017

    
2018

    
2019
def BlockdevWipe(disk, offset, size):
2020
  """Wipes a block device.
2021

2022
  @type disk: L{objects.Disk}
2023
  @param disk: the disk object we want to wipe
2024
  @type offset: int
2025
  @param offset: The offset in MiB in the file
2026
  @type size: int
2027
  @param size: The size in MiB to write
2028

2029
  """
2030
  try:
2031
    rdev = _RecursiveFindBD(disk)
2032
  except errors.BlockDeviceError:
2033
    rdev = None
2034

    
2035
  if not rdev:
2036
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
2037

    
2038
  # Do cross verify some of the parameters
2039
  if offset < 0:
2040
    _Fail("Negative offset")
2041
  if size < 0:
2042
    _Fail("Negative size")
2043
  if offset > rdev.size:
2044
    _Fail("Offset is bigger than device size")
2045
  if (offset + size) > rdev.size:
2046
    _Fail("The provided offset and size to wipe is bigger than device size")
2047

    
2048
  _WipeDevice(rdev.dev_path, offset, size)
2049

    
2050

    
2051
def BlockdevPauseResumeSync(disks, pause):
2052
  """Pause or resume the sync of the block device.
2053

2054
  @type disks: list of L{objects.Disk}
2055
  @param disks: the disks object we want to pause/resume
2056
  @type pause: bool
2057
  @param pause: Wheater to pause or resume
2058

2059
  """
2060
  success = []
2061
  for disk in disks:
2062
    try:
2063
      rdev = _RecursiveFindBD(disk)
2064
    except errors.BlockDeviceError:
2065
      rdev = None
2066

    
2067
    if not rdev:
2068
      success.append((False, ("Cannot change sync for device %s:"
2069
                              " device not found" % disk.iv_name)))
2070
      continue
2071

    
2072
    result = rdev.PauseResumeSync(pause)
2073

    
2074
    if result:
2075
      success.append((result, None))
2076
    else:
2077
      if pause:
2078
        msg = "Pause"
2079
      else:
2080
        msg = "Resume"
2081
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
2082

    
2083
  return success
2084

    
2085

    
2086
def BlockdevRemove(disk):
2087
  """Remove a block device.
2088

2089
  @note: This is intended to be called recursively.
2090

2091
  @type disk: L{objects.Disk}
2092
  @param disk: the disk object we should remove
2093
  @rtype: boolean
2094
  @return: the success of the operation
2095

2096
  """
2097
  msgs = []
2098
  try:
2099
    rdev = _RecursiveFindBD(disk)
2100
  except errors.BlockDeviceError, err:
2101
    # probably can't attach
2102
    logging.info("Can't attach to device %s in remove", disk)
2103
    rdev = None
2104
  if rdev is not None:
2105
    r_path = rdev.dev_path
2106
    try:
2107
      rdev.Remove()
2108
    except errors.BlockDeviceError, err:
2109
      msgs.append(str(err))
2110
    if not msgs:
2111
      DevCacheManager.RemoveCache(r_path)
2112

    
2113
  if disk.children:
2114
    for child in disk.children:
2115
      try:
2116
        BlockdevRemove(child)
2117
      except RPCFail, err:
2118
        msgs.append(str(err))
2119

    
2120
  if msgs:
2121
    _Fail("; ".join(msgs))
2122

    
2123

    
2124
def _RecursiveAssembleBD(disk, owner, as_primary):
2125
  """Activate a block device for an instance.
2126

2127
  This is run on the primary and secondary nodes for an instance.
2128

2129
  @note: this function is called recursively.
2130

2131
  @type disk: L{objects.Disk}
2132
  @param disk: the disk we try to assemble
2133
  @type owner: str
2134
  @param owner: the name of the instance which owns the disk
2135
  @type as_primary: boolean
2136
  @param as_primary: if we should make the block device
2137
      read/write
2138

2139
  @return: the assembled device or None (in case no device
2140
      was assembled)
2141
  @raise errors.BlockDeviceError: in case there is an error
2142
      during the activation of the children or the device
2143
      itself
2144

2145
  """
2146
  children = []
2147
  if disk.children:
2148
    mcn = disk.ChildrenNeeded()
2149
    if mcn == -1:
2150
      mcn = 0 # max number of Nones allowed
2151
    else:
2152
      mcn = len(disk.children) - mcn # max number of Nones
2153
    for chld_disk in disk.children:
2154
      try:
2155
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
2156
      except errors.BlockDeviceError, err:
2157
        if children.count(None) >= mcn:
2158
          raise
2159
        cdev = None
2160
        logging.error("Error in child activation (but continuing): %s",
2161
                      str(err))
2162
      children.append(cdev)
2163

    
2164
  if as_primary or disk.AssembleOnSecondary():
2165
    r_dev = bdev.Assemble(disk, children)
2166
    result = r_dev
2167
    if as_primary or disk.OpenOnSecondary():
2168
      r_dev.Open()
2169
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
2170
                                as_primary, disk.iv_name)
2171

    
2172
  else:
2173
    result = True
2174
  return result
2175

    
2176

    
2177
def BlockdevAssemble(disk, owner, as_primary, idx):
2178
  """Activate a block device for an instance.
2179

2180
  This is a wrapper over _RecursiveAssembleBD.
2181

2182
  @rtype: str or boolean
2183
  @return: a C{/dev/...} path for primary nodes, and
2184
      C{True} for secondary nodes
2185

2186
  """
2187
  try:
2188
    result = _RecursiveAssembleBD(disk, owner, as_primary)
2189
    if isinstance(result, BlockDev):
2190
      # pylint: disable=E1103
2191
      result = result.dev_path
2192
      if as_primary:
2193
        _SymlinkBlockDev(owner, result, idx)
2194
  except errors.BlockDeviceError, err:
2195
    _Fail("Error while assembling disk: %s", err, exc=True)
2196
  except OSError, err:
2197
    _Fail("Error while symlinking disk: %s", err, exc=True)
2198

    
2199
  return result
2200

    
2201

    
2202
def BlockdevShutdown(disk):
2203
  """Shut down a block device.
2204

2205
  First, if the device is assembled (Attach() is successful), then
2206
  the device is shutdown. Then the children of the device are
2207
  shutdown.
2208

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

2213
  @type disk: L{objects.Disk}
2214
  @param disk: the description of the disk we should
2215
      shutdown
2216
  @rtype: None
2217

2218
  """
2219
  msgs = []
2220
  r_dev = _RecursiveFindBD(disk)
2221
  if r_dev is not None:
2222
    r_path = r_dev.dev_path
2223
    try:
2224
      r_dev.Shutdown()
2225
      DevCacheManager.RemoveCache(r_path)
2226
    except errors.BlockDeviceError, err:
2227
      msgs.append(str(err))
2228

    
2229
  if disk.children:
2230
    for child in disk.children:
2231
      try:
2232
        BlockdevShutdown(child)
2233
      except RPCFail, err:
2234
        msgs.append(str(err))
2235

    
2236
  if msgs:
2237
    _Fail("; ".join(msgs))
2238

    
2239

    
2240
def BlockdevAddchildren(parent_cdev, new_cdevs):
2241
  """Extend a mirrored block device.
2242

2243
  @type parent_cdev: L{objects.Disk}
2244
  @param parent_cdev: the disk to which we should add children
2245
  @type new_cdevs: list of L{objects.Disk}
2246
  @param new_cdevs: the list of children which we should add
2247
  @rtype: None
2248

2249
  """
2250
  parent_bdev = _RecursiveFindBD(parent_cdev)
2251
  if parent_bdev is None:
2252
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
2253
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
2254
  if new_bdevs.count(None) > 0:
2255
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
2256
  parent_bdev.AddChildren(new_bdevs)
2257

    
2258

    
2259
def BlockdevRemovechildren(parent_cdev, new_cdevs):
2260
  """Shrink a mirrored block device.
2261

2262
  @type parent_cdev: L{objects.Disk}
2263
  @param parent_cdev: the disk from which we should remove children
2264
  @type new_cdevs: list of L{objects.Disk}
2265
  @param new_cdevs: the list of children which we should remove
2266
  @rtype: None
2267

2268
  """
2269
  parent_bdev = _RecursiveFindBD(parent_cdev)
2270
  if parent_bdev is None:
2271
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
2272
  devs = []
2273
  for disk in new_cdevs:
2274
    rpath = disk.StaticDevPath()
2275
    if rpath is None:
2276
      bd = _RecursiveFindBD(disk)
2277
      if bd is None:
2278
        _Fail("Can't find device %s while removing children", disk)
2279
      else:
2280
        devs.append(bd.dev_path)
2281
    else:
2282
      if not utils.IsNormAbsPath(rpath):
2283
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
2284
      devs.append(rpath)
2285
  parent_bdev.RemoveChildren(devs)
2286

    
2287

    
2288
def BlockdevGetmirrorstatus(disks):
2289
  """Get the mirroring status of a list of devices.
2290

2291
  @type disks: list of L{objects.Disk}
2292
  @param disks: the list of disks which we should query
2293
  @rtype: disk
2294
  @return: List of L{objects.BlockDevStatus}, one for each disk
2295
  @raise errors.BlockDeviceError: if any of the disks cannot be
2296
      found
2297

2298
  """
2299
  stats = []
2300
  for dsk in disks:
2301
    rbd = _RecursiveFindBD(dsk)
2302
    if rbd is None:
2303
      _Fail("Can't find device %s", dsk)
2304

    
2305
    stats.append(rbd.CombinedSyncStatus())
2306

    
2307
  return stats
2308

    
2309

    
2310
def BlockdevGetmirrorstatusMulti(disks):
2311
  """Get the mirroring status of a list of devices.
2312

2313
  @type disks: list of L{objects.Disk}
2314
  @param disks: the list of disks which we should query
2315
  @rtype: disk
2316
  @return: List of tuples, (bool, status), one for each disk; bool denotes
2317
    success/failure, status is L{objects.BlockDevStatus} on success, string
2318
    otherwise
2319

2320
  """
2321
  result = []
2322
  for disk in disks:
2323
    try:
2324
      rbd = _RecursiveFindBD(disk)
2325
      if rbd is None:
2326
        result.append((False, "Can't find device %s" % disk))
2327
        continue
2328

    
2329
      status = rbd.CombinedSyncStatus()
2330
    except errors.BlockDeviceError, err:
2331
      logging.exception("Error while getting disk status")
2332
      result.append((False, str(err)))
2333
    else:
2334
      result.append((True, status))
2335

    
2336
  assert len(disks) == len(result)
2337

    
2338
  return result
2339

    
2340

    
2341
def _RecursiveFindBD(disk):
2342
  """Check if a device is activated.
2343

2344
  If so, return information about the real device.
2345

2346
  @type disk: L{objects.Disk}
2347
  @param disk: the disk object we need to find
2348

2349
  @return: None if the device can't be found,
2350
      otherwise the device instance
2351

2352
  """
2353
  children = []
2354
  if disk.children:
2355
    for chdisk in disk.children:
2356
      children.append(_RecursiveFindBD(chdisk))
2357

    
2358
  return bdev.FindDevice(disk, children)
2359

    
2360

    
2361
def _OpenRealBD(disk):
2362
  """Opens the underlying block device of a disk.
2363

2364
  @type disk: L{objects.Disk}
2365
  @param disk: the disk object we want to open
2366

2367
  """
2368
  real_disk = _RecursiveFindBD(disk)
2369
  if real_disk is None:
2370
    _Fail("Block device '%s' is not set up", disk)
2371

    
2372
  real_disk.Open()
2373

    
2374
  return real_disk
2375

    
2376

    
2377
def BlockdevFind(disk):
2378
  """Check if a device is activated.
2379

2380
  If it is, return information about the real device.
2381

2382
  @type disk: L{objects.Disk}
2383
  @param disk: the disk to find
2384
  @rtype: None or objects.BlockDevStatus
2385
  @return: None if the disk cannot be found, otherwise a the current
2386
           information
2387

2388
  """
2389
  try:
2390
    rbd = _RecursiveFindBD(disk)
2391
  except errors.BlockDeviceError, err:
2392
    _Fail("Failed to find device: %s", err, exc=True)
2393

    
2394
  if rbd is None:
2395
    return None
2396

    
2397
  return rbd.GetSyncStatus()
2398

    
2399

    
2400
def BlockdevGetdimensions(disks):
2401
  """Computes the size of the given disks.
2402

2403
  If a disk is not found, returns None instead.
2404

2405
  @type disks: list of L{objects.Disk}
2406
  @param disks: the list of disk to compute the size for
2407
  @rtype: list
2408
  @return: list with elements None if the disk cannot be found,
2409
      otherwise the pair (size, spindles), where spindles is None if the
2410
      device doesn't support that
2411

2412
  """
2413
  result = []
2414
  for cf in disks:
2415
    try:
2416
      rbd = _RecursiveFindBD(cf)
2417
    except errors.BlockDeviceError:
2418
      result.append(None)
2419
      continue
2420
    if rbd is None:
2421
      result.append(None)
2422
    else:
2423
      result.append(rbd.GetActualDimensions())
2424
  return result
2425

    
2426

    
2427
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2428
  """Export a block device to a remote node.
2429

2430
  @type disk: L{objects.Disk}
2431
  @param disk: the description of the disk to export
2432
  @type dest_node: str
2433
  @param dest_node: the destination node to export to
2434
  @type dest_path: str
2435
  @param dest_path: the destination path on the target node
2436
  @type cluster_name: str
2437
  @param cluster_name: the cluster name, needed for SSH hostalias
2438
  @rtype: None
2439

2440
  """
2441
  real_disk = _OpenRealBD(disk)
2442

    
2443
  # the block size on the read dd is 1MiB to match our units
2444
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2445
                               "dd if=%s bs=1048576 count=%s",
2446
                               real_disk.dev_path, str(disk.size))
2447

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

    
2457
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2458
                                                   constants.SSH_LOGIN_USER,
2459
                                                   destcmd)
2460

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

    
2464
  result = utils.RunCmd(["bash", "-c", command])
2465

    
2466
  if result.failed:
2467
    _Fail("Disk copy command '%s' returned error: %s"
2468
          " output: %s", command, result.fail_reason, result.output)
2469

    
2470

    
2471
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2472
  """Write a file to the filesystem.
2473

2474
  This allows the master to overwrite(!) a file. It will only perform
2475
  the operation if the file belongs to a list of configuration files.
2476

2477
  @type file_name: str
2478
  @param file_name: the target file name
2479
  @type data: str
2480
  @param data: the new contents of the file
2481
  @type mode: int
2482
  @param mode: the mode to give the file (can be None)
2483
  @type uid: string
2484
  @param uid: the owner of the file
2485
  @type gid: string
2486
  @param gid: the group of the file
2487
  @type atime: float
2488
  @param atime: the atime to set on the file (can be None)
2489
  @type mtime: float
2490
  @param mtime: the mtime to set on the file (can be None)
2491
  @rtype: None
2492

2493
  """
2494
  file_name = vcluster.LocalizeVirtualPath(file_name)
2495

    
2496
  if not os.path.isabs(file_name):
2497
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2498

    
2499
  if file_name not in _ALLOWED_UPLOAD_FILES:
2500
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2501
          file_name)
2502

    
2503
  raw_data = _Decompress(data)
2504

    
2505
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2506
    _Fail("Invalid username/groupname type")
2507

    
2508
  getents = runtime.GetEnts()
2509
  uid = getents.LookupUser(uid)
2510
  gid = getents.LookupGroup(gid)
2511

    
2512
  utils.SafeWriteFile(file_name, None,
2513
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2514
                      atime=atime, mtime=mtime)
2515

    
2516

    
2517
def RunOob(oob_program, command, node, timeout):
2518
  """Executes oob_program with given command on given node.
2519

2520
  @param oob_program: The path to the executable oob_program
2521
  @param command: The command to invoke on oob_program
2522
  @param node: The node given as an argument to the program
2523
  @param timeout: Timeout after which we kill the oob program
2524

2525
  @return: stdout
2526
  @raise RPCFail: If execution fails for some reason
2527

2528
  """
2529
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2530

    
2531
  if result.failed:
2532
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2533
          result.fail_reason, result.output)
2534

    
2535
  return result.stdout
2536

    
2537

    
2538
def _OSOndiskAPIVersion(os_dir):
2539
  """Compute and return the API version of a given OS.
2540

2541
  This function will try to read the API version of the OS residing in
2542
  the 'os_dir' directory.
2543

2544
  @type os_dir: str
2545
  @param os_dir: the directory in which we should look for the OS
2546
  @rtype: tuple
2547
  @return: tuple (status, data) with status denoting the validity and
2548
      data holding either the vaid versions or an error message
2549

2550
  """
2551
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2552

    
2553
  try:
2554
    st = os.stat(api_file)
2555
  except EnvironmentError, err:
2556
    return False, ("Required file '%s' not found under path %s: %s" %
2557
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2558

    
2559
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2560
    return False, ("File '%s' in %s is not a regular file" %
2561
                   (constants.OS_API_FILE, os_dir))
2562

    
2563
  try:
2564
    api_versions = utils.ReadFile(api_file).splitlines()
2565
  except EnvironmentError, err:
2566
    return False, ("Error while reading the API version file at %s: %s" %
2567
                   (api_file, utils.ErrnoOrStr(err)))
2568

    
2569
  try:
2570
    api_versions = [int(version.strip()) for version in api_versions]
2571
  except (TypeError, ValueError), err:
2572
    return False, ("API version(s) can't be converted to integer: %s" %
2573
                   str(err))
2574

    
2575
  return True, api_versions
2576

    
2577

    
2578
def DiagnoseOS(top_dirs=None):
2579
  """Compute the validity for all OSes.
2580

2581
  @type top_dirs: list
2582
  @param top_dirs: the list of directories in which to
2583
      search (if not given defaults to
2584
      L{pathutils.OS_SEARCH_PATH})
2585
  @rtype: list of L{objects.OS}
2586
  @return: a list of tuples (name, path, status, diagnose, variants,
2587
      parameters, api_version) for all (potential) OSes under all
2588
      search paths, where:
2589
          - name is the (potential) OS name
2590
          - path is the full path to the OS
2591
          - status True/False is the validity of the OS
2592
          - diagnose is the error message for an invalid OS, otherwise empty
2593
          - variants is a list of supported OS variants, if any
2594
          - parameters is a list of (name, help) parameters, if any
2595
          - api_version is a list of support OS API versions
2596

2597
  """
2598
  if top_dirs is None:
2599
    top_dirs = pathutils.OS_SEARCH_PATH
2600

    
2601
  result = []
2602
  for dir_name in top_dirs:
2603
    if os.path.isdir(dir_name):
2604
      try:
2605
        f_names = utils.ListVisibleFiles(dir_name)
2606
      except EnvironmentError, err:
2607
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2608
        break
2609
      for name in f_names:
2610
        os_path = utils.PathJoin(dir_name, name)
2611
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2612
        if status:
2613
          diagnose = ""
2614
          variants = os_inst.supported_variants
2615
          parameters = os_inst.supported_parameters
2616
          api_versions = os_inst.api_versions
2617
        else:
2618
          diagnose = os_inst
2619
          variants = parameters = api_versions = []
2620
        result.append((name, os_path, status, diagnose, variants,
2621
                       parameters, api_versions))
2622

    
2623
  return result
2624

    
2625

    
2626
def _TryOSFromDisk(name, base_dir=None):
2627
  """Create an OS instance from disk.
2628

2629
  This function will return an OS instance if the given name is a
2630
  valid OS name.
2631

2632
  @type base_dir: string
2633
  @keyword base_dir: Base directory containing OS installations.
2634
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2635
  @rtype: tuple
2636
  @return: success and either the OS instance if we find a valid one,
2637
      or error message
2638

2639
  """
2640
  if base_dir is None:
2641
    os_dir = utils.FindFile(name, pathutils.OS_SEARCH_PATH, os.path.isdir)
2642
  else:
2643
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2644

    
2645
  if os_dir is None:
2646
    return False, "Directory for OS %s not found in search path" % name
2647

    
2648
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2649
  if not status:
2650
    # push the error up
2651
    return status, api_versions
2652

    
2653
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2654
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2655
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2656

    
2657
  # OS Files dictionary, we will populate it with the absolute path
2658
  # names; if the value is True, then it is a required file, otherwise
2659
  # an optional one
2660
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2661

    
2662
  if max(api_versions) >= constants.OS_API_V15:
2663
    os_files[constants.OS_VARIANTS_FILE] = False
2664

    
2665
  if max(api_versions) >= constants.OS_API_V20:
2666
    os_files[constants.OS_PARAMETERS_FILE] = True
2667
  else:
2668
    del os_files[constants.OS_SCRIPT_VERIFY]
2669

    
2670
  for (filename, required) in os_files.items():
2671
    os_files[filename] = utils.PathJoin(os_dir, filename)
2672

    
2673
    try:
2674
      st = os.stat(os_files[filename])
2675
    except EnvironmentError, err:
2676
      if err.errno == errno.ENOENT and not required:
2677
        del os_files[filename]
2678
        continue
2679
      return False, ("File '%s' under path '%s' is missing (%s)" %
2680
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2681

    
2682
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2683
      return False, ("File '%s' under path '%s' is not a regular file" %
2684
                     (filename, os_dir))
2685

    
2686
    if filename in constants.OS_SCRIPTS:
2687
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2688
        return False, ("File '%s' under path '%s' is not executable" %
2689
                       (filename, os_dir))
2690

    
2691
  variants = []
2692
  if constants.OS_VARIANTS_FILE in os_files:
2693
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2694
    try:
2695
      variants = \
2696
        utils.FilterEmptyLinesAndComments(utils.ReadFile(variants_file))
2697
    except EnvironmentError, err:
2698
      # we accept missing files, but not other errors
2699
      if err.errno != errno.ENOENT:
2700
        return False, ("Error while reading the OS variants file at %s: %s" %
2701
                       (variants_file, utils.ErrnoOrStr(err)))
2702

    
2703
  parameters = []
2704
  if constants.OS_PARAMETERS_FILE in os_files:
2705
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2706
    try:
2707
      parameters = utils.ReadFile(parameters_file).splitlines()
2708
    except EnvironmentError, err:
2709
      return False, ("Error while reading the OS parameters file at %s: %s" %
2710
                     (parameters_file, utils.ErrnoOrStr(err)))
2711
    parameters = [v.split(None, 1) for v in parameters]
2712

    
2713
  os_obj = objects.OS(name=name, path=os_dir,
2714
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2715
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2716
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2717
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2718
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2719
                                                 None),
2720
                      supported_variants=variants,
2721
                      supported_parameters=parameters,
2722
                      api_versions=api_versions)
2723
  return True, os_obj
2724

    
2725

    
2726
def OSFromDisk(name, base_dir=None):
2727
  """Create an OS instance from disk.
2728

2729
  This function will return an OS instance if the given name is a
2730
  valid OS name. Otherwise, it will raise an appropriate
2731
  L{RPCFail} exception, detailing why this is not a valid OS.
2732

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

2736
  @type base_dir: string
2737
  @keyword base_dir: Base directory containing OS installations.
2738
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2739
  @rtype: L{objects.OS}
2740
  @return: the OS instance if we find a valid one
2741
  @raise RPCFail: if we don't find a valid OS
2742

2743
  """
2744
  name_only = objects.OS.GetName(name)
2745
  status, payload = _TryOSFromDisk(name_only, base_dir)
2746

    
2747
  if not status:
2748
    _Fail(payload)
2749

    
2750
  return payload
2751

    
2752

    
2753
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2754
  """Calculate the basic environment for an os script.
2755

2756
  @type os_name: str
2757
  @param os_name: full operating system name (including variant)
2758
  @type inst_os: L{objects.OS}
2759
  @param inst_os: operating system for which the environment is being built
2760
  @type os_params: dict
2761
  @param os_params: the OS parameters
2762
  @type debug: integer
2763
  @param debug: debug level (0 or 1, for OS Api 10)
2764
  @rtype: dict
2765
  @return: dict of environment variables
2766
  @raise errors.BlockDeviceError: if the block device
2767
      cannot be found
2768

2769
  """
2770
  result = {}
2771
  api_version = \
2772
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2773
  result["OS_API_VERSION"] = "%d" % api_version
2774
  result["OS_NAME"] = inst_os.name
2775
  result["DEBUG_LEVEL"] = "%d" % debug
2776

    
2777
  # OS variants
2778
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2779
    variant = objects.OS.GetVariant(os_name)
2780
    if not variant:
2781
      variant = inst_os.supported_variants[0]
2782
  else:
2783
    variant = ""
2784
  result["OS_VARIANT"] = variant
2785

    
2786
  # OS params
2787
  for pname, pvalue in os_params.items():
2788
    result["OSP_%s" % pname.upper()] = pvalue
2789

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

    
2795
  return result
2796

    
2797

    
2798
def OSEnvironment(instance, inst_os, debug=0):
2799
  """Calculate the environment for an os script.
2800

2801
  @type instance: L{objects.Instance}
2802
  @param instance: target instance for the os script run
2803
  @type inst_os: L{objects.OS}
2804
  @param inst_os: operating system for which the environment is being built
2805
  @type debug: integer
2806
  @param debug: debug level (0 or 1, for OS Api 10)
2807
  @rtype: dict
2808
  @return: dict of environment variables
2809
  @raise errors.BlockDeviceError: if the block device
2810
      cannot be found
2811

2812
  """
2813
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2814

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

    
2818
  result["HYPERVISOR"] = instance.hypervisor
2819
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2820
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2821
  result["INSTANCE_SECONDARY_NODES"] = \
2822
      ("%s" % " ".join(instance.secondary_nodes))
2823

    
2824
  # Disks
2825
  for idx, disk in enumerate(instance.disks):
2826
    real_disk = _OpenRealBD(disk)
2827
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2828
    result["DISK_%d_ACCESS" % idx] = disk.mode
2829
    result["DISK_%d_UUID" % idx] = disk.uuid
2830
    if disk.name:
2831
      result["DISK_%d_NAME" % idx] = disk.name
2832
    if constants.HV_DISK_TYPE in instance.hvparams:
2833
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2834
        instance.hvparams[constants.HV_DISK_TYPE]
2835
    if disk.dev_type in constants.LDS_BLOCK:
2836
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2837
    elif disk.dev_type == constants.LD_FILE:
2838
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2839
        "file:%s" % disk.physical_id[0]
2840

    
2841
  # NICs
2842
  for idx, nic in enumerate(instance.nics):
2843
    result["NIC_%d_MAC" % idx] = nic.mac
2844
    result["NIC_%d_UUID" % idx] = nic.uuid
2845
    if nic.name:
2846
      result["NIC_%d_NAME" % idx] = nic.name
2847
    if nic.ip:
2848
      result["NIC_%d_IP" % idx] = nic.ip
2849
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2850
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2851
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2852
    if nic.nicparams[constants.NIC_LINK]:
2853
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2854
    if nic.netinfo:
2855
      nobj = objects.Network.FromDict(nic.netinfo)
2856
      result.update(nobj.HooksDict("NIC_%d_" % idx))
2857
    if constants.HV_NIC_TYPE in instance.hvparams:
2858
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2859
        instance.hvparams[constants.HV_NIC_TYPE]
2860

    
2861
  # HV/BE params
2862
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2863
    for key, value in source.items():
2864
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2865

    
2866
  return result
2867

    
2868

    
2869
def DiagnoseExtStorage(top_dirs=None):
2870
  """Compute the validity for all ExtStorage Providers.
2871

2872
  @type top_dirs: list
2873
  @param top_dirs: the list of directories in which to
2874
      search (if not given defaults to
2875
      L{pathutils.ES_SEARCH_PATH})
2876
  @rtype: list of L{objects.ExtStorage}
2877
  @return: a list of tuples (name, path, status, diagnose, parameters)
2878
      for all (potential) ExtStorage Providers under all
2879
      search paths, where:
2880
          - name is the (potential) ExtStorage Provider
2881
          - path is the full path to the ExtStorage Provider
2882
          - status True/False is the validity of the ExtStorage Provider
2883
          - diagnose is the error message for an invalid ExtStorage Provider,
2884
            otherwise empty
2885
          - parameters is a list of (name, help) parameters, if any
2886

2887
  """
2888
  if top_dirs is None:
2889
    top_dirs = pathutils.ES_SEARCH_PATH
2890

    
2891
  result = []
2892
  for dir_name in top_dirs:
2893
    if os.path.isdir(dir_name):
2894
      try:
2895
        f_names = utils.ListVisibleFiles(dir_name)
2896
      except EnvironmentError, err:
2897
        logging.exception("Can't list the ExtStorage directory %s: %s",
2898
                          dir_name, err)
2899
        break
2900
      for name in f_names:
2901
        es_path = utils.PathJoin(dir_name, name)
2902
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2903
        if status:
2904
          diagnose = ""
2905
          parameters = es_inst.supported_parameters
2906
        else:
2907
          diagnose = es_inst
2908
          parameters = []
2909
        result.append((name, es_path, status, diagnose, parameters))
2910

    
2911
  return result
2912

    
2913

    
2914
def BlockdevGrow(disk, amount, dryrun, backingstore, excl_stor):
2915
  """Grow a stack of block devices.
2916

2917
  This function is called recursively, with the childrens being the
2918
  first ones to resize.
2919

2920
  @type disk: L{objects.Disk}
2921
  @param disk: the disk to be grown
2922
  @type amount: integer
2923
  @param amount: the amount (in mebibytes) to grow with
2924
  @type dryrun: boolean
2925
  @param dryrun: whether to execute the operation in simulation mode
2926
      only, without actually increasing the size
2927
  @param backingstore: whether to execute the operation on backing storage
2928
      only, or on "logical" storage only; e.g. DRBD is logical storage,
2929
      whereas LVM, file, RBD are backing storage
2930
  @rtype: (status, result)
2931
  @type excl_stor: boolean
2932
  @param excl_stor: Whether exclusive_storage is active
2933
  @return: a tuple with the status of the operation (True/False), and
2934
      the errors message if status is False
2935

2936
  """
2937
  r_dev = _RecursiveFindBD(disk)
2938
  if r_dev is None:
2939
    _Fail("Cannot find block device %s", disk)
2940

    
2941
  try:
2942
    r_dev.Grow(amount, dryrun, backingstore, excl_stor)
2943
  except errors.BlockDeviceError, err:
2944
    _Fail("Failed to grow block device: %s", err, exc=True)
2945

    
2946

    
2947
def BlockdevSnapshot(disk):
2948
  """Create a snapshot copy of a block device.
2949

2950
  This function is called recursively, and the snapshot is actually created
2951
  just for the leaf lvm backend device.
2952

2953
  @type disk: L{objects.Disk}
2954
  @param disk: the disk to be snapshotted
2955
  @rtype: string
2956
  @return: snapshot disk ID as (vg, lv)
2957

2958
  """
2959
  if disk.dev_type == constants.LD_DRBD8:
2960
    if not disk.children:
2961
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2962
            disk.unique_id)
2963
    return BlockdevSnapshot(disk.children[0])
2964
  elif disk.dev_type == constants.LD_LV:
2965
    r_dev = _RecursiveFindBD(disk)
2966
    if r_dev is not None:
2967
      # FIXME: choose a saner value for the snapshot size
2968
      # let's stay on the safe side and ask for the full size, for now
2969
      return r_dev.Snapshot(disk.size)
2970
    else:
2971
      _Fail("Cannot find block device %s", disk)
2972
  else:
2973
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2974
          disk.unique_id, disk.dev_type)
2975

    
2976

    
2977
def BlockdevSetInfo(disk, info):
2978
  """Sets 'metadata' information on block devices.
2979

2980
  This function sets 'info' metadata on block devices. Initial
2981
  information is set at device creation; this function should be used
2982
  for example after renames.
2983

2984
  @type disk: L{objects.Disk}
2985
  @param disk: the disk to be grown
2986
  @type info: string
2987
  @param info: new 'info' metadata
2988
  @rtype: (status, result)
2989
  @return: a tuple with the status of the operation (True/False), and
2990
      the errors message if status is False
2991

2992
  """
2993
  r_dev = _RecursiveFindBD(disk)
2994
  if r_dev is None:
2995
    _Fail("Cannot find block device %s", disk)
2996

    
2997
  try:
2998
    r_dev.SetInfo(info)
2999
  except errors.BlockDeviceError, err:
3000
    _Fail("Failed to set information on block device: %s", err, exc=True)
3001

    
3002

    
3003
def FinalizeExport(instance, snap_disks):
3004
  """Write out the export configuration information.
3005

3006
  @type instance: L{objects.Instance}
3007
  @param instance: the instance which we export, used for
3008
      saving configuration
3009
  @type snap_disks: list of L{objects.Disk}
3010
  @param snap_disks: list of snapshot block devices, which
3011
      will be used to get the actual name of the dump file
3012

3013
  @rtype: None
3014

3015
  """
3016
  destdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name + ".new")
3017
  finaldestdir = utils.PathJoin(pathutils.EXPORT_DIR, instance.name)
3018

    
3019
  config = objects.SerializableConfigParser()
3020

    
3021
  config.add_section(constants.INISECT_EXP)
3022
  config.set(constants.INISECT_EXP, "version", "0")
3023
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
3024
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
3025
  config.set(constants.INISECT_EXP, "os", instance.os)
3026
  config.set(constants.INISECT_EXP, "compression", "none")
3027

    
3028
  config.add_section(constants.INISECT_INS)
3029
  config.set(constants.INISECT_INS, "name", instance.name)
3030
  config.set(constants.INISECT_INS, "maxmem", "%d" %
3031
             instance.beparams[constants.BE_MAXMEM])
3032
  config.set(constants.INISECT_INS, "minmem", "%d" %
3033
             instance.beparams[constants.BE_MINMEM])
3034
  # "memory" is deprecated, but useful for exporting to old ganeti versions
3035
  config.set(constants.INISECT_INS, "memory", "%d" %
3036
             instance.beparams[constants.BE_MAXMEM])
3037
  config.set(constants.INISECT_INS, "vcpus", "%d" %
3038
             instance.beparams[constants.BE_VCPUS])
3039
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
3040
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
3041
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
3042

    
3043
  nic_total = 0
3044
  for nic_count, nic in enumerate(instance.nics):
3045
    nic_total += 1
3046
    config.set(constants.INISECT_INS, "nic%d_mac" %
3047
               nic_count, "%s" % nic.mac)
3048
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
3049
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
3050
               "%s" % nic.network)
3051
    for param in constants.NICS_PARAMETER_TYPES:
3052
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
3053
                 "%s" % nic.nicparams.get(param, None))
3054
  # TODO: redundant: on load can read nics until it doesn't exist
3055
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
3056

    
3057
  disk_total = 0
3058
  for disk_count, disk in enumerate(snap_disks):
3059
    if disk:
3060
      disk_total += 1
3061
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
3062
                 ("%s" % disk.iv_name))
3063
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
3064
                 ("%s" % disk.physical_id[1]))
3065
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
3066
                 ("%d" % disk.size))
3067

    
3068
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
3069

    
3070
  # New-style hypervisor/backend parameters
3071

    
3072
  config.add_section(constants.INISECT_HYP)
3073
  for name, value in instance.hvparams.items():
3074
    if name not in constants.HVC_GLOBALS:
3075
      config.set(constants.INISECT_HYP, name, str(value))
3076

    
3077
  config.add_section(constants.INISECT_BEP)
3078
  for name, value in instance.beparams.items():
3079
    config.set(constants.INISECT_BEP, name, str(value))
3080

    
3081
  config.add_section(constants.INISECT_OSP)
3082
  for name, value in instance.osparams.items():
3083
    config.set(constants.INISECT_OSP, name, str(value))
3084

    
3085
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
3086
                  data=config.Dumps())
3087
  shutil.rmtree(finaldestdir, ignore_errors=True)
3088
  shutil.move(destdir, finaldestdir)
3089

    
3090

    
3091
def ExportInfo(dest):
3092
  """Get export configuration information.
3093

3094
  @type dest: str
3095
  @param dest: directory containing the export
3096

3097
  @rtype: L{objects.SerializableConfigParser}
3098
  @return: a serializable config file containing the
3099
      export info
3100

3101
  """
3102
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
3103

    
3104
  config = objects.SerializableConfigParser()
3105
  config.read(cff)
3106

    
3107
  if (not config.has_section(constants.INISECT_EXP) or
3108
      not config.has_section(constants.INISECT_INS)):
3109
    _Fail("Export info file doesn't have the required fields")
3110

    
3111
  return config.Dumps()
3112

    
3113

    
3114
def ListExports():
3115
  """Return a list of exports currently available on this machine.
3116

3117
  @rtype: list
3118
  @return: list of the exports
3119

3120
  """
3121
  if os.path.isdir(pathutils.EXPORT_DIR):
3122
    return sorted(utils.ListVisibleFiles(pathutils.EXPORT_DIR))
3123
  else:
3124
    _Fail("No exports directory")
3125

    
3126

    
3127
def RemoveExport(export):
3128
  """Remove an existing export from the node.
3129

3130
  @type export: str
3131
  @param export: the name of the export to remove
3132
  @rtype: None
3133

3134
  """
3135
  target = utils.PathJoin(pathutils.EXPORT_DIR, export)
3136

    
3137
  try:
3138
    shutil.rmtree(target)
3139
  except EnvironmentError, err:
3140
    _Fail("Error while removing the export: %s", err, exc=True)
3141

    
3142

    
3143
def BlockdevRename(devlist):
3144
  """Rename a list of block devices.
3145

3146
  @type devlist: list of tuples
3147
  @param devlist: list of tuples of the form  (disk,
3148
      new_logical_id, new_physical_id); disk is an
3149
      L{objects.Disk} object describing the current disk,
3150
      and new logical_id/physical_id is the name we
3151
      rename it to
3152
  @rtype: boolean
3153
  @return: True if all renames succeeded, False otherwise
3154

3155
  """
3156
  msgs = []
3157
  result = True
3158
  for disk, unique_id in devlist:
3159
    dev = _RecursiveFindBD(disk)
3160
    if dev is None:
3161
      msgs.append("Can't find device %s in rename" % str(disk))
3162
      result = False
3163
      continue
3164
    try:
3165
      old_rpath = dev.dev_path
3166
      dev.Rename(unique_id)
3167
      new_rpath = dev.dev_path
3168
      if old_rpath != new_rpath:
3169
        DevCacheManager.RemoveCache(old_rpath)
3170
        # FIXME: we should add the new cache information here, like:
3171
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
3172
        # but we don't have the owner here - maybe parse from existing
3173
        # cache? for now, we only lose lvm data when we rename, which
3174
        # is less critical than DRBD or MD
3175
    except errors.BlockDeviceError, err:
3176
      msgs.append("Can't rename device '%s' to '%s': %s" %
3177
                  (dev, unique_id, err))
3178
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
3179
      result = False
3180
  if not result:
3181
    _Fail("; ".join(msgs))
3182

    
3183

    
3184
def _TransformFileStorageDir(fs_dir):
3185
  """Checks whether given file_storage_dir is valid.
3186

3187
  Checks wheter the given fs_dir is within the cluster-wide default
3188
  file_storage_dir or the shared_file_storage_dir, which are stored in
3189
  SimpleStore. Only paths under those directories are allowed.
3190

3191
  @type fs_dir: str
3192
  @param fs_dir: the path to check
3193

3194
  @return: the normalized path if valid, None otherwise
3195

3196
  """
3197
  if not (constants.ENABLE_FILE_STORAGE or
3198
          constants.ENABLE_SHARED_FILE_STORAGE):
3199
    _Fail("File storage disabled at configure time")
3200

    
3201
  bdev.CheckFileStoragePath(fs_dir)
3202

    
3203
  return os.path.normpath(fs_dir)
3204

    
3205

    
3206
def CreateFileStorageDir(file_storage_dir):
3207
  """Create file storage directory.
3208

3209
  @type file_storage_dir: str
3210
  @param file_storage_dir: directory to create
3211

3212
  @rtype: tuple
3213
  @return: tuple with first element a boolean indicating wheter dir
3214
      creation was successful or not
3215

3216
  """
3217
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3218
  if os.path.exists(file_storage_dir):
3219
    if not os.path.isdir(file_storage_dir):
3220
      _Fail("Specified storage dir '%s' is not a directory",
3221
            file_storage_dir)
3222
  else:
3223
    try:
3224
      os.makedirs(file_storage_dir, 0750)
3225
    except OSError, err:
3226
      _Fail("Cannot create file storage directory '%s': %s",
3227
            file_storage_dir, err, exc=True)
3228

    
3229

    
3230
def RemoveFileStorageDir(file_storage_dir):
3231
  """Remove file storage directory.
3232

3233
  Remove it only if it's empty. If not log an error and return.
3234

3235
  @type file_storage_dir: str
3236
  @param file_storage_dir: the directory we should cleanup
3237
  @rtype: tuple (success,)
3238
  @return: tuple of one element, C{success}, denoting
3239
      whether the operation was successful
3240

3241
  """
3242
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
3243
  if os.path.exists(file_storage_dir):
3244
    if not os.path.isdir(file_storage_dir):
3245
      _Fail("Specified Storage directory '%s' is not a directory",
3246
            file_storage_dir)
3247
    # deletes dir only if empty, otherwise we want to fail the rpc call
3248
    try:
3249
      os.rmdir(file_storage_dir)
3250
    except OSError, err:
3251
      _Fail("Cannot remove file storage directory '%s': %s",
3252
            file_storage_dir, err)
3253

    
3254

    
3255
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
3256
  """Rename the file storage directory.
3257

3258
  @type old_file_storage_dir: str
3259
  @param old_file_storage_dir: the current path
3260
  @type new_file_storage_dir: str
3261
  @param new_file_storage_dir: the name we should rename to
3262
  @rtype: tuple (success,)
3263
  @return: tuple of one element, C{success}, denoting
3264
      whether the operation was successful
3265

3266
  """
3267
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
3268
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
3269
  if not os.path.exists(new_file_storage_dir):
3270
    if os.path.isdir(old_file_storage_dir):
3271
      try:
3272
        os.rename(old_file_storage_dir, new_file_storage_dir)
3273
      except OSError, err:
3274
        _Fail("Cannot rename '%s' to '%s': %s",
3275
              old_file_storage_dir, new_file_storage_dir, err)
3276
    else:
3277
      _Fail("Specified storage dir '%s' is not a directory",
3278
            old_file_storage_dir)
3279
  else:
3280
    if os.path.exists(old_file_storage_dir):
3281
      _Fail("Cannot rename '%s' to '%s': both locations exist",
3282
            old_file_storage_dir, new_file_storage_dir)
3283

    
3284

    
3285
def _EnsureJobQueueFile(file_name):
3286
  """Checks whether the given filename is in the queue directory.
3287

3288
  @type file_name: str
3289
  @param file_name: the file name we should check
3290
  @rtype: None
3291
  @raises RPCFail: if the file is not valid
3292

3293
  """
3294
  if not utils.IsBelowDir(pathutils.QUEUE_DIR, file_name):
3295
    _Fail("Passed job queue file '%s' does not belong to"
3296
          " the queue directory '%s'", file_name, pathutils.QUEUE_DIR)
3297

    
3298

    
3299
def JobQueueUpdate(file_name, content):
3300
  """Updates a file in the queue directory.
3301

3302
  This is just a wrapper over L{utils.io.WriteFile}, with proper
3303
  checking.
3304

3305
  @type file_name: str
3306
  @param file_name: the job file name
3307
  @type content: str
3308
  @param content: the new job contents
3309
  @rtype: boolean
3310
  @return: the success of the operation
3311

3312
  """
3313
  file_name = vcluster.LocalizeVirtualPath(file_name)
3314

    
3315
  _EnsureJobQueueFile(file_name)
3316
  getents = runtime.GetEnts()
3317

    
3318
  # Write and replace the file atomically
3319
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
3320
                  gid=getents.daemons_gid, mode=constants.JOB_QUEUE_FILES_PERMS)
3321

    
3322

    
3323
def JobQueueRename(old, new):
3324
  """Renames a job queue file.
3325

3326
  This is just a wrapper over os.rename with proper checking.
3327

3328
  @type old: str
3329
  @param old: the old (actual) file name
3330
  @type new: str
3331
  @param new: the desired file name
3332
  @rtype: tuple
3333
  @return: the success of the operation and payload
3334

3335
  """
3336
  old = vcluster.LocalizeVirtualPath(old)
3337
  new = vcluster.LocalizeVirtualPath(new)
3338

    
3339
  _EnsureJobQueueFile(old)
3340
  _EnsureJobQueueFile(new)
3341

    
3342
  getents = runtime.GetEnts()
3343

    
3344
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0750,
3345
                   dir_uid=getents.masterd_uid, dir_gid=getents.daemons_gid)
3346

    
3347

    
3348
def BlockdevClose(instance_name, disks):
3349
  """Closes the given block devices.
3350

3351
  This means they will be switched to secondary mode (in case of
3352
  DRBD).
3353

3354
  @param instance_name: if the argument is not empty, the symlinks
3355
      of this instance will be removed
3356
  @type disks: list of L{objects.Disk}
3357
  @param disks: the list of disks to be closed
3358
  @rtype: tuple (success, message)
3359
  @return: a tuple of success and message, where success
3360
      indicates the succes of the operation, and message
3361
      which will contain the error details in case we
3362
      failed
3363

3364
  """
3365
  bdevs = []
3366
  for cf in disks:
3367
    rd = _RecursiveFindBD(cf)
3368
    if rd is None:
3369
      _Fail("Can't find device %s", cf)
3370
    bdevs.append(rd)
3371

    
3372
  msg = []
3373
  for rd in bdevs:
3374
    try:
3375
      rd.Close()
3376
    except errors.BlockDeviceError, err:
3377
      msg.append(str(err))
3378
  if msg:
3379
    _Fail("Can't make devices secondary: %s", ",".join(msg))
3380
  else:
3381
    if instance_name:
3382
      _RemoveBlockDevLinks(instance_name, disks)
3383

    
3384

    
3385
def ValidateHVParams(hvname, hvparams):
3386
  """Validates the given hypervisor parameters.
3387

3388
  @type hvname: string
3389
  @param hvname: the hypervisor name
3390
  @type hvparams: dict
3391
  @param hvparams: the hypervisor parameters to be validated
3392
  @rtype: None
3393

3394
  """
3395
  try:
3396
    hv_type = hypervisor.GetHypervisor(hvname)
3397
    hv_type.ValidateParameters(hvparams)
3398
  except errors.HypervisorError, err:
3399
    _Fail(str(err), log=False)
3400

    
3401

    
3402
def _CheckOSPList(os_obj, parameters):
3403
  """Check whether a list of parameters is supported by the OS.
3404

3405
  @type os_obj: L{objects.OS}
3406
  @param os_obj: OS object to check
3407
  @type parameters: list
3408
  @param parameters: the list of parameters to check
3409

3410
  """
3411
  supported = [v[0] for v in os_obj.supported_parameters]
3412
  delta = frozenset(parameters).difference(supported)
3413
  if delta:
3414
    _Fail("The following parameters are not supported"
3415
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
3416

    
3417

    
3418
def ValidateOS(required, osname, checks, osparams):
3419
  """Validate the given OS' parameters.
3420

3421
  @type required: boolean
3422
  @param required: whether absence of the OS should translate into
3423
      failure or not
3424
  @type osname: string
3425
  @param osname: the OS to be validated
3426
  @type checks: list
3427
  @param checks: list of the checks to run (currently only 'parameters')
3428
  @type osparams: dict
3429
  @param osparams: dictionary with OS parameters
3430
  @rtype: boolean
3431
  @return: True if the validation passed, or False if the OS was not
3432
      found and L{required} was false
3433

3434
  """
3435
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3436
    _Fail("Unknown checks required for OS %s: %s", osname,
3437
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3438

    
3439
  name_only = objects.OS.GetName(osname)
3440
  status, tbv = _TryOSFromDisk(name_only, None)
3441

    
3442
  if not status:
3443
    if required:
3444
      _Fail(tbv)
3445
    else:
3446
      return False
3447

    
3448
  if max(tbv.api_versions) < constants.OS_API_V20:
3449
    return True
3450

    
3451
  if constants.OS_VALIDATE_PARAMETERS in checks:
3452
    _CheckOSPList(tbv, osparams.keys())
3453

    
3454
  validate_env = OSCoreEnv(osname, tbv, osparams)
3455
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3456
                        cwd=tbv.path, reset_env=True)
3457
  if result.failed:
3458
    logging.error("os validate command '%s' returned error: %s output: %s",
3459
                  result.cmd, result.fail_reason, result.output)
3460
    _Fail("OS validation script failed (%s), output: %s",
3461
          result.fail_reason, result.output, log=False)
3462

    
3463
  return True
3464

    
3465

    
3466
def DemoteFromMC():
3467
  """Demotes the current node from master candidate role.
3468

3469
  """
3470
  # try to ensure we're not the master by mistake
3471
  master, myself = ssconf.GetMasterAndMyself()
3472
  if master == myself:
3473
    _Fail("ssconf status shows I'm the master node, will not demote")
3474

    
3475
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "check", constants.MASTERD])
3476
  if not result.failed:
3477
    _Fail("The master daemon is running, will not demote")
3478

    
3479
  try:
3480
    if os.path.isfile(pathutils.CLUSTER_CONF_FILE):
3481
      utils.CreateBackup(pathutils.CLUSTER_CONF_FILE)
3482
  except EnvironmentError, err:
3483
    if err.errno != errno.ENOENT:
3484
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3485

    
3486
  utils.RemoveFile(pathutils.CLUSTER_CONF_FILE)
3487

    
3488

    
3489
def _GetX509Filenames(cryptodir, name):
3490
  """Returns the full paths for the private key and certificate.
3491

3492
  """
3493
  return (utils.PathJoin(cryptodir, name),
3494
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3495
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3496

    
3497

    
3498
def CreateX509Certificate(validity, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3499
  """Creates a new X509 certificate for SSL/TLS.
3500

3501
  @type validity: int
3502
  @param validity: Validity in seconds
3503
  @rtype: tuple; (string, string)
3504
  @return: Certificate name and public part
3505

3506
  """
3507
  (key_pem, cert_pem) = \
3508
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3509
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3510

    
3511
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3512
                              prefix="x509-%s-" % utils.TimestampForFilename())
3513
  try:
3514
    name = os.path.basename(cert_dir)
3515
    assert len(name) > 5
3516

    
3517
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3518

    
3519
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3520
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3521

    
3522
    # Never return private key as it shouldn't leave the node
3523
    return (name, cert_pem)
3524
  except Exception:
3525
    shutil.rmtree(cert_dir, ignore_errors=True)
3526
    raise
3527

    
3528

    
3529
def RemoveX509Certificate(name, cryptodir=pathutils.CRYPTO_KEYS_DIR):
3530
  """Removes a X509 certificate.
3531

3532
  @type name: string
3533
  @param name: Certificate name
3534

3535
  """
3536
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3537

    
3538
  utils.RemoveFile(key_file)
3539
  utils.RemoveFile(cert_file)
3540

    
3541
  try:
3542
    os.rmdir(cert_dir)
3543
  except EnvironmentError, err:
3544
    _Fail("Cannot remove certificate directory '%s': %s",
3545
          cert_dir, err)
3546

    
3547

    
3548
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3549
  """Returns the command for the requested input/output.
3550

3551
  @type instance: L{objects.Instance}
3552
  @param instance: The instance object
3553
  @param mode: Import/export mode
3554
  @param ieio: Input/output type
3555
  @param ieargs: Input/output arguments
3556

3557
  """
3558
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3559

    
3560
  env = None
3561
  prefix = None
3562
  suffix = None
3563
  exp_size = None
3564

    
3565
  if ieio == constants.IEIO_FILE:
3566
    (filename, ) = ieargs
3567

    
3568
    if not utils.IsNormAbsPath(filename):
3569
      _Fail("Path '%s' is not normalized or absolute", filename)
3570

    
3571
    real_filename = os.path.realpath(filename)
3572
    directory = os.path.dirname(real_filename)
3573

    
3574
    if not utils.IsBelowDir(pathutils.EXPORT_DIR, real_filename):
3575
      _Fail("File '%s' is not under exports directory '%s': %s",
3576
            filename, pathutils.EXPORT_DIR, real_filename)
3577

    
3578
    # Create directory
3579
    utils.Makedirs(directory, mode=0750)
3580

    
3581
    quoted_filename = utils.ShellQuote(filename)
3582

    
3583
    if mode == constants.IEM_IMPORT:
3584
      suffix = "> %s" % quoted_filename
3585
    elif mode == constants.IEM_EXPORT:
3586
      suffix = "< %s" % quoted_filename
3587

    
3588
      # Retrieve file size
3589
      try:
3590
        st = os.stat(filename)
3591
      except EnvironmentError, err:
3592
        logging.error("Can't stat(2) %s: %s", filename, err)
3593
      else:
3594
        exp_size = utils.BytesToMebibyte(st.st_size)
3595

    
3596
  elif ieio == constants.IEIO_RAW_DISK:
3597
    (disk, ) = ieargs
3598

    
3599
    real_disk = _OpenRealBD(disk)
3600

    
3601
    if mode == constants.IEM_IMPORT:
3602
      # we set here a smaller block size as, due to transport buffering, more
3603
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3604
      # is not already there or we pass a wrong path; we use notrunc to no
3605
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3606
      # much memory; this means that at best, we flush every 64k, which will
3607
      # not be very fast
3608
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3609
                                    " bs=%s oflag=dsync"),
3610
                                    real_disk.dev_path,
3611
                                    str(64 * 1024))
3612

    
3613
    elif mode == constants.IEM_EXPORT:
3614
      # the block size on the read dd is 1MiB to match our units
3615
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3616
                                   real_disk.dev_path,
3617
                                   str(1024 * 1024), # 1 MB
3618
                                   str(disk.size))
3619
      exp_size = disk.size
3620

    
3621
  elif ieio == constants.IEIO_SCRIPT:
3622
    (disk, disk_index, ) = ieargs
3623

    
3624
    assert isinstance(disk_index, (int, long))
3625

    
3626
    real_disk = _OpenRealBD(disk)
3627

    
3628
    inst_os = OSFromDisk(instance.os)
3629
    env = OSEnvironment(instance, inst_os)
3630

    
3631
    if mode == constants.IEM_IMPORT:
3632
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3633
      env["IMPORT_INDEX"] = str(disk_index)
3634
      script = inst_os.import_script
3635

    
3636
    elif mode == constants.IEM_EXPORT:
3637
      env["EXPORT_DEVICE"] = real_disk.dev_path
3638
      env["EXPORT_INDEX"] = str(disk_index)
3639
      script = inst_os.export_script
3640

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

    
3644
    if mode == constants.IEM_IMPORT:
3645
      suffix = "| %s" % script_cmd
3646

    
3647
    elif mode == constants.IEM_EXPORT:
3648
      prefix = "%s |" % script_cmd
3649

    
3650
    # Let script predict size
3651
    exp_size = constants.IE_CUSTOM_SIZE
3652

    
3653
  else:
3654
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3655

    
3656
  return (env, prefix, suffix, exp_size)
3657

    
3658

    
3659
def _CreateImportExportStatusDir(prefix):
3660
  """Creates status directory for import/export.
3661

3662
  """
3663
  return tempfile.mkdtemp(dir=pathutils.IMPORT_EXPORT_DIR,
3664
                          prefix=("%s-%s-" %
3665
                                  (prefix, utils.TimestampForFilename())))
3666

    
3667

    
3668
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3669
                            ieio, ieioargs):
3670
  """Starts an import or export daemon.
3671

3672
  @param mode: Import/output mode
3673
  @type opts: L{objects.ImportExportOptions}
3674
  @param opts: Daemon options
3675
  @type host: string
3676
  @param host: Remote host for export (None for import)
3677
  @type port: int
3678
  @param port: Remote port for export (None for import)
3679
  @type instance: L{objects.Instance}
3680
  @param instance: Instance object
3681
  @type component: string
3682
  @param component: which part of the instance is transferred now,
3683
      e.g. 'disk/0'
3684
  @param ieio: Input/output type
3685
  @param ieioargs: Input/output arguments
3686

3687
  """
3688
  if mode == constants.IEM_IMPORT:
3689
    prefix = "import"
3690

    
3691
    if not (host is None and port is None):
3692
      _Fail("Can not specify host or port on import")
3693

    
3694
  elif mode == constants.IEM_EXPORT:
3695
    prefix = "export"
3696

    
3697
    if host is None or port is None:
3698
      _Fail("Host and port must be specified for an export")
3699

    
3700
  else:
3701
    _Fail("Invalid mode %r", mode)
3702

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

    
3706
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3707
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3708

    
3709
  if opts.key_name is None:
3710
    # Use server.pem
3711
    key_path = pathutils.NODED_CERT_FILE
3712
    cert_path = pathutils.NODED_CERT_FILE
3713
    assert opts.ca_pem is None
3714
  else:
3715
    (_, key_path, cert_path) = _GetX509Filenames(pathutils.CRYPTO_KEYS_DIR,
3716
                                                 opts.key_name)
3717
    assert opts.ca_pem is not None
3718

    
3719
  for i in [key_path, cert_path]:
3720
    if not os.path.exists(i):
3721
      _Fail("File '%s' does not exist" % i)
3722

    
3723
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3724
  try:
3725
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3726
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3727
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3728

    
3729
    if opts.ca_pem is None:
3730
      # Use server.pem
3731
      ca = utils.ReadFile(pathutils.NODED_CERT_FILE)
3732
    else:
3733
      ca = opts.ca_pem
3734

    
3735
    # Write CA file
3736
    utils.WriteFile(ca_file, data=ca, mode=0400)
3737

    
3738
    cmd = [
3739
      pathutils.IMPORT_EXPORT_DAEMON,
3740
      status_file, mode,
3741
      "--key=%s" % key_path,
3742
      "--cert=%s" % cert_path,
3743
      "--ca=%s" % ca_file,
3744
      ]
3745

    
3746
    if host:
3747
      cmd.append("--host=%s" % host)
3748

    
3749
    if port:
3750
      cmd.append("--port=%s" % port)
3751

    
3752
    if opts.ipv6:
3753
      cmd.append("--ipv6")
3754
    else:
3755
      cmd.append("--ipv4")
3756

    
3757
    if opts.compress:
3758
      cmd.append("--compress=%s" % opts.compress)
3759

    
3760
    if opts.magic:
3761
      cmd.append("--magic=%s" % opts.magic)
3762

    
3763
    if exp_size is not None:
3764
      cmd.append("--expected-size=%s" % exp_size)
3765

    
3766
    if cmd_prefix:
3767
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3768

    
3769
    if cmd_suffix:
3770
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3771

    
3772
    if mode == constants.IEM_EXPORT:
3773
      # Retry connection a few times when connecting to remote peer
3774
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3775
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3776
    elif opts.connect_timeout is not None:
3777
      assert mode == constants.IEM_IMPORT
3778
      # Overall timeout for establishing connection while listening
3779
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3780

    
3781
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3782

    
3783
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3784
    # support for receiving a file descriptor for output
3785
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3786
                      output=logfile)
3787

    
3788
    # The import/export name is simply the status directory name
3789
    return os.path.basename(status_dir)
3790

    
3791
  except Exception:
3792
    shutil.rmtree(status_dir, ignore_errors=True)
3793
    raise
3794

    
3795

    
3796
def GetImportExportStatus(names):
3797
  """Returns import/export daemon status.
3798

3799
  @type names: sequence
3800
  @param names: List of names
3801
  @rtype: List of dicts
3802
  @return: Returns a list of the state of each named import/export or None if a
3803
           status couldn't be read
3804

3805
  """
3806
  result = []
3807

    
3808
  for name in names:
3809
    status_file = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name,
3810
                                 _IES_STATUS_FILE)
3811

    
3812
    try:
3813
      data = utils.ReadFile(status_file)
3814
    except EnvironmentError, err:
3815
      if err.errno != errno.ENOENT:
3816
        raise
3817
      data = None
3818

    
3819
    if not data:
3820
      result.append(None)
3821
      continue
3822

    
3823
    result.append(serializer.LoadJson(data))
3824

    
3825
  return result
3826

    
3827

    
3828
def AbortImportExport(name):
3829
  """Sends SIGTERM to a running import/export daemon.
3830

3831
  """
3832
  logging.info("Abort import/export %s", name)
3833

    
3834
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3835
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3836

    
3837
  if pid:
3838
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3839
                 name, pid)
3840
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3841

    
3842

    
3843
def CleanupImportExport(name):
3844
  """Cleanup after an import or export.
3845

3846
  If the import/export daemon is still running it's killed. Afterwards the
3847
  whole status directory is removed.
3848

3849
  """
3850
  logging.info("Finalizing import/export %s", name)
3851

    
3852
  status_dir = utils.PathJoin(pathutils.IMPORT_EXPORT_DIR, name)
3853

    
3854
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3855

    
3856
  if pid:
3857
    logging.info("Import/export %s is still running with PID %s",
3858
                 name, pid)
3859
    utils.KillProcess(pid, waitpid=False)
3860

    
3861
  shutil.rmtree(status_dir, ignore_errors=True)
3862

    
3863

    
3864
def _SetPhysicalId(target_node_uuid, nodes_ip, disks):
3865
  """Sets the correct physical ID on all passed disks.
3866

3867
  """
3868
  for cf in disks:
3869
    cf.SetPhysicalID(target_node_uuid, nodes_ip)
3870

    
3871

    
3872
def _FindDisks(target_node_uuid, nodes_ip, disks):
3873
  """Sets the physical ID on disks and returns the block devices.
3874

3875
  """
3876
  _SetPhysicalId(target_node_uuid, nodes_ip, disks)
3877

    
3878
  bdevs = []
3879

    
3880
  for cf in disks:
3881
    rd = _RecursiveFindBD(cf)
3882
    if rd is None:
3883
      _Fail("Can't find device %s", cf)
3884
    bdevs.append(rd)
3885
  return bdevs
3886

    
3887

    
3888
def DrbdDisconnectNet(target_node_uuid, nodes_ip, disks):
3889
  """Disconnects the network on a list of drbd devices.
3890

3891
  """
3892
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3893

    
3894
  # disconnect disks
3895
  for rd in bdevs:
3896
    try:
3897
      rd.DisconnectNet()
3898
    except errors.BlockDeviceError, err:
3899
      _Fail("Can't change network configuration to standalone mode: %s",
3900
            err, exc=True)
3901

    
3902

    
3903
def DrbdAttachNet(target_node_uuid, nodes_ip, disks, instance_name,
3904
                  multimaster):
3905
  """Attaches the network on a list of drbd devices.
3906

3907
  """
3908
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3909

    
3910
  if multimaster:
3911
    for idx, rd in enumerate(bdevs):
3912
      try:
3913
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3914
      except EnvironmentError, err:
3915
        _Fail("Can't create symlink: %s", err)
3916
  # reconnect disks, switch to new master configuration and if
3917
  # needed primary mode
3918
  for rd in bdevs:
3919
    try:
3920
      rd.AttachNet(multimaster)
3921
    except errors.BlockDeviceError, err:
3922
      _Fail("Can't change network configuration: %s", err)
3923

    
3924
  # wait until the disks are connected; we need to retry the re-attach
3925
  # if the device becomes standalone, as this might happen if the one
3926
  # node disconnects and reconnects in a different mode before the
3927
  # other node reconnects; in this case, one or both of the nodes will
3928
  # decide it has wrong configuration and switch to standalone
3929

    
3930
  def _Attach():
3931
    all_connected = True
3932

    
3933
    for rd in bdevs:
3934
      stats = rd.GetProcStatus()
3935

    
3936
      all_connected = (all_connected and
3937
                       (stats.is_connected or stats.is_in_resync))
3938

    
3939
      if stats.is_standalone:
3940
        # peer had different config info and this node became
3941
        # standalone, even though this should not happen with the
3942
        # new staged way of changing disk configs
3943
        try:
3944
          rd.AttachNet(multimaster)
3945
        except errors.BlockDeviceError, err:
3946
          _Fail("Can't change network configuration: %s", err)
3947

    
3948
    if not all_connected:
3949
      raise utils.RetryAgain()
3950

    
3951
  try:
3952
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3953
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3954
  except utils.RetryTimeout:
3955
    _Fail("Timeout in disk reconnecting")
3956

    
3957
  if multimaster:
3958
    # change to primary mode
3959
    for rd in bdevs:
3960
      try:
3961
        rd.Open()
3962
      except errors.BlockDeviceError, err:
3963
        _Fail("Can't change to primary mode: %s", err)
3964

    
3965

    
3966
def DrbdWaitSync(target_node_uuid, nodes_ip, disks):
3967
  """Wait until DRBDs have synchronized.
3968

3969
  """
3970
  def _helper(rd):
3971
    stats = rd.GetProcStatus()
3972
    if not (stats.is_connected or stats.is_in_resync):
3973
      raise utils.RetryAgain()
3974
    return stats
3975

    
3976
  bdevs = _FindDisks(target_node_uuid, nodes_ip, disks)
3977

    
3978
  min_resync = 100
3979
  alldone = True
3980
  for rd in bdevs:
3981
    try:
3982
      # poll each second for 15 seconds
3983
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3984
    except utils.RetryTimeout:
3985
      stats = rd.GetProcStatus()
3986
      # last check
3987
      if not (stats.is_connected or stats.is_in_resync):
3988
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3989
    alldone = alldone and (not stats.is_in_resync)
3990
    if stats.sync_percent is not None:
3991
      min_resync = min(min_resync, stats.sync_percent)
3992

    
3993
  return (alldone, min_resync)
3994

    
3995

    
3996
def DrbdNeedsActivation(target_node_uuid, nodes_ip, disks):
3997
  """Checks which of the passed disks needs activation and returns their UUIDs.
3998

3999
  """
4000
  _SetPhysicalId(target_node_uuid, nodes_ip, disks)
4001
  faulty_disks = []
4002

    
4003
  for disk in disks:
4004
    rd = _RecursiveFindBD(disk)
4005
    if rd is None:
4006
      faulty_disks.append(disk)
4007
      continue
4008

    
4009
    stats = rd.GetProcStatus()
4010
    if stats.is_standalone or stats.is_diskless:
4011
      faulty_disks.append(disk)
4012

    
4013
  return [disk.uuid for disk in faulty_disks]
4014

    
4015

    
4016
def GetDrbdUsermodeHelper():
4017
  """Returns DRBD usermode helper currently configured.
4018

4019
  """
4020
  try:
4021
    return drbd.DRBD8.GetUsermodeHelper()
4022
  except errors.BlockDeviceError, err:
4023
    _Fail(str(err))
4024

    
4025

    
4026
def PowercycleNode(hypervisor_type, hvparams=None):
4027
  """Hard-powercycle the node.
4028

4029
  Because we need to return first, and schedule the powercycle in the
4030
  background, we won't be able to report failures nicely.
4031

4032
  """
4033
  hyper = hypervisor.GetHypervisor(hypervisor_type)
4034
  try:
4035
    pid = os.fork()
4036
  except OSError:
4037
    # if we can't fork, we'll pretend that we're in the child process
4038
    pid = 0
4039
  if pid > 0:
4040
    return "Reboot scheduled in 5 seconds"
4041
  # ensure the child is running on ram
4042
  try:
4043
    utils.Mlockall()
4044
  except Exception: # pylint: disable=W0703
4045
    pass
4046
  time.sleep(5)
4047
  hyper.PowercycleNode(hvparams=hvparams)
4048

    
4049

    
4050
def _VerifyRestrictedCmdName(cmd):
4051
  """Verifies a restricted command name.
4052

4053
  @type cmd: string
4054
  @param cmd: Command name
4055
  @rtype: tuple; (boolean, string or None)
4056
  @return: The tuple's first element is the status; if C{False}, the second
4057
    element is an error message string, otherwise it's C{None}
4058

4059
  """
4060
  if not cmd.strip():
4061
    return (False, "Missing command name")
4062

    
4063
  if os.path.basename(cmd) != cmd:
4064
    return (False, "Invalid command name")
4065

    
4066
  if not constants.EXT_PLUGIN_MASK.match(cmd):
4067
    return (False, "Command name contains forbidden characters")
4068

    
4069
  return (True, None)
4070

    
4071

    
4072
def _CommonRestrictedCmdCheck(path, owner):
4073
  """Common checks for restricted command file system directories and files.
4074

4075
  @type path: string
4076
  @param path: Path to check
4077
  @param owner: C{None} or tuple containing UID and GID
4078
  @rtype: tuple; (boolean, string or C{os.stat} result)
4079
  @return: The tuple's first element is the status; if C{False}, the second
4080
    element is an error message string, otherwise it's the result of C{os.stat}
4081

4082
  """
4083
  if owner is None:
4084
    # Default to root as owner
4085
    owner = (0, 0)
4086

    
4087
  try:
4088
    st = os.stat(path)
4089
  except EnvironmentError, err:
4090
    return (False, "Can't stat(2) '%s': %s" % (path, err))
4091

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

    
4095
  if (st.st_uid, st.st_gid) != owner:
4096
    (owner_uid, owner_gid) = owner
4097
    return (False, "'%s' is not owned by %s:%s" % (path, owner_uid, owner_gid))
4098

    
4099
  return (True, st)
4100

    
4101

    
4102
def _VerifyRestrictedCmdDirectory(path, _owner=None):
4103
  """Verifies restricted command directory.
4104

4105
  @type path: string
4106
  @param path: Path to check
4107
  @rtype: tuple; (boolean, string or None)
4108
  @return: The tuple's first element is the status; if C{False}, the second
4109
    element is an error message string, otherwise it's C{None}
4110

4111
  """
4112
  (status, value) = _CommonRestrictedCmdCheck(path, _owner)
4113

    
4114
  if not status:
4115
    return (False, value)
4116

    
4117
  if not stat.S_ISDIR(value.st_mode):
4118
    return (False, "Path '%s' is not a directory" % path)
4119

    
4120
  return (True, None)
4121

    
4122

    
4123
def _VerifyRestrictedCmd(path, cmd, _owner=None):
4124
  """Verifies a whole restricted command and returns its executable filename.
4125

4126
  @type path: string
4127
  @param path: Directory containing restricted commands
4128
  @type cmd: string
4129
  @param cmd: Command name
4130
  @rtype: tuple; (boolean, string)
4131
  @return: The tuple's first element is the status; if C{False}, the second
4132
    element is an error message string, otherwise the second element is the
4133
    absolute path to the executable
4134

4135
  """
4136
  executable = utils.PathJoin(path, cmd)
4137

    
4138
  (status, msg) = _CommonRestrictedCmdCheck(executable, _owner)
4139

    
4140
  if not status:
4141
    return (False, msg)
4142

    
4143
  if not utils.IsExecutable(executable):
4144
    return (False, "access(2) thinks '%s' can't be executed" % executable)
4145

    
4146
  return (True, executable)
4147

    
4148

    
4149
def _PrepareRestrictedCmd(path, cmd,
4150
                          _verify_dir=_VerifyRestrictedCmdDirectory,
4151
                          _verify_name=_VerifyRestrictedCmdName,
4152
                          _verify_cmd=_VerifyRestrictedCmd):
4153
  """Performs a number of tests on a restricted command.
4154

4155
  @type path: string
4156
  @param path: Directory containing restricted commands
4157
  @type cmd: string
4158
  @param cmd: Command name
4159
  @return: Same as L{_VerifyRestrictedCmd}
4160

4161
  """
4162
  # Verify the directory first
4163
  (status, msg) = _verify_dir(path)
4164
  if status:
4165
    # Check command if everything was alright
4166
    (status, msg) = _verify_name(cmd)
4167

    
4168
  if not status:
4169
    return (False, msg)
4170

    
4171
  # Check actual executable
4172
  return _verify_cmd(path, cmd)
4173

    
4174

    
4175
def RunRestrictedCmd(cmd,
4176
                     _lock_timeout=_RCMD_LOCK_TIMEOUT,
4177
                     _lock_file=pathutils.RESTRICTED_COMMANDS_LOCK_FILE,
4178
                     _path=pathutils.RESTRICTED_COMMANDS_DIR,
4179
                     _sleep_fn=time.sleep,
4180
                     _prepare_fn=_PrepareRestrictedCmd,
4181
                     _runcmd_fn=utils.RunCmd,
4182
                     _enabled=constants.ENABLE_RESTRICTED_COMMANDS):
4183
  """Executes a restricted command after performing strict tests.
4184

4185
  @type cmd: string
4186
  @param cmd: Command name
4187
  @rtype: string
4188
  @return: Command output
4189
  @raise RPCFail: In case of an error
4190

4191
  """
4192
  logging.info("Preparing to run restricted command '%s'", cmd)
4193

    
4194
  if not _enabled:
4195
    _Fail("Restricted commands disabled at configure time")
4196

    
4197
  lock = None
4198
  try:
4199
    cmdresult = None
4200
    try:
4201
      lock = utils.FileLock.Open(_lock_file)
4202
      lock.Exclusive(blocking=True, timeout=_lock_timeout)
4203

    
4204
      (status, value) = _prepare_fn(_path, cmd)
4205

    
4206
      if status:
4207
        cmdresult = _runcmd_fn([value], env={}, reset_env=True,
4208
                               postfork_fn=lambda _: lock.Unlock())
4209
      else:
4210
        logging.error(value)
4211
    except Exception: # pylint: disable=W0703
4212
      # Keep original error in log
4213
      logging.exception("Caught exception")
4214

    
4215
    if cmdresult is None:
4216
      logging.info("Sleeping for %0.1f seconds before returning",
4217
                   _RCMD_INVALID_DELAY)
4218
      _sleep_fn(_RCMD_INVALID_DELAY)
4219

    
4220
      # Do not include original error message in returned error
4221
      _Fail("Executing command '%s' failed" % cmd)
4222
    elif cmdresult.failed or cmdresult.fail_reason:
4223
      _Fail("Restricted command '%s' failed: %s; output: %s",
4224
            cmd, cmdresult.fail_reason, cmdresult.output)
4225
    else:
4226
      return cmdresult.output
4227
  finally:
4228
    if lock is not None:
4229
      # Release lock at last
4230
      lock.Close()
4231
      lock = None
4232

    
4233

    
4234
def SetWatcherPause(until, _filename=pathutils.WATCHER_PAUSEFILE):
4235
  """Creates or removes the watcher pause file.
4236

4237
  @type until: None or number
4238
  @param until: Unix timestamp saying until when the watcher shouldn't run
4239

4240
  """
4241
  if until is None:
4242
    logging.info("Received request to no longer pause watcher")
4243
    utils.RemoveFile(_filename)
4244
  else:
4245
    logging.info("Received request to pause watcher until %s", until)
4246

    
4247
    if not ht.TNumber(until):
4248
      _Fail("Duration must be numeric")
4249

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

    
4252

    
4253
class HooksRunner(object):
4254
  """Hook runner.
4255

4256
  This class is instantiated on the node side (ganeti-noded) and not
4257
  on the master side.
4258

4259
  """
4260
  def __init__(self, hooks_base_dir=None):
4261
    """Constructor for hooks runner.
4262

4263
    @type hooks_base_dir: str or None
4264
    @param hooks_base_dir: if not None, this overrides the
4265
        L{pathutils.HOOKS_BASE_DIR} (useful for unittests)
4266

4267
    """
4268
    if hooks_base_dir is None:
4269
      hooks_base_dir = pathutils.HOOKS_BASE_DIR
4270
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
4271
    # constant
4272
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
4273

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

4277
    """
4278
    assert len(node_list) == 1
4279
    node = node_list[0]
4280
    _, myself = ssconf.GetMasterAndMyself()
4281
    assert node == myself
4282

    
4283
    results = self.RunHooks(hpath, phase, env)
4284

    
4285
    # Return values in the form expected by HooksMaster
4286
    return {node: (None, False, results)}
4287

    
4288
  def RunHooks(self, hpath, phase, env):
4289
    """Run the scripts in the hooks directory.
4290

4291
    @type hpath: str
4292
    @param hpath: the path to the hooks directory which
4293
        holds the scripts
4294
    @type phase: str
4295
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
4296
        L{constants.HOOKS_PHASE_POST}
4297
    @type env: dict
4298
    @param env: dictionary with the environment for the hook
4299
    @rtype: list
4300
    @return: list of 3-element tuples:
4301
      - script path
4302
      - script result, either L{constants.HKR_SUCCESS} or
4303
        L{constants.HKR_FAIL}
4304
      - output of the script
4305

4306
    @raise errors.ProgrammerError: for invalid input
4307
        parameters
4308

4309
    """
4310
    if phase == constants.HOOKS_PHASE_PRE:
4311
      suffix = "pre"
4312
    elif phase == constants.HOOKS_PHASE_POST:
4313
      suffix = "post"
4314
    else:
4315
      _Fail("Unknown hooks phase '%s'", phase)
4316

    
4317
    subdir = "%s-%s.d" % (hpath, suffix)
4318
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
4319

    
4320
    results = []
4321

    
4322
    if not os.path.isdir(dir_name):
4323
      # for non-existing/non-dirs, we simply exit instead of logging a
4324
      # warning at every operation
4325
      return results
4326

    
4327
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
4328

    
4329
    for (relname, relstatus, runresult) in runparts_results:
4330
      if relstatus == constants.RUNPARTS_SKIP:
4331
        rrval = constants.HKR_SKIP
4332
        output = ""
4333
      elif relstatus == constants.RUNPARTS_ERR:
4334
        rrval = constants.HKR_FAIL
4335
        output = "Hook script execution error: %s" % runresult
4336
      elif relstatus == constants.RUNPARTS_RUN:
4337
        if runresult.failed:
4338
          rrval = constants.HKR_FAIL
4339
        else:
4340
          rrval = constants.HKR_SUCCESS
4341
        output = utils.SafeEncode(runresult.output.strip())
4342
      results.append(("%s/%s" % (subdir, relname), rrval, output))
4343

    
4344
    return results
4345

    
4346

    
4347
class IAllocatorRunner(object):
4348
  """IAllocator runner.
4349

4350
  This class is instantiated on the node side (ganeti-noded) and not on
4351
  the master side.
4352

4353
  """
4354
  @staticmethod
4355
  def Run(name, idata):
4356
    """Run an iallocator script.
4357

4358
    @type name: str
4359
    @param name: the iallocator script name
4360
    @type idata: str
4361
    @param idata: the allocator input data
4362

4363
    @rtype: tuple
4364
    @return: two element tuple of:
4365
       - status
4366
       - either error message or stdout of allocator (for success)
4367

4368
    """
4369
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
4370
                                  os.path.isfile)
4371
    if alloc_script is None:
4372
      _Fail("iallocator module '%s' not found in the search path", name)
4373

    
4374
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
4375
    try:
4376
      os.write(fd, idata)
4377
      os.close(fd)
4378
      result = utils.RunCmd([alloc_script, fin_name])
4379
      if result.failed:
4380
        _Fail("iallocator module '%s' failed: %s, output '%s'",
4381
              name, result.fail_reason, result.output)
4382
    finally:
4383
      os.unlink(fin_name)
4384

    
4385
    return result.stdout
4386

    
4387

    
4388
class DevCacheManager(object):
4389
  """Simple class for managing a cache of block device information.
4390

4391
  """
4392
  _DEV_PREFIX = "/dev/"
4393
  _ROOT_DIR = pathutils.BDEV_CACHE_DIR
4394

    
4395
  @classmethod
4396
  def _ConvertPath(cls, dev_path):
4397
    """Converts a /dev/name path to the cache file name.
4398

4399
    This replaces slashes with underscores and strips the /dev
4400
    prefix. It then returns the full path to the cache file.
4401

4402
    @type dev_path: str
4403
    @param dev_path: the C{/dev/} path name
4404
    @rtype: str
4405
    @return: the converted path name
4406

4407
    """
4408
    if dev_path.startswith(cls._DEV_PREFIX):
4409
      dev_path = dev_path[len(cls._DEV_PREFIX):]
4410
    dev_path = dev_path.replace("/", "_")
4411
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
4412
    return fpath
4413

    
4414
  @classmethod
4415
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
4416
    """Updates the cache information for a given device.
4417

4418
    @type dev_path: str
4419
    @param dev_path: the pathname of the device
4420
    @type owner: str
4421
    @param owner: the owner (instance name) of the device
4422
    @type on_primary: bool
4423
    @param on_primary: whether this is the primary
4424
        node nor not
4425
    @type iv_name: str
4426
    @param iv_name: the instance-visible name of the
4427
        device, as in objects.Disk.iv_name
4428

4429
    @rtype: None
4430

4431
    """
4432
    if dev_path is None:
4433
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
4434
      return
4435
    fpath = cls._ConvertPath(dev_path)
4436
    if on_primary:
4437
      state = "primary"
4438
    else:
4439
      state = "secondary"
4440
    if iv_name is None:
4441
      iv_name = "not_visible"
4442
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
4443
    try:
4444
      utils.WriteFile(fpath, data=fdata)
4445
    except EnvironmentError, err:
4446
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
4447

    
4448
  @classmethod
4449
  def RemoveCache(cls, dev_path):
4450
    """Remove data for a dev_path.
4451

4452
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
4453
    path name and logging.
4454

4455
    @type dev_path: str
4456
    @param dev_path: the pathname of the device
4457

4458
    @rtype: None
4459

4460
    """
4461
    if dev_path is None:
4462
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
4463
      return
4464
    fpath = cls._ConvertPath(dev_path)
4465
    try:
4466
      utils.RemoveFile(fpath)
4467
    except EnvironmentError, err:
4468
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)