backend.py 136 KB
Newer Older
Iustin Pop's avatar
Iustin Pop committed
1
#
Iustin Pop's avatar
Iustin Pop committed
2
3
#

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


22
23
24
25
"""Functions used by the node daemon

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

"""
Iustin Pop's avatar
Iustin Pop committed
30

31
# pylint: disable=E1103
Iustin Pop's avatar
Iustin Pop committed
32
33
34
35
36

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

Iustin Pop's avatar
Iustin Pop committed
37
38
39
40
41
42
43
44

import os
import os.path
import shutil
import time
import stat
import errno
import re
45
import random
46
import logging
47
import tempfile
48
49
import zlib
import base64
50
import signal
Iustin Pop's avatar
Iustin Pop committed
51
52
53
54
55
56

from ganeti import errors
from ganeti import utils
from ganeti import ssh
from ganeti import hypervisor
from ganeti import constants
57
58
from ganeti.storage import bdev
from ganeti.storage import drbd
59
from ganeti.storage import filestorage
Iustin Pop's avatar
Iustin Pop committed
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
70
from ganeti.storage.base import BlockDev
from ganeti.storage.drbd import DRBD8
71
from ganeti import hooksmaster
Iustin Pop's avatar
Iustin Pop committed
72
73


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

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

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

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

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

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

108

109
110
111
112
113
114
115
class RPCFail(Exception):
  """Class denoting RPC failure.

  Its argument is the error message.

  """

116

117
def _GetInstReasonFilename(instance_name):
118
119
120
121
122
123
124
125
126
127
128
  """Path of the file containing the reason of the instance status change.

  @type instance_name: string
  @param instance_name: The name of the instance
  @rtype: string
  @return: The path of the file

  """
  return utils.PathJoin(pathutils.INSTANCE_REASON_DIR, instance_name)


129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
def _StoreInstReasonTrail(instance_name, trail):
  """Serialize a reason trail related to an instance change of state to file.

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

  @type instance_name: string
  @param instance_name: The name of the instance
  @rtype: None

  """
  json = serializer.DumpJson(trail)
  filename = _GetInstReasonFilename(instance_name)
  utils.WriteFile(filename, data=json)


145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def _Fail(msg, *args, **kwargs):
  """Log an error and the raise an RPCFail exception.

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

  @type msg: string
  @param msg: the text of the exception
  @raise RPCFail

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


Michael Hanselmann's avatar
Michael Hanselmann committed
168
def _GetConfig():
Iustin Pop's avatar
Iustin Pop committed
169
  """Simple wrapper to return a SimpleStore.
Iustin Pop's avatar
Iustin Pop committed
170

Iustin Pop's avatar
Iustin Pop committed
171
172
  @rtype: L{ssconf.SimpleStore}
  @return: a SimpleStore instance
Iustin Pop's avatar
Iustin Pop committed
173
174

  """
Iustin Pop's avatar
Iustin Pop committed
175
  return ssconf.SimpleStore()
Michael Hanselmann's avatar
Michael Hanselmann committed
176
177


178
def _GetSshRunner(cluster_name):
Iustin Pop's avatar
Iustin Pop committed
179
180
181
182
183
184
185
186
187
  """Simple wrapper to return an SshRunner.

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

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


191
192
193
194
195
196
197
198
199
def _Decompress(data):
  """Unpacks data compressed by the RPC client.

  @type data: list or tuple
  @param data: Data sent by RPC client
  @rtype: str
  @return: Decompressed data

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


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

Iustin Pop's avatar
Iustin Pop committed
214
215
  @type path: str
  @param path: the directory to clean
216
  @type exclude: list
Iustin Pop's avatar
Iustin Pop committed
217
218
  @param exclude: list of files to be excluded, defaults
      to the empty list
219
220

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

225
226
  if not os.path.isdir(path):
    return
227
228
229
230
231
  if exclude is None:
    exclude = []
  else:
    # Normalize excluded paths
    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
236
    if full_name in exclude:
      continue
237
238
239
240
    if os.path.isfile(full_name) and not os.path.islink(full_name):
      utils.RemoveFile(full_name)


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

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

  """
247
  allowed_files = set([
248
    pathutils.CLUSTER_CONF_FILE,
249
    pathutils.ETC_HOSTS,
250
251
252
253
254
255
256
257
    pathutils.SSH_KNOWN_HOSTS_FILE,
    pathutils.VNC_PASSWORD_FILE,
    pathutils.RAPI_CERT_FILE,
    pathutils.SPICE_CERT_FILE,
    pathutils.SPICE_CACERT_FILE,
    pathutils.RAPI_USERS_FILE,
    pathutils.CONFD_HMAC_KEY,
    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
265
266
  assert pathutils.FILE_STORAGE_PATHS_FILE not in allowed_files, \
    "Allowed file storage paths should never be uploaded via RPC"

267
  return frozenset(allowed_files)
268
269
270
271
272


_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()


273
def JobQueuePurge():
Iustin Pop's avatar
Iustin Pop committed
274
275
  """Removes job queue files and archived jobs.

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

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


284
285
286
287
288
289
290
def GetMasterInfo():
  """Returns master information.

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

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

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


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

  @type hook_opcode: string
  @param hook_opcode: opcode of the hook
  @type hooks_path: string
  @param hooks_path: path of the hooks
  @type env_builder_fn: function
  @param env_builder_fn: function that returns a dictionary containing the
318
319
    environment variables for the hooks. Will get all the parameters of the
    decorated function.
320
321
322
323
324
325
326
327
  @raise RPCFail: in case of pre-hook failure

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

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

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

      return result
    return wrapper
  return decorator


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

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

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

  return env


368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
def _RunMasterSetupScript(master_params, action, use_external_mip_script):
  """Execute the master IP address setup script.

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

  """
  env = _BuildMasterIpEnv(master_params)

  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
391
392

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

  if result.failed:
393
394
    _Fail("Failed to %s the master IP. Script return value: %s, output: '%s'" %
          (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
401
  """Activate the IP address of the master daemon.

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

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


def StartMasterDaemons(no_voting):
Iustin Pop's avatar
Iustin Pop committed
415
416
  """Activate local node as master node.

417
  The function will start the master daemons (ganeti-masterd and ganeti-rapi).
Iustin Pop's avatar
Iustin Pop committed
418

419
420
  @type no_voting: boolean
  @param no_voting: whether to start ganeti-masterd without a node vote
421
      but still non-interactively
Iustin Pop's avatar
Iustin Pop committed
422
  @rtype: None
Iustin Pop's avatar
Iustin Pop committed
423
424
425

  """

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

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

435
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "start-master"], env=env)
436
437
438
439
  if result.failed:
    msg = "Can't start Ganeti master: %s" % result.output
    logging.error(msg)
    _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.
Iustin Pop's avatar
Iustin Pop committed
446

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

Iustin Pop's avatar
Iustin Pop committed
454
  """
455
456
  _RunMasterSetupScript(master_params, _MASTER_STOP,
                        use_external_mip_script)
457

458
459
460
461
462
463
464
465
466
467
468
469

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

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

  @rtype: None

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

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


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

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

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

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

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

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


508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
def EtcHostsModify(mode, host, ip):
  """Modify a host entry in /etc/hosts.

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

  """
  if mode == constants.ETC_HOSTS_ADD:
    if not ip:
      RPCFail("Mode 'add' needs 'ip' parameter, but parameter not"
              " present")
    utils.AddHostToEtcHosts(host, ip)
  elif mode == constants.ETC_HOSTS_REMOVE:
    if ip:
      RPCFail("Mode 'remove' does not allow 'ip' parameter, but"
              " parameter is present")
    utils.RemoveHostFromEtcHosts(host)
  else:
    RPCFail("Mode not supported")


530
def LeaveCluster(modify_ssh_setup):
Iustin Pop's avatar
Iustin Pop committed
531
532
533
534
535
536
  """Cleans up and remove the current node.

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

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

540
541
  @param modify_ssh_setup: boolean

Iustin Pop's avatar
Iustin Pop committed
542
  """
543
544
  _CleanDirectory(pathutils.DATA_DIR)
  _CleanDirectory(pathutils.CRYPTO_KEYS_DIR)
545
  JobQueuePurge()
546

547
548
  if modify_ssh_setup:
    try:
Michael Hanselmann's avatar
Michael Hanselmann committed
549
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.SSH_LOGIN_USER)
550

551
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
Iustin Pop's avatar
Iustin Pop committed
552

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

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

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

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

Iustin Pop's avatar
Iustin Pop committed
575

576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
def _GetLvmVgSpaceInfo(name, params):
  """Wrapper around C{_GetVgInfo} which checks the storage parameters.

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

  """
  if params is None:
    raise errors.ProgrammerError("No storage parameter for LVM vg storage"
                                 " reporting is provided.")
  if not isinstance(params, list):
    raise errors.ProgrammerError("The storage parameters are not of type"
                                 " list: '%s'" % params)
  if not len(params) == 1:
    raise errors.ProgrammerError("Received more than one storage parameter:"
                                 " '%s'" % params)
  excl_stor = bool(params[0])
  return _GetVgInfo(name, excl_stor)


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

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

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


620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
def _GetVgSpindlesInfo(name, excl_stor):
  """Retrieves information about spindles in an LVM volume group.

  @type name: string
  @param name: VG name
  @type excl_stor: bool
  @param excl_stor: exclusive storage
  @rtype: dict
  @return: dictionary whose keys are "name", "vg_free", "vg_size" for VG name,
      free spindles, total spindles respectively

  """
  if excl_stor:
    (vg_free, vg_size) = bdev.LogicalVolume.GetVgSpindlesInfo(name)
  else:
    vg_free = 0
    vg_size = 0
  return {
638
    "type": constants.ST_LVM_PV,
639
    "name": name,
640
641
    "storage_free": vg_free,
    "storage_size": vg_size,
642
643
644
    }


645
def _GetHvInfo(name, hvparams, get_hv_fn=hypervisor.GetHypervisor):
646
647
648
649
650
651
652
653
654
655
656
  """Retrieves node information from a hypervisor.

  The information returned depends on the hypervisor. Common items:

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

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

660
  """
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
  return get_hv_fn(name).GetNodeInfo(hvparams=hvparams)


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

  See C{_GetHvInfo} for information on the output.

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

  """
  if hv_specs is None:
    return None

  result = []
  for hvname, hvparams in hv_specs:
    result.append(_GetHvInfo(hvname, hvparams, get_hv_fn))
  return result
680
681
682
683
684
685
686
687
688
689
690


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

  @rtype: None or dict

  """
  if names is None:
    return None
  else:
691
    return map(fn, names)
692
693


694
def GetNodeInfo(storage_units, hv_specs):
Michael Hanselmann's avatar
Michael Hanselmann committed
695
  """Gives back a hash with different information about the node.
Iustin Pop's avatar
Iustin Pop committed
696

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

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


718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
# pylint: disable=W0613
def _GetFileStorageSpaceInfo(path, *args):
  """Wrapper around filestorage.GetSpaceInfo.

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

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

  """
  return filestorage.GetFileStorageSpaceInfo(path)


733
734
735
736
737
# FIXME: implement storage reporting for all missing storage types.
_STORAGE_TYPE_INFO_FN = {
  constants.ST_BLOCK: None,
  constants.ST_DISKLESS: None,
  constants.ST_EXT: None,
738
  constants.ST_FILE: _GetFileStorageSpaceInfo,
739
  constants.ST_LVM_PV: _GetVgSpindlesInfo,
740
  constants.ST_LVM_VG: _GetLvmVgSpaceInfo,
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
  constants.ST_RADOS: None,
}


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

  @type storage_type: string
  @param storage_type: the storage type for which the storage shall be reported.
  @type storage_key: string
  @param storage_key: identifier of a storage unit, e.g. the volume group name
    of an LVM storage unit
  @type args: any
  @param args: various parameters that can be used for storage reporting. These
    parameters and their semantics vary from storage type to storage type and
    are just propagated in this function.
  @return: the results of the application of the storage space function (see
    _STORAGE_TYPE_INFO_FN) if storage space reporting is implemented for that
    storage type
  @raises NotImplementedError: for storage types who don't support space
    reporting yet
  """
  fn = _STORAGE_TYPE_INFO_FN[storage_type]
  if fn is not None:
    return fn(storage_key, *args)
  else:
    raise NotImplementedError
Iustin Pop's avatar
Iustin Pop committed
769
770


771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
def _CheckExclusivePvs(pvi_list):
  """Check that PVs are not shared among LVs

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

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

  """
  res = []
  for pvi in pvi_list:
    if len(pvi.lv_list) > 1:
      res.append((pvi.name, pvi.lv_list))
  return res


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

  @type what: C{dict}
  @param what: a dictionary of things to check
  @type vm_capable: boolean
795
  @param vm_capable: whether or not this node is vm capable
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
  @type result: dict
  @param result: dictionary of verification results; results of the
    verifications in this function will be added here
  @type all_hvparams: dict of dict of string
  @param all_hvparams: dictionary mapping hypervisor names to hvparams
  @type get_hv_fn: function
  @param get_hv_fn: function to retrieve the hypervisor, to improve testability

  """
  if not vm_capable:
    return

  if constants.NV_HYPERVISOR in what:
    result[constants.NV_HYPERVISOR] = {}
    for hv_name in what[constants.NV_HYPERVISOR]:
      hvparams = all_hvparams[hv_name]
      try:
        val = get_hv_fn(hv_name).Verify(hvparams=hvparams)
      except errors.HypervisorError, err:
        val = "Error while checking hypervisor: %s" % str(err)
      result[constants.NV_HYPERVISOR][hv_name] = val


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

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

  """
  if not vm_capable:
    return

  if constants.NV_HVPARAMS in what:
    result[constants.NV_HVPARAMS] = []
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
      try:
        logging.info("Validating hv %s, %s", hv_name, hvparms)
        get_hv_fn(hv_name).ValidateParameters(hvparms)
      except errors.HypervisorError, err:
        result[constants.NV_HVPARAMS].append((source, hv_name, str(err)))


847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
def _VerifyInstanceList(what, vm_capable, result, all_hvparams):
  """Verifies the instance list.

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

  """
  if constants.NV_INSTANCELIST in what and vm_capable:
    # GetInstanceList can fail
    try:
      val = GetInstanceList(what[constants.NV_INSTANCELIST],
                            all_hvparams=all_hvparams)
    except RPCFail, err:
      val = str(err)
    result[constants.NV_INSTANCELIST] = val


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

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

  """
  if constants.NV_HVINFO in what and vm_capable:
    hvname = what[constants.NV_HVINFO]
    hyper = hypervisor.GetHypervisor(hvname)
    hvparams = all_hvparams[hvname]
    result[constants.NV_HVINFO] = hyper.GetNodeInfo(hvparams=hvparams)


def VerifyNode(what, cluster_name, all_hvparams):
Iustin Pop's avatar
Iustin Pop committed
893
894
  """Verify the status of the local node.

895
896
897
898
899
900
901
902
903
  Based on the input L{what} parameter, various checks are done on the
  local node.

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

  If the I{nodelist} key is present, we check that we have
  connectivity via ssh with the target nodes (and check the hostname
  report).
Iustin Pop's avatar
Iustin Pop committed
904

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

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

  """
  result = {}
926
  my_name = netutils.Hostname.GetSysName()
927
  port = netutils.GetDaemonPort(constants.NODED)
928
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
Iustin Pop's avatar
Iustin Pop committed
929

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

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

  if constants.NV_NODELIST in what:
941
942
943
944
945
946
947
948
949
950
951
952
953
954
    (nodes, bynode) = what[constants.NV_NODELIST]

    # Add nodes from other groups (different for each node)
    try:
      nodes.extend(bynode[my_name])
    except KeyError:
      pass

    # Use a random order
    random.shuffle(nodes)

    # Try to contact all nodes
    val = {}
    for node in nodes:
955
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
Iustin Pop's avatar
Iustin Pop committed
956
      if not success:
957
958
959
        val[node] = message

    result[constants.NV_NODELIST] = val
960
961
962

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1099
  return result
Iustin Pop's avatar
Iustin Pop committed
1100
1101


1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
def GetBlockDevSizes(devices):
  """Return the size of the given block devices

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

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

  """
  DEV_PREFIX = "/dev/"
  blockdevs = {}

  for devpath in devices:
1119
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
      continue

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

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

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


1140
def GetVolumeList(vg_names):
Iustin Pop's avatar
Iustin Pop committed
1141
1142
  """Compute list of logical volumes and their size.

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

1151
        {'xenvg/test1': ('20.06', True, True)}
Iustin Pop's avatar
Iustin Pop committed
1152
1153
1154

      in case of errors, a string is returned with the error
      details.
Iustin Pop's avatar
Iustin Pop committed
1155
1156

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

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

  return lvs
Iustin Pop's avatar
Iustin Pop committed
1184
1185
1186


def ListVolumeGroups():
Alexander Schreiber's avatar
Alexander Schreiber committed
1187
  """List the volume groups and their size.
Iustin Pop's avatar
Iustin Pop committed
1188

Iustin Pop's avatar
Iustin Pop committed
1189
1190
1191
  @rtype: dict
  @return: dictionary with keys volume name and values the
      size of the volume
Iustin Pop's avatar
Iustin Pop committed
1192
1193

  """
1194
  return utils.ListVolumeGroups()
Iustin Pop's avatar
Iustin Pop committed
1195
1196


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

Iustin Pop's avatar
Iustin Pop committed
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
  @rtype: list
  @return:
    A list of dictionaries, each having four keys:
      - name: the logical volume name,
      - size: the size of the logical volume
      - dev: the physical device on which the LV lives
      - vg: the volume group to which it belongs

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

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

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

  def parse_dev(dev):
Iustin Pop's avatar
Iustin Pop committed
1224
    return dev.split("(")[0]
1225
1226
1227

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

  def map_line(line):
1230
    line = [v.strip() for v in line]
Iustin Pop's avatar
Iustin Pop committed
1231
1232
    return [{"name": line[0], "size": line[1],
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
1233
1234
1235

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


Iustin Pop's avatar
Iustin Pop committed
1243
def BridgesExist(bridges_list):
Alexander Schreiber's avatar
Alexander Schreiber committed
1244
  """Check if a list of bridges exist on the current node.
Iustin Pop's avatar
Iustin Pop committed
1245