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

Jose A. Lopes's avatar
Jose A. Lopes committed
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 Google Inc.
Klaus Aehlig's avatar
Klaus Aehlig committed
5
# All rights reserved.
Iustin Pop's avatar
Iustin Pop committed
6
#
Klaus Aehlig's avatar
Klaus Aehlig committed
7
8
9
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
Iustin Pop's avatar
Iustin Pop committed
10
#
Klaus Aehlig's avatar
Klaus Aehlig committed
11
12
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
Iustin Pop's avatar
Iustin Pop committed
13
#
Klaus Aehlig's avatar
Klaus Aehlig committed
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
Iustin Pop's avatar
Iustin Pop committed
29
30


31
32
33
34
"""Functions used by the node daemon

@var _ALLOWED_UPLOAD_FILES: denotes which files are accepted in
     the L{UploadFile} function
35
36
@var _ALLOWED_CLEAN_DIRS: denotes which directories are accepted
     in the L{_CleanDirectory} function
37
38

"""
Iustin Pop's avatar
Iustin Pop committed
39

40
# pylint: disable=E1103,C0302
Iustin Pop's avatar
Iustin Pop committed
41
42
43
44
45

# 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

46
47
# C0302: This module has become too big and should be split up

Iustin Pop's avatar
Iustin Pop committed
48

49
50
51
import base64
import errno
import logging
Iustin Pop's avatar
Iustin Pop committed
52
53
import os
import os.path
54
import pycurl
55
56
import random
import re
Iustin Pop's avatar
Iustin Pop committed
57
import shutil
58
import signal
59
import socket
Iustin Pop's avatar
Iustin Pop committed
60
import stat
61
import tempfile
62
import time
63
import zlib
Iustin Pop's avatar
Iustin Pop committed
64
65

from ganeti import errors
66
from ganeti import http
Iustin Pop's avatar
Iustin Pop committed
67
68
69
from ganeti import utils
from ganeti import ssh
from ganeti import hypervisor
70
from ganeti.hypervisor import hv_base
Iustin Pop's avatar
Iustin Pop committed
71
from ganeti import constants
72
73
from ganeti.storage import bdev
from ganeti.storage import drbd
74
from ganeti.storage import filestorage
Iustin Pop's avatar
Iustin Pop committed
75
from ganeti import objects
76
from ganeti import ssconf
77
from ganeti import serializer
78
from ganeti import netutils
79
from ganeti import runtime
80
from ganeti import compat
81
from ganeti import pathutils
82
from ganeti import vcluster
83
from ganeti import ht
84
85
from ganeti.storage.base import BlockDev
from ganeti.storage.drbd import DRBD8
86
from ganeti import hooksmaster
87
88
from ganeti.rpc import transport
from ganeti.rpc.errors import NoMasterError, TimeoutError
Iustin Pop's avatar
Iustin Pop committed
89
90


91
_BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id"
92
_ALLOWED_CLEAN_DIRS = compat.UniqueFrozenset([
93
94
95
96
  pathutils.DATA_DIR,
  pathutils.JOB_QUEUE_ARCHIVE_DIR,
  pathutils.QUEUE_DIR,
  pathutils.CRYPTO_KEYS_DIR,
97
  ])
98
99
100
_MAX_SSL_CERT_VALIDITY = 7 * 24 * 60 * 60
_X509_KEY_FILE = "key"
_X509_CERT_FILE = "cert"
101
102
103
_IES_STATUS_FILE = "status"
_IES_PID_FILE = "pid"
_IES_CA_FILE = "ca"
104

105
#: Valid LVS output line regex
Michele Tartara's avatar
Michele Tartara committed
106
_LVSLINE_REGEX = re.compile(r"^ *([^|]+)\|([^|]+)\|([0-9.]+)\|([^|]{6,})\|?$")
107

108
109
110
111
# Actions for the master setup script
_MASTER_START = "start"
_MASTER_STOP = "stop"

112
#: Maximum file permissions for restricted command directory and executables
113
114
115
116
_RCMD_MAX_MODE = (stat.S_IRWXU |
                  stat.S_IRGRP | stat.S_IXGRP |
                  stat.S_IROTH | stat.S_IXOTH)

117
#: Delay before returning an error for restricted commands
118
119
_RCMD_INVALID_DELAY = 10

120
#: How long to wait to acquire lock for restricted commands (shorter than
121
122
123
124
#: L{_RCMD_INVALID_DELAY}) to reduce blockage of noded forks when many
#: command requests arrive
_RCMD_LOCK_TIMEOUT = _RCMD_INVALID_DELAY * 0.8

125

126
127
128
129
130
131
132
class RPCFail(Exception):
  """Class denoting RPC failure.

  Its argument is the error message.

  """

133

134
def _GetInstReasonFilename(instance_name):
135
136
137
138
139
140
141
142
143
144
145
  """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)


146
147
148
149
150
151
152
153
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
Jose A. Lopes's avatar
Jose A. Lopes committed
154
155
156
157

  @type trail: list of reasons
  @param trail: reason trail

158
159
160
161
162
163
164
165
  @rtype: None

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


166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
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
181
182
183
184
185
  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)
186
187
188
  raise RPCFail(msg)


Michael Hanselmann's avatar
Michael Hanselmann committed
189
def _GetConfig():
Iustin Pop's avatar
Iustin Pop committed
190
  """Simple wrapper to return a SimpleStore.
Iustin Pop's avatar
Iustin Pop committed
191

Iustin Pop's avatar
Iustin Pop committed
192
193
  @rtype: L{ssconf.SimpleStore}
  @return: a SimpleStore instance
Iustin Pop's avatar
Iustin Pop committed
194
195

  """
Iustin Pop's avatar
Iustin Pop committed
196
  return ssconf.SimpleStore()
Michael Hanselmann's avatar
Michael Hanselmann committed
197
198


199
def _GetSshRunner(cluster_name):
Iustin Pop's avatar
Iustin Pop committed
200
201
202
203
204
205
206
207
208
  """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

  """
209
  return ssh.SshRunner(cluster_name)
210
211


212
213
214
215
216
217
218
219
220
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

  """
221
  assert isinstance(data, (list, tuple))
222
223
224
225
226
227
228
229
230
231
  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")


232
def _CleanDirectory(path, exclude=None):
233
234
  """Removes all regular files in a directory.

Iustin Pop's avatar
Iustin Pop committed
235
236
  @type path: str
  @param path: the directory to clean
237
  @type exclude: list
Iustin Pop's avatar
Iustin Pop committed
238
239
  @param exclude: list of files to be excluded, defaults
      to the empty list
240
241

  """
242
243
244
245
  if path not in _ALLOWED_CLEAN_DIRS:
    _Fail("Path passed to _CleanDirectory not in allowed clean targets: '%s'",
          path)

246
247
  if not os.path.isdir(path):
    return
248
249
250
251
252
  if exclude is None:
    exclude = []
  else:
    # Normalize excluded paths
    exclude = [os.path.normpath(i) for i in exclude]
253

254
  for rel_name in utils.ListVisibleFiles(path):
255
    full_name = utils.PathJoin(path, rel_name)
256
257
    if full_name in exclude:
      continue
258
259
260
261
    if os.path.isfile(full_name) and not os.path.islink(full_name):
      utils.RemoveFile(full_name)


262
263
264
265
266
267
def _BuildUploadFileList():
  """Build the list of allowed upload files.

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

  """
268
  allowed_files = set([
269
    pathutils.CLUSTER_CONF_FILE,
270
    pathutils.ETC_HOSTS,
271
272
273
274
275
276
277
278
    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,
279
280
281
    ])

  for hv_name in constants.HYPER_TYPES:
282
    hv_class = hypervisor.GetHypervisorClass(hv_name)
283
    allowed_files.update(hv_class.GetAncillaryFiles()[0])
284

285
286
287
  assert pathutils.FILE_STORAGE_PATHS_FILE not in allowed_files, \
    "Allowed file storage paths should never be uploaded via RPC"

288
  return frozenset(allowed_files)
289
290
291
292
293


_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()


294
def JobQueuePurge():
Iustin Pop's avatar
Iustin Pop committed
295
296
  """Removes job queue files and archived jobs.

297
298
  @rtype: tuple
  @return: True, None
299
300

  """
301
302
  _CleanDirectory(pathutils.QUEUE_DIR, exclude=[pathutils.JOB_QUEUE_LOCK_FILE])
  _CleanDirectory(pathutils.JOB_QUEUE_ARCHIVE_DIR)
303
304


Jose A. Lopes's avatar
Jose A. Lopes committed
305
306
def GetMasterNodeName():
  """Returns the master node name.
307

Jose A. Lopes's avatar
Jose A. Lopes committed
308
309
  @rtype: string
  @return: name of the master node
310
  @raise RPCFail: in case of errors
311
312
313

  """
  try:
Jose A. Lopes's avatar
Jose A. Lopes committed
314
    return _GetConfig().GetMasterNode()
315
  except errors.ConfigurationError, err:
Iustin Pop's avatar
Iustin Pop committed
316
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
317
318


319
320
321
322
323
324
325
326
327
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
328
329
    environment variables for the hooks. Will get all the parameters of the
    decorated function.
330
331
332
333
334
335
336
337
  @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

338
339
      env_fn = compat.partial(env_builder_fn, *args, **kwargs)

340
341
      cfg = _GetConfig()
      hr = HooksRunner()
342
      hm = hooksmaster.HooksMaster(hook_opcode, hooks_path, nodes,
343
                                   hr.RunLocalHooks, None, env_fn, None,
344
345
                                   logging.warning, cfg.GetClusterName(),
                                   cfg.GetMasterNode())
346
347
348
349
350
351
352
353
354
      hm.RunPhase(constants.HOOKS_PHASE_PRE)
      result = fn(*args, **kwargs)
      hm.RunPhase(constants.HOOKS_PHASE_POST)

      return result
    return wrapper
  return decorator


355
def _BuildMasterIpEnv(master_params, use_external_mip_script=None):
356
357
  """Builds environment variables for master IP hooks.

358
359
  @type master_params: L{objects.MasterNetworkParameters}
  @param master_params: network parameters of the master
360
361
362
363
  @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)
364

365
  """
366
  # pylint: disable=W0613
367
  ver = netutils.IPAddress.GetVersionFromAddressFamily(master_params.ip_family)
368
  env = {
369
370
    "MASTER_NETDEV": master_params.netdev,
    "MASTER_IP": master_params.ip,
371
    "MASTER_NETMASK": str(master_params.netmask),
372
    "CLUSTER_IP_VERSION": str(ver),
373
374
375
376
377
  }

  return env


378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
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:
396
    setup_script = pathutils.EXTERNAL_MASTER_SETUP_SCRIPT
397
  else:
398
    setup_script = pathutils.DEFAULT_MASTER_SETUP_SCRIPT
399
400
401
402

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

  if result.failed:
403
404
    _Fail("Failed to %s the master IP. Script return value: %s, output: '%s'" %
          (action, result.exit_code, result.output), log=True)
405
406


407
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNUP, "master-ip-turnup",
408
               _BuildMasterIpEnv)
409
def ActivateMasterIp(master_params, use_external_mip_script):
410
411
  """Activate the IP address of the master daemon.

412
413
  @type master_params: L{objects.MasterNetworkParameters}
  @param master_params: network parameters of the master
414
415
416
  @type use_external_mip_script: boolean
  @param use_external_mip_script: whether to use an external master IP
    address setup script
417
  @raise RPCFail: in case of errors during the IP startup
418

419
  """
420
421
  _RunMasterSetupScript(master_params, _MASTER_START,
                        use_external_mip_script)
422
423
424


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

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

429
430
  @type no_voting: boolean
  @param no_voting: whether to start ganeti-masterd without a node vote
431
      but still non-interactively
Iustin Pop's avatar
Iustin Pop committed
432
  @rtype: None
Iustin Pop's avatar
Iustin Pop committed
433
434
435

  """

436
437
438
439
  if no_voting:
    masterd_args = "--no-voting --yes-do-it"
  else:
    masterd_args = ""
440

441
442
443
444
  env = {
    "EXTRA_MASTERD_ARGS": masterd_args,
    }

445
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "start-master"], env=env)
446
447
448
449
  if result.failed:
    msg = "Can't start Ganeti master: %s" % result.output
    logging.error(msg)
    _Fail(msg)
450

451

452
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNDOWN, "master-ip-turndown",
453
               _BuildMasterIpEnv)
454
def DeactivateMasterIp(master_params, use_external_mip_script):
455
  """Deactivate the master IP on this node.
Iustin Pop's avatar
Iustin Pop committed
456

457
458
  @type master_params: L{objects.MasterNetworkParameters}
  @param master_params: network parameters of the master
459
460
461
  @type use_external_mip_script: boolean
  @param use_external_mip_script: whether to use an external master IP
    address setup script
462
  @raise RPCFail: in case of errors during the IP turndown
463

Iustin Pop's avatar
Iustin Pop committed
464
  """
465
466
  _RunMasterSetupScript(master_params, _MASTER_STOP,
                        use_external_mip_script)
467

468
469
470
471
472
473
474
475
476
477
478
479

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

480
  result = utils.RunCmd([pathutils.DAEMON_UTIL, "stop-master"])
481
482
483
484
  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
485
486


487
def ChangeMasterNetmask(old_netmask, netmask, master_ip, master_netdev):
488
489
  """Change the netmask of the master IP.

490
491
492
493
494
  @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

495
496
497
498
  """
  if old_netmask == netmask:
    return

499
500
501
502
  if not netutils.IPAddress.Own(master_ip):
    _Fail("The master IP address is not up, not attempting to change its"
          " netmask")

503
504
505
506
507
  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:
508
    _Fail("Could not set the new netmask on the master IP address")
509
510
511
512
513
514

  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:
515
    _Fail("Could not bring down the master IP address with the old netmask")
516
517


518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
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")


540
def LeaveCluster(modify_ssh_setup):
Iustin Pop's avatar
Iustin Pop committed
541
542
543
544
545
546
  """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
547
  L{errors.QuitGanetiException} which is used as a special case to
Iustin Pop's avatar
Iustin Pop committed
548
  shutdown the node daemon.
Iustin Pop's avatar
Iustin Pop committed
549

550
551
  @param modify_ssh_setup: boolean

Iustin Pop's avatar
Iustin Pop committed
552
  """
553
554
  _CleanDirectory(pathutils.DATA_DIR)
  _CleanDirectory(pathutils.CRYPTO_KEYS_DIR)
555
  JobQueuePurge()
556

557
558
  if modify_ssh_setup:
    try:
Michael Hanselmann's avatar
Michael Hanselmann committed
559
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.SSH_LOGIN_USER)
560

561
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
Iustin Pop's avatar
Iustin Pop committed
562

563
564
565
566
      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
567

568
  try:
569
570
571
572
573
    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)
574
  except: # pylint: disable=W0702
575
576
    logging.exception("Error while removing cluster secrets")

577
  utils.StopDaemon(constants.CONFD)
578
  utils.StopDaemon(constants.MOND)
579
  utils.StopDaemon(constants.KVMD)
580

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

Iustin Pop's avatar
Iustin Pop committed
584

585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
def _CheckStorageParams(params, num_params):
  """Performs sanity checks for storage parameters.

  @type params: list
  @param params: list of storage parameters
  @type num_params: int
  @param num_params: expected number of parameters

  """
  if params is None:
    raise errors.ProgrammerError("No storage parameters for 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) == num_params:
    raise errors.ProgrammerError("Did not receive the expected number of"
                                 "storage parameters: expected %s,"
                                 " received '%s'" % (num_params, len(params)))


606
607
608
609
610
611
612
613
614
615
616
617
618
619
def _CheckLvmStorageParams(params):
  """Performs sanity check for the 'exclusive storage' flag.

  @see: C{_CheckStorageParams}

  """
  _CheckStorageParams(params, 1)
  excl_stor = params[0]
  if not isinstance(params[0], bool):
    raise errors.ProgrammerError("Exclusive storage parameter is not"
                                 " boolean: '%s'." % excl_stor)
  return excl_stor


620
621
622
623
624
625
626
627
628
629
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

  """
630
  excl_stor = _CheckLvmStorageParams(params)
631
632
633
  return _GetVgInfo(name, excl_stor)


Helga Velroyen's avatar
Helga Velroyen committed
634
635
def _GetVgInfo(
    name, excl_stor, info_fn=bdev.LogicalVolume.GetVGInfo):
636
637
638
639
  """Retrieves information about a LVM volume group.

  """
  # TODO: GetVGInfo supports returning information for multiple VGs at once
Helga Velroyen's avatar
Helga Velroyen committed
640
  vginfo = info_fn([name], excl_stor)
641
642
643
644
645
646
647
648
  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 {
649
    "type": constants.ST_LVM_VG,
650
    "name": name,
651
652
    "storage_free": vg_free,
    "storage_size": vg_size,
653
654
655
    }


656
657
658
def _GetLvmPvSpaceInfo(name, params):
  """Wrapper around C{_GetVgSpindlesInfo} with sanity checks.

659
  @see: C{_GetLvmVgSpaceInfo}
660
661
662
663

  """
  excl_stor = _CheckLvmStorageParams(params)
  return _GetVgSpindlesInfo(name, excl_stor)
Helga Velroyen's avatar
Helga Velroyen committed
664

665

666
667
def _GetVgSpindlesInfo(
    name, excl_stor, info_fn=bdev.LogicalVolume.GetVgSpindlesInfo):
668
669
670
671
672
673
674
675
676
677
678
679
  """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:
680
    (vg_free, vg_size) = info_fn(name)
681
682
683
684
  else:
    vg_free = 0
    vg_size = 0
  return {
685
    "type": constants.ST_LVM_PV,
686
    "name": name,
687
688
    "storage_free": vg_free,
    "storage_size": vg_size,
689
690
691
    }


692
def _GetHvInfo(name, hvparams, get_hv_fn=hypervisor.GetHypervisor):
693
694
695
696
697
698
699
700
701
702
703
  """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

704
705
706
  @type hvparams: dict of string
  @param hvparams: the hypervisor's hvparams

707
  """
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
  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
727
728
729
730
731
732
733
734
735
736
737


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:
738
    return map(fn, names)
739
740


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

744
745
746
747
748
  @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.
749
750
  @type hv_specs: list of pairs (string, dict of strings)
  @param hv_specs: list of pairs of a hypervisor's name and its hvparams
751
752
753
  @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
754

755
  """
756
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
757
758
  storage_info = _GetNamedNodeInfo(
    storage_units,
759
760
    (lambda (storage_type, storage_key, storage_params):
        _ApplyStorageInfoFunction(storage_type, storage_key, storage_params)))
761
  hv_info = _GetHvInfoAll(hv_specs)
762
763
764
  return (bootid, storage_info, hv_info)


765
def _GetFileStorageSpaceInfo(path, params):
766
767
768
769
770
771
772
773
774
775
  """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.

  """
776
  _CheckStorageParams(params, 0)
777
778
779
  return filestorage.GetFileStorageSpaceInfo(path)


780
781
782
783
784
# 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,
785
  constants.ST_FILE: _GetFileStorageSpaceInfo,
786
  constants.ST_LVM_PV: _GetLvmPvSpaceInfo,
787
  constants.ST_LVM_VG: _GetLvmVgSpaceInfo,
788
  constants.ST_SHARED_FILE: None,
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
  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
817
818


819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
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


836
837
838
839
840
841
842
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
843
  @param vm_capable: whether or not this node is vm capable
844
845
846
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
  @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
874
  @param vm_capable: whether or not this node is vm capable
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
  @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)))


895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
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)


Helga Velroyen's avatar
Helga Velroyen committed
940
941
942
943
944
945
946
947
def _VerifyClientCertificate(cert_file=pathutils.NODED_CLIENT_CERT_FILE):
  """Verify the existance and validity of the client SSL certificate.

  """
  create_cert_cmd = "gnt-cluster renew-crypto --new-node-certificates"
  if not os.path.exists(cert_file):
    return (constants.CV_ERROR,
            "The client certificate does not exist. Run '%s' to create"
948
            " client certificates for all nodes." % create_cert_cmd)
Helga Velroyen's avatar
Helga Velroyen committed
949
950
951
952
953
954
955
956
957

  (errcode, msg) = utils.VerifyCertificate(cert_file)
  if errcode is not None:
    return (errcode, msg)
  else:
    # if everything is fine, we return the digest to be compared to the config
    return (None, utils.GetCertificateDigest(cert_filename=cert_file))


958
def VerifyNode(what, cluster_name, all_hvparams, node_groups, groups_cfg):
Iustin Pop's avatar
Iustin Pop committed
959
960
  """Verify the status of the local node.

961
962
963
964
965
966
967
968
969
  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
970

971
972
973
974
975
976
977
978
979
980
981
  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
982
983
984
985
  @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
986
987
988
989
990
  @type node_groups: a dict of strings
  @param node_groups: node _names_ mapped to their group uuids (it's enough to
      have only those nodes that are in `what["nodelist"]`)
  @type groups_cfg: a dict of dict of strings
  @param groups_cfg: a dictionary mapping group uuids to their configuration
Iustin Pop's avatar
Iustin Pop committed
991
992
993
  @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
994
995
996

  """
  result = {}
997
  my_name = netutils.Hostname.GetSysName()
998
  port = netutils.GetDaemonPort(constants.NODED)
999
  vm_capable = my_name not in what.get(constants.NV_NONVMNODES, [])
Iustin Pop's avatar
Iustin Pop committed
1000

1001
1002
  _VerifyHypervisors(what, vm_capable, result, all_hvparams)
  _VerifyHvparams(what, vm_capable, result)
1003

1004
  if constants.NV_FILELIST in what:
1005
1006
1007
1008
1009
    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())
1010

Helga Velroyen's avatar
Helga Velroyen committed
1011
1012
1013
  if constants.NV_CLIENT_CERT in what:
    result[constants.NV_CLIENT_CERT] = _VerifyClientCertificate()

1014
  if constants.NV_NODELIST in what:
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
    (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:
1029
1030
1031
1032
1033
1034
      params = groups_cfg.get(node_groups.get(node))
      ssh_port = params["ndparams"].get(constants.ND_SSH_PORT)
      logging.debug("Ssh port %s (None = default) for node %s",
                    str(ssh_port), node)
      success, message = _GetSshRunner(cluster_name). \
                            VerifyNodeHostname(node, ssh_port)
Iustin Pop's avatar
Iustin Pop committed
1035
      if not success:
1036
1037
1038
        val[node] = message

    result[constants.NV_NODELIST] = val
1039
1040
1041

  if constants.NV_NODENETTEST in what:
    result[constants.NV_NODENETTEST] = tmp = {}
1042
    my_pip = my_sip = None
1043
    for name, pip, sip in what[constants.NV_NODENETTEST]:
1044
1045
1046
1047
1048
      if name == my_name:
        my_pip = pip
        my_sip = sip
        break
    if not my_pip:
1049
1050
      tmp[my_name] = ("Can't find my own primary/secondary IP"
                      " in the node list")
1051
    else:
1052
      for name, pip, sip in what[constants.NV_NODENETTEST]:
1053
        fail = []
1054
        if not netutils.TcpPing(pip, port, source=my_pip):
1055
1056
          fail.append("primary")
        if sip != pip:
1057
          if not netutils.TcpPing(sip, port, source=my_sip):
1058
1059
            fail.append("secondary")
        if fail:
1060
1061
1062
          tmp[name] = ("failure using the %s interface(s)" %
                       " and ".join(fail))

1063
1064
1065
1066
1067
  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:
1068
      source = constants.IP4_ADDRESS_LOCALHOST
1069
1070
    else:
      source = None
1071
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
Iustin Pop's avatar
Iustin Pop committed
1072
                                                     source=source)
1073

1074
1075
1076
  if constants.NV_USERSCRIPTS in what:
    result[constants.NV_USERSCRIPTS] = \
      [script for script in what[constants.NV_USERSCRIPTS]
1077
       if not utils.IsExecutable(script)]
1078

1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
  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)

1095
  if constants.NV_LVLIST in what and vm_capable:
1096
    try:
1097
      val = GetVolumeList([what[constants.NV_LVLIST]])
1098
1099
1100
    except RPCFail, err:
      val = str(err)
    result[constants.NV_LVLIST] = val
1101

1102
  _VerifyInstanceList(what, vm_capable, result, all_hvparams)
1103

1104
  if constants.NV_VGLIST in what and vm_capable:
1105
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
1106

1107
  if constants.NV_PVLIST in what and vm_capable:
1108
    check_exclusive_pvs = constants.NV_EXCLUSIVEPVS in what
1109
    val = bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
1110
1111
1112
1113
1114
1115
1116
                                       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 = []
1117
    result[constants.NV_PVLIST] = map(objects.LvmPvInfo.ToDict, val)
1118

1119
  if constants.NV_VERSION in what:
1120
1121
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
                                    constants.RELEASE_VERSION)
1122

1123
  _VerifyNodeInfo(what, vm_capable, result, all_hvparams)
1124

1125
1126
  if constants.NV_DRBDVERSION in what and vm_capable:
    try:
1127
      drbd_version = DRBD8.GetProcInfo().GetVersionString()
1128
1129
1130
1131
1132
    except errors.BlockDeviceError, err:
      logging.warning("Can't get DRBD version", exc_info=True)
      drbd_version = str(err)
    result[constants.NV_DRBDVERSION] = drbd_version

1133
  if constants.NV_DRBDLIST in what and vm_capable:
1134
    try:
1135
      used_minors = drbd.DRBD8.GetUsedDevs()
1136
    except errors.BlockDeviceError, err:
1137
      logging.warning("Can't get used minors list", exc_info=True)
1138
      used_minors = str(err)
1139
1140
    result[constants.NV_DRBDLIST] = used_minors

1141
  if constants.NV_DRBDHELPER in what and vm_capable:
1142
1143
    status = True
    try:
1144
      payload = drbd.DRBD8.GetUsermodeHelper()
1145
1146
1147
1148
1149
1150
    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)

1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
  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")
1162
1163
1164
1165

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

1166
  if constants.NV_OSLIST in what and vm_capable:
1167
1168
    result[constants.NV_OSLIST] = DiagnoseOS()

1169
1170
1171
1172
  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)]
1173

1174
1175
1176
  if what.get(constants.NV_ACCEPTED_STORAGE_PATHS) == my_name:
    result[constants.NV_ACCEPTED_STORAGE_PATHS] = \
        filestorage.ComputeWrongFileStoragePaths()
1177

Helga Velroyen's avatar
Helga Velroyen committed
1178
1179
1180
1181
1182
1183
  if what.get(constants.NV_FILE_STORAGE_PATH):
    pathresult = filestorage.CheckFileStoragePath(
        what[constants.NV_FILE_STORAGE_PATH])
    if pathresult:
      result[constants.NV_FILE_STORAGE_PATH] = pathresult

1184
1185
1186
1187
1188
1189
  if what.get(constants.NV_SHARED_FILE_STORAGE_PATH):
    pathresult = filestorage.CheckFileStoragePath(
        what[constants.NV_SHARED_FILE_STORAGE_PATH])
    if pathresult:
      result[constants.NV_SHARED_FILE_STORAGE_PATH] = pathresult

1190
  return result
Iustin Pop's avatar
Iustin Pop committed
1191
1192


1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
def GetCryptoTokens(token_requests):
  """Perform actions on the node's cryptographic tokens.

  Token types can be 'ssl' or 'ssh'. So far only some actions are implemented
  for 'ssl'. Action 'get' returns the digest of the public client ssl
  certificate. Action 'create' creates a new client certificate and private key
  and also returns the digest of the certificate. The third parameter of a
  token request are optional parameters for the actions, so far only the
  filename is supported.

  @type token_requests: list of tuples of (string, string, dict), where the
    first string is in constants.CRYPTO_TYPES, the second in
    constants.CRYPTO_ACTIONS. The third parameter is a dictionary of string
    to string.
  @param token_requests: list of requests of cryptographic tokens and actions
    to perform on them. The actions come with a dictionary of options.
1209
1210
1211
1212
  @rtype: list of tuples (string, string)
  @return: list of tuples of the token type and the public crypto token

  """
1213
  getents = runtime.GetEnts()
1214
1215
1216
1217
  _VALID_CERT_FILES = [pathutils.NODED_CERT_FILE,
                       pathutils.NODED_CLIENT_CERT_FILE,
                       pathutils.NODED_CLIENT_CERT_FILE_TMP]
  _DEFAULT_CERT_FILE = pathutils.NODED_CLIENT_CERT_FILE
1218
  tokens = []
1219
  for (token_type, action, options) in token_requests:
1220
    if token_type not in constants.CRYPTO_TYPES:
1221
      raise errors.ProgrammerError("Token type '%s' not supported." %
1222
                                   token_type)
1223
1224
1225
    if action not in constants.CRYPTO_ACTIONS:
      raise errors.ProgrammerError("Action '%s' is not supported." %
                                   action)
1226