backend.py 152 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.
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,C0302
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

37
38
# C0302: This module has become too big and should be split up

Iustin Pop's avatar
Iustin Pop committed
39

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

from ganeti import errors
57
from ganeti import http
Iustin Pop's avatar
Iustin Pop committed
58
59
60
61
from ganeti import utils
from ganeti import ssh
from ganeti import hypervisor
from ganeti import constants
62
63
from ganeti.storage import bdev
from ganeti.storage import drbd
64
from ganeti.storage import filestorage
Iustin Pop's avatar
Iustin Pop committed
65
from ganeti import objects
66
from ganeti import ssconf
67
from ganeti import serializer
68
from ganeti import netutils
69
from ganeti import runtime
70
from ganeti import compat
71
from ganeti import pathutils
72
from ganeti import vcluster
73
from ganeti import ht
74
75
from ganeti.storage.base import BlockDev
from ganeti.storage.drbd import DRBD8
76
from ganeti import hooksmaster
77
78
from ganeti.rpc import transport
from ganeti.rpc.errors import NoMasterError, TimeoutError
Iustin Pop's avatar
Iustin Pop committed
79
80


81
_BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id"
82
_ALLOWED_CLEAN_DIRS = compat.UniqueFrozenset([
83
84
85
86
  pathutils.DATA_DIR,
  pathutils.JOB_QUEUE_ARCHIVE_DIR,
  pathutils.QUEUE_DIR,
  pathutils.CRYPTO_KEYS_DIR,
87
  ])
88
89
90
_MAX_SSL_CERT_VALIDITY = 7 * 24 * 60 * 60
_X509_KEY_FILE = "key"
_X509_CERT_FILE = "cert"
91
92
93
_IES_STATUS_FILE = "status"
_IES_PID_FILE = "pid"
_IES_CA_FILE = "ca"
94

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

98
99
100
101
# Actions for the master setup script
_MASTER_START = "start"
_MASTER_STOP = "stop"

102
#: Maximum file permissions for restricted command directory and executables
103
104
105
106
_RCMD_MAX_MODE = (stat.S_IRWXU |
                  stat.S_IRGRP | stat.S_IXGRP |
                  stat.S_IROTH | stat.S_IXOTH)

107
#: Delay before returning an error for restricted commands
108
109
_RCMD_INVALID_DELAY = 10

110
#: How long to wait to acquire lock for restricted commands (shorter than
111
112
113
114
#: L{_RCMD_INVALID_DELAY}) to reduce blockage of noded forks when many
#: command requests arrive
_RCMD_LOCK_TIMEOUT = _RCMD_INVALID_DELAY * 0.8

115

116
117
118
119
120
121
122
class RPCFail(Exception):
  """Class denoting RPC failure.

  Its argument is the error message.

  """

123

124
def _GetInstReasonFilename(instance_name):
125
126
127
128
129
130
131
132
133
134
135
  """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)


136
137
138
139
140
141
142
143
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
144
145
146
147

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

148
149
150
151
152
153
154
155
  @rtype: None

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


156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
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
171
172
173
174
175
  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)
176
177
178
  raise RPCFail(msg)


Michael Hanselmann's avatar
Michael Hanselmann committed
179
def _GetConfig():
Iustin Pop's avatar
Iustin Pop committed
180
  """Simple wrapper to return a SimpleStore.
Iustin Pop's avatar
Iustin Pop committed
181

Iustin Pop's avatar
Iustin Pop committed
182
183
  @rtype: L{ssconf.SimpleStore}
  @return: a SimpleStore instance
Iustin Pop's avatar
Iustin Pop committed
184
185

  """
Iustin Pop's avatar
Iustin Pop committed
186
  return ssconf.SimpleStore()
Michael Hanselmann's avatar
Michael Hanselmann committed
187
188


189
def _GetSshRunner(cluster_name):
Iustin Pop's avatar
Iustin Pop committed
190
191
192
193
194
195
196
197
198
  """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

  """
199
  return ssh.SshRunner(cluster_name)
200
201


202
203
204
205
206
207
208
209
210
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

  """
211
  assert isinstance(data, (list, tuple))
212
213
214
215
216
217
218
219
220
221
  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")


222
def _CleanDirectory(path, exclude=None):
223
224
  """Removes all regular files in a directory.

Iustin Pop's avatar
Iustin Pop committed
225
226
  @type path: str
  @param path: the directory to clean
227
  @type exclude: list
Iustin Pop's avatar
Iustin Pop committed
228
229
  @param exclude: list of files to be excluded, defaults
      to the empty list
230
231

  """
232
233
234
235
  if path not in _ALLOWED_CLEAN_DIRS:
    _Fail("Path passed to _CleanDirectory not in allowed clean targets: '%s'",
          path)

236
237
  if not os.path.isdir(path):
    return
238
239
240
241
242
  if exclude is None:
    exclude = []
  else:
    # Normalize excluded paths
    exclude = [os.path.normpath(i) for i in exclude]
243

244
  for rel_name in utils.ListVisibleFiles(path):
245
    full_name = utils.PathJoin(path, rel_name)
246
247
    if full_name in exclude:
      continue
248
249
250
251
    if os.path.isfile(full_name) and not os.path.islink(full_name):
      utils.RemoveFile(full_name)


252
253
254
255
256
257
def _BuildUploadFileList():
  """Build the list of allowed upload files.

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

  """
258
  allowed_files = set([
259
    pathutils.CLUSTER_CONF_FILE,
260
    pathutils.ETC_HOSTS,
261
262
263
264
265
266
267
268
    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,
269
270
271
    ])

  for hv_name in constants.HYPER_TYPES:
272
    hv_class = hypervisor.GetHypervisorClass(hv_name)
273
    allowed_files.update(hv_class.GetAncillaryFiles()[0])
274

275
276
277
  assert pathutils.FILE_STORAGE_PATHS_FILE not in allowed_files, \
    "Allowed file storage paths should never be uploaded via RPC"

278
  return frozenset(allowed_files)
279
280
281
282
283


_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()


284
def JobQueuePurge():
Iustin Pop's avatar
Iustin Pop committed
285
286
  """Removes job queue files and archived jobs.

287
288
  @rtype: tuple
  @return: True, None
289
290

  """
291
292
  _CleanDirectory(pathutils.QUEUE_DIR, exclude=[pathutils.JOB_QUEUE_LOCK_FILE])
  _CleanDirectory(pathutils.JOB_QUEUE_ARCHIVE_DIR)
293
294


Jose A. Lopes's avatar
Jose A. Lopes committed
295
296
def GetMasterNodeName():
  """Returns the master node name.
297

Jose A. Lopes's avatar
Jose A. Lopes committed
298
299
  @rtype: string
  @return: name of the master node
300
  @raise RPCFail: in case of errors
301
302
303

  """
  try:
Jose A. Lopes's avatar
Jose A. Lopes committed
304
    return _GetConfig().GetMasterNode()
305
  except errors.ConfigurationError, err:
Iustin Pop's avatar
Iustin Pop committed
306
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
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
      hm = hooksmaster.HooksMaster(hook_opcode, hooks_path, nodes,
333
                                   hr.RunLocalHooks, None, env_fn, None,
334
335
                                   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
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)))


597
598
599
600
601
602
603
604
605
606
607
608
609
610
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


611
612
613
614
615
616
617
618
619
620
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

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


Helga Velroyen's avatar
Helga Velroyen committed
625
626
def _GetVgInfo(
    name, excl_stor, info_fn=bdev.LogicalVolume.GetVGInfo):
627
628
629
630
  """Retrieves information about a LVM volume group.

  """
  # TODO: GetVGInfo supports returning information for multiple VGs at once
Helga Velroyen's avatar
Helga Velroyen committed
631
  vginfo = info_fn([name], excl_stor)
632
633
634
635
636
637
638
639
  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 {
640
    "type": constants.ST_LVM_VG,
641
    "name": name,
642
643
    "storage_free": vg_free,
    "storage_size": vg_size,
644
645
646
    }


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

650
  @see: C{_GetLvmVgSpaceInfo}
651
652
653
654

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

656

657
658
def _GetVgSpindlesInfo(
    name, excl_stor, info_fn=bdev.LogicalVolume.GetVgSpindlesInfo):
659
660
661
662
663
664
665
666
667
668
669
670
  """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:
671
    (vg_free, vg_size) = info_fn(name)
672
673
674
675
  else:
    vg_free = 0
    vg_size = 0
  return {
676
    "type": constants.ST_LVM_PV,
677
    "name": name,
678
679
    "storage_free": vg_free,
    "storage_size": vg_size,
680
681
682
    }


683
def _GetHvInfo(name, hvparams, get_hv_fn=hypervisor.GetHypervisor):
684
685
686
687
688
689
690
691
692
693
694
  """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

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

698
  """
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
  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
718
719
720
721
722
723
724
725
726
727
728


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:
729
    return map(fn, names)
730
731


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

735
736
737
738
739
  @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.
740
741
  @type hv_specs: list of pairs (string, dict of strings)
  @param hv_specs: list of pairs of a hypervisor's name and its hvparams
742
743
744
  @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
745

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


756
def _GetFileStorageSpaceInfo(path, params):
757
758
759
760
761
762
763
764
765
766
  """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.

  """
767
  _CheckStorageParams(params, 0)
768
769
770
  return filestorage.GetFileStorageSpaceInfo(path)


771
772
773
774
775
# 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,
776
  constants.ST_FILE: _GetFileStorageSpaceInfo,
777
  constants.ST_LVM_PV: _GetLvmPvSpaceInfo,
778
  constants.ST_LVM_VG: _GetLvmVgSpaceInfo,
779
  constants.ST_SHARED_FILE: None,
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
  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
808
809


810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
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


827
828
829
830
831
832
833
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
834
  @param vm_capable: whether or not this node is vm capable
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
  @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
865
  @param vm_capable: whether or not this node is vm capable
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
  @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)))


886
887
888
889
890
891
892
893
894
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
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
931
932
933
934
935
936
937
938
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"
939
            " client certificates for all nodes." % create_cert_cmd)
Helga Velroyen's avatar
Helga Velroyen committed
940
941
942
943
944
945
946
947
948

  (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))


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

952
953
954
955
956
957
958
959
960
  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
961

962
963
964
965
966
967
968
969
970
971
972
  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
973
974
975
976
  @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
977
978
979
980
981
  @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
982
983
984
  @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
985
986
987

  """
  result = {}
988
  my_name = netutils.Hostname.GetSysName()
989
  port = netutils.GetDaemonPort(constants.NODED)
990
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
Iustin Pop's avatar
Iustin Pop committed
991

992
993
  _VerifyHypervisors(what, vm_capable, result, all_hvparams)
  _VerifyHvparams(what, vm_capable, result)
994

995
  if constants.NV_FILELIST in what:
996
997
998
999
1000
    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())
1001

Helga Velroyen's avatar
Helga Velroyen committed
1002
1003
1004
  if constants.NV_CLIENT_CERT in what:
    result[constants.NV_CLIENT_CERT] = _VerifyClientCertificate()

1005
  if constants.NV_NODELIST in what:
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
    (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:
1020
1021
1022
1023
1024
1025
      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
1026
      if not success:
1027
1028
1029
        val[node] = message

    result[constants.NV_NODELIST] = val
1030
1031
1032

  if constants.NV_NODENETTEST in what:
    result[constants.NV_NODENETTEST] = tmp = {}
1033
    my_pip = my_sip = None
1034
    for name, pip, sip in what[constants.NV_NODENETTEST]:
1035
1036
1037
1038
1039
      if name == my_name:
        my_pip = pip
        my_sip = sip
        break
    if not my_pip:
1040
1041
      tmp[my_name] = ("Can't find my own primary/secondary IP"
                      " in the node list")
1042
    else:
1043
      for name, pip, sip in what[constants.NV_NODENETTEST]:
1044
        fail = []
1045
        if not netutils.TcpPing(pip, port, source=my_pip):
1046
1047
          fail.append("primary")
        if sip != pip:
1048
          if not netutils.TcpPing(sip, port, source=my_sip):
1049
1050
            fail.append("secondary")
        if fail:
1051
1052
1053
          tmp[name] = ("failure using the %s interface(s)" %
                       " and ".join(fail))

1054
1055
1056
1057
1058
  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:
1059
      source = constants.IP4_ADDRESS_LOCALHOST
1060
1061
    else:
      source = None
1062
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
Iustin Pop's avatar
Iustin Pop committed
1063
                                                     source=source)
1064

1065
1066
1067
  if constants.NV_USERSCRIPTS in what:
    result[constants.NV_USERSCRIPTS] = \
      [script for script in what[constants.NV_USERSCRIPTS]
1068
       if not utils.IsExecutable(script)]
1069

1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
  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)

1086
  if constants.NV_LVLIST in what and vm_capable:
1087
    try:
1088
      val = GetVolumeList(utils.ListVolumeGroups().keys())
1089
1090
1091
    except RPCFail, err:
      val = str(err)
    result[constants.NV_LVLIST] = val
1092

1093
  _VerifyInstanceList(what, vm_capable, result, all_hvparams)
1094

1095
  if constants.NV_VGLIST in what and vm_capable:
1096
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
1097

1098
  if constants.NV_PVLIST in what and vm_capable:
1099
    check_exclusive_pvs = constants.NV_EXCLUSIVEPVS in what
1100
    val = bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
1101
1102
1103
1104
1105
1106
1107
                                       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 = []
1108
    result[constants.NV_PVLIST] = map(objects.LvmPvInfo.ToDict, val)
1109

1110
  if constants.NV_VERSION in what:
1111
1112
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
                                    constants.RELEASE_VERSION)
1113

1114
  _VerifyNodeInfo(what, vm_capable, result, all_hvparams)
1115

1116
1117
  if constants.NV_DRBDVERSION in what and vm_capable:
    try:
1118
      drbd_version = DRBD8.GetProcInfo().GetVersionString()
1119
1120
1121
1122
1123
    except errors.BlockDeviceError, err:
      logging.warning("Can't get DRBD version", exc_info=True)
      drbd_version = str(err)
    result[constants.NV_DRBDVERSION] = drbd_version

1124
  if constants.NV_DRBDLIST in what and vm_capable:
1125
    try:
1126
      used_minors = drbd.DRBD8.GetUsedDevs()
1127
    except errors.BlockDeviceError, err:
1128
      logging.warning("Can't get used minors list", exc_info=True)
1129
      used_minors = str(err)
1130
1131
    result[constants.NV_DRBDLIST] = used_minors

1132
  if constants.NV_DRBDHELPER in what and vm_capable:
1133
1134
    status = True
    try:
1135
      payload = drbd.DRBD8.GetUsermodeHelper()
1136
1137
1138
1139
1140
1141
    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)

1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
  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")
1153
1154
1155
1156

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

1157
  if constants.NV_OSLIST in what and vm_capable:
1158
1159
    result[constants.NV_OSLIST] = DiagnoseOS()

1160
1161
1162
1163
  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)]
1164

1165
1166
1167
  if what.get(constants.NV_ACCEPTED_STORAGE_PATHS) == my_name:
    result[constants.NV_ACCEPTED_STORAGE_PATHS] = \
        filestorage.ComputeWrongFileStoragePaths()
1168

Helga Velroyen's avatar
Helga Velroyen committed
1169
1170
1171
1172
1173
1174
  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

1175
1176
1177
1178
1179
1180
  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

1181
  return result
Iustin Pop's avatar
Iustin Pop committed
1182
1183


1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
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.
1200
1201
1202
1203
  @rtype: list of tuples (string, string)
  @return: list of tuples of the token type and the public crypto token

  """
1204
  getents = runtime.GetEnts()
1205
1206
1207
1208
  _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
1209
  tokens = []
1210
  for (token_type, action, options) in token_requests:
1211
    if token_type not in constants.CRYPTO_TYPES:
1212
      raise errors.ProgrammerError("Token type '%s' not supported." %
1213
                                   token_type)
1214
1215
1216
    if action not in constants.CRYPTO_ACTIONS:
      raise errors.ProgrammerError("Action '%s' is not supported." %
                                   action)
1217
    if token_type == constants.CRYPTO_TYPE_SSL_DIGEST:
1218
      if action == constants.CRYPTO_ACTION_CREATE:
1219
1220

        # extract file name from options
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
        cert_filename = None
        if options:
          cert_filename = options.get(constants.CRYPTO_OPTION_CERT_FILE)
        if not cert_filename:
          cert_filename = _DEFAULT_CERT_FILE
        # For security reason, we don't allow arbitrary filenames
        if not cert_filename in _VALID_CERT_FILES:
          raise errors.ProgrammerError(
            "The certificate file name path '%s' is not allowed." %
            cert_filename)
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247

        # extract serial number from options
        serial_no = None
        if options:
          try:
            serial_no = int(options[constants.CRYPTO_OPTION_SERIAL_NO])
          except ValueError:
            raise errors.ProgrammerError(
              "The given serial number is not an intenger: %s." %
              options.get(constants.CRYPTO_OPTION_SERIAL_NO))
          except KeyError:
            raise errors.ProgrammerError("No serial number was provided.")

        if not serial_no:
          raise errors.ProgrammerError(