Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 6ece11be

History | View | Annotate | Download (115.2 kB)

1
#
2
#
3

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

    
21

    
22
"""Functions used by the node daemon
23

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

29
"""
30

    
31
# pylint: disable=E1103
32

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

    
37

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

    
52
from ganeti import errors
53
from ganeti import utils
54
from ganeti import ssh
55
from ganeti import hypervisor
56
from ganeti import constants
57
from ganeti import bdev
58
from ganeti import objects
59
from ganeti import ssconf
60
from ganeti import serializer
61
from ganeti import netutils
62
from ganeti import runtime
63
from ganeti import mcpu
64
from ganeti import compat
65

    
66

    
67
_BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id"
68
_ALLOWED_CLEAN_DIRS = frozenset([
69
  constants.DATA_DIR,
70
  constants.JOB_QUEUE_ARCHIVE_DIR,
71
  constants.QUEUE_DIR,
72
  constants.CRYPTO_KEYS_DIR,
73
  ])
74
_MAX_SSL_CERT_VALIDITY = 7 * 24 * 60 * 60
75
_X509_KEY_FILE = "key"
76
_X509_CERT_FILE = "cert"
77
_IES_STATUS_FILE = "status"
78
_IES_PID_FILE = "pid"
79
_IES_CA_FILE = "ca"
80

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

    
84
# Actions for the master setup script
85
_MASTER_START = "start"
86
_MASTER_STOP = "stop"
87

    
88

    
89
class RPCFail(Exception):
90
  """Class denoting RPC failure.
91

92
  Its argument is the error message.
93

94
  """
95

    
96

    
97
def _Fail(msg, *args, **kwargs):
98
  """Log an error and the raise an RPCFail exception.
99

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

105
  @type msg: string
106
  @param msg: the text of the exception
107
  @raise RPCFail
108

109
  """
110
  if args:
111
    msg = msg % args
112
  if "log" not in kwargs or kwargs["log"]: # if we should log this error
113
    if "exc" in kwargs and kwargs["exc"]:
114
      logging.exception(msg)
115
    else:
116
      logging.error(msg)
117
  raise RPCFail(msg)
118

    
119

    
120
def _GetConfig():
121
  """Simple wrapper to return a SimpleStore.
122

123
  @rtype: L{ssconf.SimpleStore}
124
  @return: a SimpleStore instance
125

126
  """
127
  return ssconf.SimpleStore()
128

    
129

    
130
def _GetSshRunner(cluster_name):
131
  """Simple wrapper to return an SshRunner.
132

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

139
  """
140
  return ssh.SshRunner(cluster_name)
141

    
142

    
143
def _Decompress(data):
144
  """Unpacks data compressed by the RPC client.
145

146
  @type data: list or tuple
147
  @param data: Data sent by RPC client
148
  @rtype: str
149
  @return: Decompressed data
150

151
  """
152
  assert isinstance(data, (list, tuple))
153
  assert len(data) == 2
154
  (encoding, content) = data
155
  if encoding == constants.RPC_ENCODING_NONE:
156
    return content
157
  elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
158
    return zlib.decompress(base64.b64decode(content))
159
  else:
160
    raise AssertionError("Unknown data encoding")
161

    
162

    
163
def _CleanDirectory(path, exclude=None):
164
  """Removes all regular files in a directory.
165

166
  @type path: str
167
  @param path: the directory to clean
168
  @type exclude: list
169
  @param exclude: list of files to be excluded, defaults
170
      to the empty list
171

172
  """
173
  if path not in _ALLOWED_CLEAN_DIRS:
174
    _Fail("Path passed to _CleanDirectory not in allowed clean targets: '%s'",
175
          path)
176

    
177
  if not os.path.isdir(path):
178
    return
179
  if exclude is None:
180
    exclude = []
181
  else:
182
    # Normalize excluded paths
183
    exclude = [os.path.normpath(i) for i in exclude]
184

    
185
  for rel_name in utils.ListVisibleFiles(path):
186
    full_name = utils.PathJoin(path, rel_name)
187
    if full_name in exclude:
188
      continue
189
    if os.path.isfile(full_name) and not os.path.islink(full_name):
190
      utils.RemoveFile(full_name)
191

    
192

    
193
def _BuildUploadFileList():
194
  """Build the list of allowed upload files.
195

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

198
  """
199
  allowed_files = set([
200
    constants.CLUSTER_CONF_FILE,
201
    constants.ETC_HOSTS,
202
    constants.SSH_KNOWN_HOSTS_FILE,
203
    constants.VNC_PASSWORD_FILE,
204
    constants.RAPI_CERT_FILE,
205
    constants.SPICE_CERT_FILE,
206
    constants.SPICE_CACERT_FILE,
207
    constants.RAPI_USERS_FILE,
208
    constants.CONFD_HMAC_KEY,
209
    constants.CLUSTER_DOMAIN_SECRET_FILE,
210
    ])
211

    
212
  for hv_name in constants.HYPER_TYPES:
213
    hv_class = hypervisor.GetHypervisorClass(hv_name)
214
    allowed_files.update(hv_class.GetAncillaryFiles()[0])
215

    
216
  return frozenset(allowed_files)
217

    
218

    
219
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
220

    
221

    
222
def JobQueuePurge():
223
  """Removes job queue files and archived jobs.
224

225
  @rtype: tuple
226
  @return: True, None
227

228
  """
229
  _CleanDirectory(constants.QUEUE_DIR, exclude=[constants.JOB_QUEUE_LOCK_FILE])
230
  _CleanDirectory(constants.JOB_QUEUE_ARCHIVE_DIR)
231

    
232

    
233
def GetMasterInfo():
234
  """Returns master information.
235

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

239
  @rtype: tuple
240
  @return: master_netdev, master_ip, master_name, primary_ip_family,
241
    master_netmask
242
  @raise RPCFail: in case of errors
243

244
  """
245
  try:
246
    cfg = _GetConfig()
247
    master_netdev = cfg.GetMasterNetdev()
248
    master_ip = cfg.GetMasterIP()
249
    master_netmask = cfg.GetMasterNetmask()
250
    master_node = cfg.GetMasterNode()
251
    primary_ip_family = cfg.GetPrimaryIPFamily()
252
  except errors.ConfigurationError, err:
253
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
254
  return (master_netdev, master_ip, master_node, primary_ip_family,
255
      master_netmask)
256

    
257

    
258
def RunLocalHooks(hook_opcode, hooks_path, env_builder_fn):
259
  """Decorator that runs hooks before and after the decorated function.
260

261
  @type hook_opcode: string
262
  @param hook_opcode: opcode of the hook
263
  @type hooks_path: string
264
  @param hooks_path: path of the hooks
265
  @type env_builder_fn: function
266
  @param env_builder_fn: function that returns a dictionary containing the
267
    environment variables for the hooks. Will get all the parameters of the
268
    decorated function.
269
  @raise RPCFail: in case of pre-hook failure
270

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

    
277
      env_fn = compat.partial(env_builder_fn, *args, **kwargs)
278

    
279
      cfg = _GetConfig()
280
      hr = HooksRunner()
281
      hm = mcpu.HooksMaster(hook_opcode, hooks_path, nodes, hr.RunLocalHooks,
282
                            None, env_fn, logging.warning, cfg.GetClusterName(),
283
                            cfg.GetMasterNode())
284

    
285
      hm.RunPhase(constants.HOOKS_PHASE_PRE)
286
      result = fn(*args, **kwargs)
287
      hm.RunPhase(constants.HOOKS_PHASE_POST)
288

    
289
      return result
290
    return wrapper
291
  return decorator
292

    
293

    
294
def _BuildMasterIpEnv(master_params, use_external_mip_script=None):
295
  """Builds environment variables for master IP hooks.
296

297
  @type master_params: L{objects.MasterNetworkParameters}
298
  @param master_params: network parameters of the master
299
  @type use_external_mip_script: boolean
300
  @param use_external_mip_script: whether to use an external master IP
301
    address setup script (unused, but necessary per the implementation of the
302
    _RunLocalHooks decorator)
303

304
  """
305
  # pylint: disable=W0613
306
  ver = netutils.IPAddress.GetVersionFromAddressFamily(master_params.ip_family)
307
  env = {
308
    "MASTER_NETDEV": master_params.netdev,
309
    "MASTER_IP": master_params.ip,
310
    "MASTER_NETMASK": str(master_params.netmask),
311
    "CLUSTER_IP_VERSION": str(ver),
312
  }
313

    
314
  return env
315

    
316

    
317
def _RunMasterSetupScript(master_params, action, use_external_mip_script):
318
  """Execute the master IP address setup script.
319

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

331
  """
332
  env = _BuildMasterIpEnv(master_params)
333

    
334
  if use_external_mip_script:
335
    setup_script = constants.EXTERNAL_MASTER_SETUP_SCRIPT
336
  else:
337
    setup_script = constants.DEFAULT_MASTER_SETUP_SCRIPT
338

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

    
341
  if result.failed:
342
    _Fail("Failed to %s the master IP. Script return value: %s" %
343
          (action, result.exit_code), log=True)
344

    
345

    
346
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNUP, "master-ip-turnup",
347
               _BuildMasterIpEnv)
348
def ActivateMasterIp(master_params, use_external_mip_script):
349
  """Activate the IP address of the master daemon.
350

351
  @type master_params: L{objects.MasterNetworkParameters}
352
  @param master_params: network parameters of the master
353
  @type use_external_mip_script: boolean
354
  @param use_external_mip_script: whether to use an external master IP
355
    address setup script
356
  @raise RPCFail: in case of errors during the IP startup
357

358
  """
359
  _RunMasterSetupScript(master_params, _MASTER_START,
360
                        use_external_mip_script)
361

    
362

    
363
def StartMasterDaemons(no_voting):
364
  """Activate local node as master node.
365

366
  The function will start the master daemons (ganeti-masterd and ganeti-rapi).
367

368
  @type no_voting: boolean
369
  @param no_voting: whether to start ganeti-masterd without a node vote
370
      but still non-interactively
371
  @rtype: None
372

373
  """
374

    
375
  if no_voting:
376
    masterd_args = "--no-voting --yes-do-it"
377
  else:
378
    masterd_args = ""
379

    
380
  env = {
381
    "EXTRA_MASTERD_ARGS": masterd_args,
382
    }
383

    
384
  result = utils.RunCmd([constants.DAEMON_UTIL, "start-master"], env=env)
385
  if result.failed:
386
    msg = "Can't start Ganeti master: %s" % result.output
387
    logging.error(msg)
388
    _Fail(msg)
389

    
390

    
391
@RunLocalHooks(constants.FAKE_OP_MASTER_TURNDOWN, "master-ip-turndown",
392
               _BuildMasterIpEnv)
393
def DeactivateMasterIp(master_params, use_external_mip_script):
394
  """Deactivate the master IP on this node.
395

396
  @type master_params: L{objects.MasterNetworkParameters}
397
  @param master_params: network parameters of the master
398
  @type use_external_mip_script: boolean
399
  @param use_external_mip_script: whether to use an external master IP
400
    address setup script
401
  @raise RPCFail: in case of errors during the IP turndown
402

403
  """
404
  _RunMasterSetupScript(master_params, _MASTER_STOP,
405
                        use_external_mip_script)
406

    
407

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

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

413
  @rtype: None
414

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

    
419
  result = utils.RunCmd([constants.DAEMON_UTIL, "stop-master"])
420
  if result.failed:
421
    logging.error("Could not stop Ganeti master, command %s had exitcode %s"
422
                  " and error %s",
423
                  result.cmd, result.exit_code, result.output)
424

    
425

    
426
def ChangeMasterNetmask(old_netmask, netmask, master_ip, master_netdev):
427
  """Change the netmask of the master IP.
428

429
  @param old_netmask: the old value of the netmask
430
  @param netmask: the new value of the netmask
431
  @param master_ip: the master IP
432
  @param master_netdev: the master network device
433

434
  """
435
  if old_netmask == netmask:
436
    return
437

    
438
  if not netutils.IPAddress.Own(master_ip):
439
    _Fail("The master IP address is not up, not attempting to change its"
440
          " netmask")
441

    
442
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "add",
443
                         "%s/%s" % (master_ip, netmask),
444
                         "dev", master_netdev, "label",
445
                         "%s:0" % master_netdev])
446
  if result.failed:
447
    _Fail("Could not set the new netmask on the master IP address")
448

    
449
  result = utils.RunCmd([constants.IP_COMMAND_PATH, "address", "del",
450
                         "%s/%s" % (master_ip, old_netmask),
451
                         "dev", master_netdev, "label",
452
                         "%s:0" % master_netdev])
453
  if result.failed:
454
    _Fail("Could not bring down the master IP address with the old netmask")
455

    
456

    
457
def EtcHostsModify(mode, host, ip):
458
  """Modify a host entry in /etc/hosts.
459

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

464
  """
465
  if mode == constants.ETC_HOSTS_ADD:
466
    if not ip:
467
      RPCFail("Mode 'add' needs 'ip' parameter, but parameter not"
468
              " present")
469
    utils.AddHostToEtcHosts(host, ip)
470
  elif mode == constants.ETC_HOSTS_REMOVE:
471
    if ip:
472
      RPCFail("Mode 'remove' does not allow 'ip' parameter, but"
473
              " parameter is present")
474
    utils.RemoveHostFromEtcHosts(host)
475
  else:
476
    RPCFail("Mode not supported")
477

    
478

    
479
def LeaveCluster(modify_ssh_setup):
480
  """Cleans up and remove the current node.
481

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

485
  If processing is successful, then it raises an
486
  L{errors.QuitGanetiException} which is used as a special case to
487
  shutdown the node daemon.
488

489
  @param modify_ssh_setup: boolean
490

491
  """
492
  _CleanDirectory(constants.DATA_DIR)
493
  _CleanDirectory(constants.CRYPTO_KEYS_DIR)
494
  JobQueuePurge()
495

    
496
  if modify_ssh_setup:
497
    try:
498
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
499

    
500
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
501

    
502
      utils.RemoveFile(priv_key)
503
      utils.RemoveFile(pub_key)
504
    except errors.OpExecError:
505
      logging.exception("Error while processing ssh files")
506

    
507
  try:
508
    utils.RemoveFile(constants.CONFD_HMAC_KEY)
509
    utils.RemoveFile(constants.RAPI_CERT_FILE)
510
    utils.RemoveFile(constants.SPICE_CERT_FILE)
511
    utils.RemoveFile(constants.SPICE_CACERT_FILE)
512
    utils.RemoveFile(constants.NODED_CERT_FILE)
513
  except: # pylint: disable=W0702
514
    logging.exception("Error while removing cluster secrets")
515

    
516
  result = utils.RunCmd([constants.DAEMON_UTIL, "stop", constants.CONFD])
517
  if result.failed:
518
    logging.error("Command %s failed with exitcode %s and error %s",
519
                  result.cmd, result.exit_code, result.output)
520

    
521
  # Raise a custom exception (handled in ganeti-noded)
522
  raise errors.QuitGanetiException(True, "Shutdown scheduled")
523

    
524

    
525
def _GetVgInfo(name):
526
  """Retrieves information about a LVM volume group.
527

528
  """
529
  # TODO: GetVGInfo supports returning information for multiple VGs at once
530
  vginfo = bdev.LogicalVolume.GetVGInfo([name])
531
  if vginfo:
532
    vg_free = int(round(vginfo[0][0], 0))
533
    vg_size = int(round(vginfo[0][1], 0))
534
  else:
535
    vg_free = 0
536
    vg_size = 0
537

    
538
  return {
539
    "name": name,
540
    "vg_free": vg_free,
541
    "vg_size": vg_size,
542
    }
543

    
544

    
545
def _GetHvInfo(name):
546
  """Retrieves node information from a hypervisor.
547

548
  The information returned depends on the hypervisor. Common items:
549

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

557
  """
558
  return hypervisor.GetHypervisor(name).GetNodeInfo()
559

    
560

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

564
  @rtype: None or dict
565

566
  """
567
  if names is None:
568
    return None
569
  else:
570
    return map(fn, names)
571

    
572

    
573
def GetNodeInfo(vg_names, hv_names):
574
  """Gives back a hash with different information about the node.
575

576
  @type vg_names: list of string
577
  @param vg_names: Names of the volume groups to ask for disk space information
578
  @type hv_names: list of string
579
  @param hv_names: Names of the hypervisors to ask for node information
580
  @rtype: tuple; (string, None/dict, None/dict)
581
  @return: Tuple containing boot ID, volume group information and hypervisor
582
    information
583

584
  """
585
  bootid = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
586
  vg_info = _GetNamedNodeInfo(vg_names, _GetVgInfo)
587
  hv_info = _GetNamedNodeInfo(hv_names, _GetHvInfo)
588

    
589
  return (bootid, vg_info, hv_info)
590

    
591

    
592
def VerifyNode(what, cluster_name):
593
  """Verify the status of the local node.
594

595
  Based on the input L{what} parameter, various checks are done on the
596
  local node.
597

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

601
  If the I{nodelist} key is present, we check that we have
602
  connectivity via ssh with the target nodes (and check the hostname
603
  report).
604

605
  If the I{node-net-test} key is present, we check that we have
606
  connectivity to the given nodes via both primary IP and, if
607
  applicable, secondary IPs.
608

609
  @type what: C{dict}
610
  @param what: a dictionary of things to check:
611
      - filelist: list of files for which to compute checksums
612
      - nodelist: list of nodes we should check ssh communication with
613
      - node-net-test: list of nodes we should check node daemon port
614
        connectivity with
615
      - hypervisor: list with hypervisors to run the verify for
616
  @rtype: dict
617
  @return: a dictionary with the same keys as the input dict, and
618
      values representing the result of the checks
619

620
  """
621
  result = {}
622
  my_name = netutils.Hostname.GetSysName()
623
  port = netutils.GetDaemonPort(constants.NODED)
624
  vm_capable = my_name not in what.get(constants.NV_VMNODES, [])
625

    
626
  if constants.NV_HYPERVISOR in what and vm_capable:
627
    result[constants.NV_HYPERVISOR] = tmp = {}
628
    for hv_name in what[constants.NV_HYPERVISOR]:
629
      try:
630
        val = hypervisor.GetHypervisor(hv_name).Verify()
631
      except errors.HypervisorError, err:
632
        val = "Error while checking hypervisor: %s" % str(err)
633
      tmp[hv_name] = val
634

    
635
  if constants.NV_HVPARAMS in what and vm_capable:
636
    result[constants.NV_HVPARAMS] = tmp = []
637
    for source, hv_name, hvparms in what[constants.NV_HVPARAMS]:
638
      try:
639
        logging.info("Validating hv %s, %s", hv_name, hvparms)
640
        hypervisor.GetHypervisor(hv_name).ValidateParameters(hvparms)
641
      except errors.HypervisorError, err:
642
        tmp.append((source, hv_name, str(err)))
643

    
644
  if constants.NV_FILELIST in what:
645
    result[constants.NV_FILELIST] = utils.FingerprintFiles(
646
      what[constants.NV_FILELIST])
647

    
648
  if constants.NV_NODELIST in what:
649
    (nodes, bynode) = what[constants.NV_NODELIST]
650

    
651
    # Add nodes from other groups (different for each node)
652
    try:
653
      nodes.extend(bynode[my_name])
654
    except KeyError:
655
      pass
656

    
657
    # Use a random order
658
    random.shuffle(nodes)
659

    
660
    # Try to contact all nodes
661
    val = {}
662
    for node in nodes:
663
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
664
      if not success:
665
        val[node] = message
666

    
667
    result[constants.NV_NODELIST] = val
668

    
669
  if constants.NV_NODENETTEST in what:
670
    result[constants.NV_NODENETTEST] = tmp = {}
671
    my_pip = my_sip = None
672
    for name, pip, sip in what[constants.NV_NODENETTEST]:
673
      if name == my_name:
674
        my_pip = pip
675
        my_sip = sip
676
        break
677
    if not my_pip:
678
      tmp[my_name] = ("Can't find my own primary/secondary IP"
679
                      " in the node list")
680
    else:
681
      for name, pip, sip in what[constants.NV_NODENETTEST]:
682
        fail = []
683
        if not netutils.TcpPing(pip, port, source=my_pip):
684
          fail.append("primary")
685
        if sip != pip:
686
          if not netutils.TcpPing(sip, port, source=my_sip):
687
            fail.append("secondary")
688
        if fail:
689
          tmp[name] = ("failure using the %s interface(s)" %
690
                       " and ".join(fail))
691

    
692
  if constants.NV_MASTERIP in what:
693
    # FIXME: add checks on incoming data structures (here and in the
694
    # rest of the function)
695
    master_name, master_ip = what[constants.NV_MASTERIP]
696
    if master_name == my_name:
697
      source = constants.IP4_ADDRESS_LOCALHOST
698
    else:
699
      source = None
700
    result[constants.NV_MASTERIP] = netutils.TcpPing(master_ip, port,
701
                                                  source=source)
702

    
703
  if constants.NV_USERSCRIPTS in what:
704
    result[constants.NV_USERSCRIPTS] = \
705
      [script for script in what[constants.NV_USERSCRIPTS]
706
       if not (os.path.exists(script) and os.access(script, os.X_OK))]
707

    
708
  if constants.NV_OOB_PATHS in what:
709
    result[constants.NV_OOB_PATHS] = tmp = []
710
    for path in what[constants.NV_OOB_PATHS]:
711
      try:
712
        st = os.stat(path)
713
      except OSError, err:
714
        tmp.append("error stating out of band helper: %s" % err)
715
      else:
716
        if stat.S_ISREG(st.st_mode):
717
          if stat.S_IMODE(st.st_mode) & stat.S_IXUSR:
718
            tmp.append(None)
719
          else:
720
            tmp.append("out of band helper %s is not executable" % path)
721
        else:
722
          tmp.append("out of band helper %s is not a file" % path)
723

    
724
  if constants.NV_LVLIST in what and vm_capable:
725
    try:
726
      val = GetVolumeList(utils.ListVolumeGroups().keys())
727
    except RPCFail, err:
728
      val = str(err)
729
    result[constants.NV_LVLIST] = val
730

    
731
  if constants.NV_INSTANCELIST in what and vm_capable:
732
    # GetInstanceList can fail
733
    try:
734
      val = GetInstanceList(what[constants.NV_INSTANCELIST])
735
    except RPCFail, err:
736
      val = str(err)
737
    result[constants.NV_INSTANCELIST] = val
738

    
739
  if constants.NV_VGLIST in what and vm_capable:
740
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
741

    
742
  if constants.NV_PVLIST in what and vm_capable:
743
    result[constants.NV_PVLIST] = \
744
      bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
745
                                   filter_allocatable=False)
746

    
747
  if constants.NV_VERSION in what:
748
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
749
                                    constants.RELEASE_VERSION)
750

    
751
  if constants.NV_HVINFO in what and vm_capable:
752
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
753
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
754

    
755
  if constants.NV_DRBDLIST in what and vm_capable:
756
    try:
757
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
758
    except errors.BlockDeviceError, err:
759
      logging.warning("Can't get used minors list", exc_info=True)
760
      used_minors = str(err)
761
    result[constants.NV_DRBDLIST] = used_minors
762

    
763
  if constants.NV_DRBDHELPER in what and vm_capable:
764
    status = True
765
    try:
766
      payload = bdev.BaseDRBD.GetUsermodeHelper()
767
    except errors.BlockDeviceError, err:
768
      logging.error("Can't get DRBD usermode helper: %s", str(err))
769
      status = False
770
      payload = str(err)
771
    result[constants.NV_DRBDHELPER] = (status, payload)
772

    
773
  if constants.NV_NODESETUP in what:
774
    result[constants.NV_NODESETUP] = tmpr = []
775
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
776
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
777
                  " under /sys, missing required directories /sys/block"
778
                  " and /sys/class/net")
779
    if (not os.path.isdir("/proc/sys") or
780
        not os.path.isfile("/proc/sysrq-trigger")):
781
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
782
                  " under /proc, missing required directory /proc/sys and"
783
                  " the file /proc/sysrq-trigger")
784

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

    
788
  if constants.NV_OSLIST in what and vm_capable:
789
    result[constants.NV_OSLIST] = DiagnoseOS()
790

    
791
  if constants.NV_BRIDGES in what and vm_capable:
792
    result[constants.NV_BRIDGES] = [bridge
793
                                    for bridge in what[constants.NV_BRIDGES]
794
                                    if not utils.BridgeExists(bridge)]
795
  return result
796

    
797

    
798
def GetBlockDevSizes(devices):
799
  """Return the size of the given block devices
800

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

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

810
  """
811
  DEV_PREFIX = "/dev/"
812
  blockdevs = {}
813

    
814
  for devpath in devices:
815
    if not utils.IsBelowDir(DEV_PREFIX, devpath):
816
      continue
817

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

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

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

    
835

    
836
def GetVolumeList(vg_names):
837
  """Compute list of logical volumes and their size.
838

839
  @type vg_names: list
840
  @param vg_names: the volume groups whose LVs we should list, or
841
      empty for all volume groups
842
  @rtype: dict
843
  @return:
844
      dictionary of all partions (key) with value being a tuple of
845
      their size (in MiB), inactive and online status::
846

847
        {'xenvg/test1': ('20.06', True, True)}
848

849
      in case of errors, a string is returned with the error
850
      details.
851

852
  """
853
  lvs = {}
854
  sep = "|"
855
  if not vg_names:
856
    vg_names = []
857
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
858
                         "--separator=%s" % sep,
859
                         "-ovg_name,lv_name,lv_size,lv_attr"] + vg_names)
860
  if result.failed:
861
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
862

    
863
  for line in result.stdout.splitlines():
864
    line = line.strip()
865
    match = _LVSLINE_REGEX.match(line)
866
    if not match:
867
      logging.error("Invalid line returned from lvs output: '%s'", line)
868
      continue
869
    vg_name, name, size, attr = match.groups()
870
    inactive = attr[4] == "-"
871
    online = attr[5] == "o"
872
    virtual = attr[0] == "v"
873
    if virtual:
874
      # we don't want to report such volumes as existing, since they
875
      # don't really hold data
876
      continue
877
    lvs[vg_name + "/" + name] = (size, inactive, online)
878

    
879
  return lvs
880

    
881

    
882
def ListVolumeGroups():
883
  """List the volume groups and their size.
884

885
  @rtype: dict
886
  @return: dictionary with keys volume name and values the
887
      size of the volume
888

889
  """
890
  return utils.ListVolumeGroups()
891

    
892

    
893
def NodeVolumes():
894
  """List all volumes on this node.
895

896
  @rtype: list
897
  @return:
898
    A list of dictionaries, each having four keys:
899
      - name: the logical volume name,
900
      - size: the size of the logical volume
901
      - dev: the physical device on which the LV lives
902
      - vg: the volume group to which it belongs
903

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

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

911
  """
912
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
913
                         "--separator=|",
914
                         "--options=lv_name,lv_size,devices,vg_name"])
915
  if result.failed:
916
    _Fail("Failed to list logical volumes, lvs output: %s",
917
          result.output)
918

    
919
  def parse_dev(dev):
920
    return dev.split("(")[0]
921

    
922
  def handle_dev(dev):
923
    return [parse_dev(x) for x in dev.split(",")]
924

    
925
  def map_line(line):
926
    line = [v.strip() for v in line]
927
    return [{"name": line[0], "size": line[1],
928
             "dev": dev, "vg": line[3]} for dev in handle_dev(line[2])]
929

    
930
  all_devs = []
931
  for line in result.stdout.splitlines():
932
    if line.count("|") >= 3:
933
      all_devs.extend(map_line(line.split("|")))
934
    else:
935
      logging.warning("Strange line in the output from lvs: '%s'", line)
936
  return all_devs
937

    
938

    
939
def BridgesExist(bridges_list):
940
  """Check if a list of bridges exist on the current node.
941

942
  @rtype: boolean
943
  @return: C{True} if all of them exist, C{False} otherwise
944

945
  """
946
  missing = []
947
  for bridge in bridges_list:
948
    if not utils.BridgeExists(bridge):
949
      missing.append(bridge)
950

    
951
  if missing:
952
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
953

    
954

    
955
def GetInstanceList(hypervisor_list):
956
  """Provides a list of instances.
957

958
  @type hypervisor_list: list
959
  @param hypervisor_list: the list of hypervisors to query information
960

961
  @rtype: list
962
  @return: a list of all running instances on the current node
963
    - instance1.example.com
964
    - instance2.example.com
965

966
  """
967
  results = []
968
  for hname in hypervisor_list:
969
    try:
970
      names = hypervisor.GetHypervisor(hname).ListInstances()
971
      results.extend(names)
972
    except errors.HypervisorError, err:
973
      _Fail("Error enumerating instances (hypervisor %s): %s",
974
            hname, err, exc=True)
975

    
976
  return results
977

    
978

    
979
def GetInstanceInfo(instance, hname):
980
  """Gives back the information about an instance as a dictionary.
981

982
  @type instance: string
983
  @param instance: the instance name
984
  @type hname: string
985
  @param hname: the hypervisor type of the instance
986

987
  @rtype: dict
988
  @return: dictionary with the following keys:
989
      - memory: memory size of instance (int)
990
      - state: xen state of instance (string)
991
      - time: cpu time of instance (float)
992

993
  """
994
  output = {}
995

    
996
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
997
  if iinfo is not None:
998
    output["memory"] = iinfo[2]
999
    output["state"] = iinfo[4]
1000
    output["time"] = iinfo[5]
1001

    
1002
  return output
1003

    
1004

    
1005
def GetInstanceMigratable(instance):
1006
  """Gives whether an instance can be migrated.
1007

1008
  @type instance: L{objects.Instance}
1009
  @param instance: object representing the instance to be checked.
1010

1011
  @rtype: tuple
1012
  @return: tuple of (result, description) where:
1013
      - result: whether the instance can be migrated or not
1014
      - description: a description of the issue, if relevant
1015

1016
  """
1017
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1018
  iname = instance.name
1019
  if iname not in hyper.ListInstances():
1020
    _Fail("Instance %s is not running", iname)
1021

    
1022
  for idx in range(len(instance.disks)):
1023
    link_name = _GetBlockDevSymlinkPath(iname, idx)
1024
    if not os.path.islink(link_name):
1025
      logging.warning("Instance %s is missing symlink %s for disk %d",
1026
                      iname, link_name, idx)
1027

    
1028

    
1029
def GetAllInstancesInfo(hypervisor_list):
1030
  """Gather data about all instances.
1031

1032
  This is the equivalent of L{GetInstanceInfo}, except that it
1033
  computes data for all instances at once, thus being faster if one
1034
  needs data about more than one instance.
1035

1036
  @type hypervisor_list: list
1037
  @param hypervisor_list: list of hypervisors to query for instance data
1038

1039
  @rtype: dict
1040
  @return: dictionary of instance: data, with data having the following keys:
1041
      - memory: memory size of instance (int)
1042
      - state: xen state of instance (string)
1043
      - time: cpu time of instance (float)
1044
      - vcpus: the number of vcpus
1045

1046
  """
1047
  output = {}
1048

    
1049
  for hname in hypervisor_list:
1050
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
1051
    if iinfo:
1052
      for name, _, memory, vcpus, state, times in iinfo:
1053
        value = {
1054
          "memory": memory,
1055
          "vcpus": vcpus,
1056
          "state": state,
1057
          "time": times,
1058
          }
1059
        if name in output:
1060
          # we only check static parameters, like memory and vcpus,
1061
          # and not state and time which can change between the
1062
          # invocations of the different hypervisors
1063
          for key in "memory", "vcpus":
1064
            if value[key] != output[name][key]:
1065
              _Fail("Instance %s is running twice"
1066
                    " with different parameters", name)
1067
        output[name] = value
1068

    
1069
  return output
1070

    
1071

    
1072
def _InstanceLogName(kind, os_name, instance, component):
1073
  """Compute the OS log filename for a given instance and operation.
1074

1075
  The instance name and os name are passed in as strings since not all
1076
  operations have these as part of an instance object.
1077

1078
  @type kind: string
1079
  @param kind: the operation type (e.g. add, import, etc.)
1080
  @type os_name: string
1081
  @param os_name: the os name
1082
  @type instance: string
1083
  @param instance: the name of the instance being imported/added/etc.
1084
  @type component: string or None
1085
  @param component: the name of the component of the instance being
1086
      transferred
1087

1088
  """
1089
  # TODO: Use tempfile.mkstemp to create unique filename
1090
  if component:
1091
    assert "/" not in component
1092
    c_msg = "-%s" % component
1093
  else:
1094
    c_msg = ""
1095
  base = ("%s-%s-%s%s-%s.log" %
1096
          (kind, os_name, instance, c_msg, utils.TimestampForFilename()))
1097
  return utils.PathJoin(constants.LOG_OS_DIR, base)
1098

    
1099

    
1100
def InstanceOsAdd(instance, reinstall, debug):
1101
  """Add an OS to an instance.
1102

1103
  @type instance: L{objects.Instance}
1104
  @param instance: Instance whose OS is to be installed
1105
  @type reinstall: boolean
1106
  @param reinstall: whether this is an instance reinstall
1107
  @type debug: integer
1108
  @param debug: debug level, passed to the OS scripts
1109
  @rtype: None
1110

1111
  """
1112
  inst_os = OSFromDisk(instance.os)
1113

    
1114
  create_env = OSEnvironment(instance, inst_os, debug)
1115
  if reinstall:
1116
    create_env["INSTANCE_REINSTALL"] = "1"
1117

    
1118
  logfile = _InstanceLogName("add", instance.os, instance.name, None)
1119

    
1120
  result = utils.RunCmd([inst_os.create_script], env=create_env,
1121
                        cwd=inst_os.path, output=logfile, reset_env=True)
1122
  if result.failed:
1123
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
1124
                  " output: %s", result.cmd, result.fail_reason, logfile,
1125
                  result.output)
1126
    lines = [utils.SafeEncode(val)
1127
             for val in utils.TailFile(logfile, lines=20)]
1128
    _Fail("OS create script failed (%s), last lines in the"
1129
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1130

    
1131

    
1132
def RunRenameInstance(instance, old_name, debug):
1133
  """Run the OS rename script for an instance.
1134

1135
  @type instance: L{objects.Instance}
1136
  @param instance: Instance whose OS is to be installed
1137
  @type old_name: string
1138
  @param old_name: previous instance name
1139
  @type debug: integer
1140
  @param debug: debug level, passed to the OS scripts
1141
  @rtype: boolean
1142
  @return: the success of the operation
1143

1144
  """
1145
  inst_os = OSFromDisk(instance.os)
1146

    
1147
  rename_env = OSEnvironment(instance, inst_os, debug)
1148
  rename_env["OLD_INSTANCE_NAME"] = old_name
1149

    
1150
  logfile = _InstanceLogName("rename", instance.os,
1151
                             "%s-%s" % (old_name, instance.name), None)
1152

    
1153
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
1154
                        cwd=inst_os.path, output=logfile, reset_env=True)
1155

    
1156
  if result.failed:
1157
    logging.error("os create command '%s' returned error: %s output: %s",
1158
                  result.cmd, result.fail_reason, result.output)
1159
    lines = [utils.SafeEncode(val)
1160
             for val in utils.TailFile(logfile, lines=20)]
1161
    _Fail("OS rename script failed (%s), last lines in the"
1162
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
1163

    
1164

    
1165
def _GetBlockDevSymlinkPath(instance_name, idx):
1166
  return utils.PathJoin(constants.DISK_LINKS_DIR, "%s%s%d" %
1167
                        (instance_name, constants.DISK_SEPARATOR, idx))
1168

    
1169

    
1170
def _SymlinkBlockDev(instance_name, device_path, idx):
1171
  """Set up symlinks to a instance's block device.
1172

1173
  This is an auxiliary function run when an instance is start (on the primary
1174
  node) or when an instance is migrated (on the target node).
1175

1176

1177
  @param instance_name: the name of the target instance
1178
  @param device_path: path of the physical block device, on the node
1179
  @param idx: the disk index
1180
  @return: absolute path to the disk's symlink
1181

1182
  """
1183
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1184
  try:
1185
    os.symlink(device_path, link_name)
1186
  except OSError, err:
1187
    if err.errno == errno.EEXIST:
1188
      if (not os.path.islink(link_name) or
1189
          os.readlink(link_name) != device_path):
1190
        os.remove(link_name)
1191
        os.symlink(device_path, link_name)
1192
    else:
1193
      raise
1194

    
1195
  return link_name
1196

    
1197

    
1198
def _RemoveBlockDevLinks(instance_name, disks):
1199
  """Remove the block device symlinks belonging to the given instance.
1200

1201
  """
1202
  for idx, _ in enumerate(disks):
1203
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
1204
    if os.path.islink(link_name):
1205
      try:
1206
        os.remove(link_name)
1207
      except OSError:
1208
        logging.exception("Can't remove symlink '%s'", link_name)
1209

    
1210

    
1211
def _GatherAndLinkBlockDevs(instance):
1212
  """Set up an instance's block device(s).
1213

1214
  This is run on the primary node at instance startup. The block
1215
  devices must be already assembled.
1216

1217
  @type instance: L{objects.Instance}
1218
  @param instance: the instance whose disks we shoul assemble
1219
  @rtype: list
1220
  @return: list of (disk_object, device_path)
1221

1222
  """
1223
  block_devices = []
1224
  for idx, disk in enumerate(instance.disks):
1225
    device = _RecursiveFindBD(disk)
1226
    if device is None:
1227
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
1228
                                    str(disk))
1229
    device.Open()
1230
    try:
1231
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
1232
    except OSError, e:
1233
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
1234
                                    e.strerror)
1235

    
1236
    block_devices.append((disk, link_name))
1237

    
1238
  return block_devices
1239

    
1240

    
1241
def StartInstance(instance, startup_paused):
1242
  """Start an instance.
1243

1244
  @type instance: L{objects.Instance}
1245
  @param instance: the instance object
1246
  @type startup_paused: bool
1247
  @param instance: pause instance at startup?
1248
  @rtype: None
1249

1250
  """
1251
  running_instances = GetInstanceList([instance.hypervisor])
1252

    
1253
  if instance.name in running_instances:
1254
    logging.info("Instance %s already running, not starting", instance.name)
1255
    return
1256

    
1257
  try:
1258
    block_devices = _GatherAndLinkBlockDevs(instance)
1259
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
1260
    hyper.StartInstance(instance, block_devices, startup_paused)
1261
  except errors.BlockDeviceError, err:
1262
    _Fail("Block device error: %s", err, exc=True)
1263
  except errors.HypervisorError, err:
1264
    _RemoveBlockDevLinks(instance.name, instance.disks)
1265
    _Fail("Hypervisor error: %s", err, exc=True)
1266

    
1267

    
1268
def InstanceShutdown(instance, timeout):
1269
  """Shut an instance down.
1270

1271
  @note: this functions uses polling with a hardcoded timeout.
1272

1273
  @type instance: L{objects.Instance}
1274
  @param instance: the instance object
1275
  @type timeout: integer
1276
  @param timeout: maximum timeout for soft shutdown
1277
  @rtype: None
1278

1279
  """
1280
  hv_name = instance.hypervisor
1281
  hyper = hypervisor.GetHypervisor(hv_name)
1282
  iname = instance.name
1283

    
1284
  if instance.name not in hyper.ListInstances():
1285
    logging.info("Instance %s not running, doing nothing", iname)
1286
    return
1287

    
1288
  class _TryShutdown:
1289
    def __init__(self):
1290
      self.tried_once = False
1291

    
1292
    def __call__(self):
1293
      if iname not in hyper.ListInstances():
1294
        return
1295

    
1296
      try:
1297
        hyper.StopInstance(instance, retry=self.tried_once)
1298
      except errors.HypervisorError, err:
1299
        if iname not in hyper.ListInstances():
1300
          # if the instance is no longer existing, consider this a
1301
          # success and go to cleanup
1302
          return
1303

    
1304
        _Fail("Failed to stop instance %s: %s", iname, err)
1305

    
1306
      self.tried_once = True
1307

    
1308
      raise utils.RetryAgain()
1309

    
1310
  try:
1311
    utils.Retry(_TryShutdown(), 5, timeout)
1312
  except utils.RetryTimeout:
1313
    # the shutdown did not succeed
1314
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1315

    
1316
    try:
1317
      hyper.StopInstance(instance, force=True)
1318
    except errors.HypervisorError, err:
1319
      if iname in hyper.ListInstances():
1320
        # only raise an error if the instance still exists, otherwise
1321
        # the error could simply be "instance ... unknown"!
1322
        _Fail("Failed to force stop instance %s: %s", iname, err)
1323

    
1324
    time.sleep(1)
1325

    
1326
    if iname in hyper.ListInstances():
1327
      _Fail("Could not shutdown instance %s even by destroy", iname)
1328

    
1329
  try:
1330
    hyper.CleanupInstance(instance.name)
1331
  except errors.HypervisorError, err:
1332
    logging.warning("Failed to execute post-shutdown cleanup step: %s", err)
1333

    
1334
  _RemoveBlockDevLinks(iname, instance.disks)
1335

    
1336

    
1337
def InstanceReboot(instance, reboot_type, shutdown_timeout):
1338
  """Reboot an instance.
1339

1340
  @type instance: L{objects.Instance}
1341
  @param instance: the instance object to reboot
1342
  @type reboot_type: str
1343
  @param reboot_type: the type of reboot, one the following
1344
    constants:
1345
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1346
        instance OS, do not recreate the VM
1347
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1348
        restart the VM (at the hypervisor level)
1349
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1350
        not accepted here, since that mode is handled differently, in
1351
        cmdlib, and translates into full stop and start of the
1352
        instance (instead of a call_instance_reboot RPC)
1353
  @type shutdown_timeout: integer
1354
  @param shutdown_timeout: maximum timeout for soft shutdown
1355
  @rtype: None
1356

1357
  """
1358
  running_instances = GetInstanceList([instance.hypervisor])
1359

    
1360
  if instance.name not in running_instances:
1361
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1362

    
1363
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1364
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1365
    try:
1366
      hyper.RebootInstance(instance)
1367
    except errors.HypervisorError, err:
1368
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1369
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1370
    try:
1371
      InstanceShutdown(instance, shutdown_timeout)
1372
      return StartInstance(instance, False)
1373
    except errors.HypervisorError, err:
1374
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1375
  else:
1376
    _Fail("Invalid reboot_type received: %s", reboot_type)
1377

    
1378

    
1379
def InstanceBalloonMemory(instance, memory):
1380
  """Resize an instance's memory.
1381

1382
  @type instance: L{objects.Instance}
1383
  @param instance: the instance object
1384
  @type memory: int
1385
  @param memory: new memory amount in MB
1386
  @rtype: None
1387

1388
  """
1389
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1390
  running = hyper.ListInstances()
1391
  if instance.name not in running:
1392
    logging.info("Instance %s is not running, cannot balloon", instance.name)
1393
    return
1394
  try:
1395
    hyper.BalloonInstanceMemory(instance, memory)
1396
  except errors.HypervisorError, err:
1397
    _Fail("Failed to balloon instance memory: %s", err, exc=True)
1398

    
1399

    
1400
def MigrationInfo(instance):
1401
  """Gather information about an instance to be migrated.
1402

1403
  @type instance: L{objects.Instance}
1404
  @param instance: the instance definition
1405

1406
  """
1407
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1408
  try:
1409
    info = hyper.MigrationInfo(instance)
1410
  except errors.HypervisorError, err:
1411
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1412
  return info
1413

    
1414

    
1415
def AcceptInstance(instance, info, target):
1416
  """Prepare the node to accept an instance.
1417

1418
  @type instance: L{objects.Instance}
1419
  @param instance: the instance definition
1420
  @type info: string/data (opaque)
1421
  @param info: migration information, from the source node
1422
  @type target: string
1423
  @param target: target host (usually ip), on this node
1424

1425
  """
1426
  # TODO: why is this required only for DTS_EXT_MIRROR?
1427
  if instance.disk_template in constants.DTS_EXT_MIRROR:
1428
    # Create the symlinks, as the disks are not active
1429
    # in any way
1430
    try:
1431
      _GatherAndLinkBlockDevs(instance)
1432
    except errors.BlockDeviceError, err:
1433
      _Fail("Block device error: %s", err, exc=True)
1434

    
1435
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1436
  try:
1437
    hyper.AcceptInstance(instance, info, target)
1438
  except errors.HypervisorError, err:
1439
    if instance.disk_template in constants.DTS_EXT_MIRROR:
1440
      _RemoveBlockDevLinks(instance.name, instance.disks)
1441
    _Fail("Failed to accept instance: %s", err, exc=True)
1442

    
1443

    
1444
def FinalizeMigrationDst(instance, info, success):
1445
  """Finalize any preparation to accept an instance.
1446

1447
  @type instance: L{objects.Instance}
1448
  @param instance: the instance definition
1449
  @type info: string/data (opaque)
1450
  @param info: migration information, from the source node
1451
  @type success: boolean
1452
  @param success: whether the migration was a success or a failure
1453

1454
  """
1455
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1456
  try:
1457
    hyper.FinalizeMigrationDst(instance, info, success)
1458
  except errors.HypervisorError, err:
1459
    _Fail("Failed to finalize migration on the target node: %s", err, exc=True)
1460

    
1461

    
1462
def MigrateInstance(instance, target, live):
1463
  """Migrates an instance to another node.
1464

1465
  @type instance: L{objects.Instance}
1466
  @param instance: the instance definition
1467
  @type target: string
1468
  @param target: the target node name
1469
  @type live: boolean
1470
  @param live: whether the migration should be done live or not (the
1471
      interpretation of this parameter is left to the hypervisor)
1472
  @raise RPCFail: if migration fails for some reason
1473

1474
  """
1475
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1476

    
1477
  try:
1478
    hyper.MigrateInstance(instance, target, live)
1479
  except errors.HypervisorError, err:
1480
    _Fail("Failed to migrate instance: %s", err, exc=True)
1481

    
1482

    
1483
def FinalizeMigrationSource(instance, success, live):
1484
  """Finalize the instance migration on the source node.
1485

1486
  @type instance: L{objects.Instance}
1487
  @param instance: the instance definition of the migrated instance
1488
  @type success: bool
1489
  @param success: whether the migration succeeded or not
1490
  @type live: bool
1491
  @param live: whether the user requested a live migration or not
1492
  @raise RPCFail: If the execution fails for some reason
1493

1494
  """
1495
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1496

    
1497
  try:
1498
    hyper.FinalizeMigrationSource(instance, success, live)
1499
  except Exception, err:  # pylint: disable=W0703
1500
    _Fail("Failed to finalize the migration on the source node: %s", err,
1501
          exc=True)
1502

    
1503

    
1504
def GetMigrationStatus(instance):
1505
  """Get the migration status
1506

1507
  @type instance: L{objects.Instance}
1508
  @param instance: the instance that is being migrated
1509
  @rtype: L{objects.MigrationStatus}
1510
  @return: the status of the current migration (one of
1511
           L{constants.HV_MIGRATION_VALID_STATUSES}), plus any additional
1512
           progress info that can be retrieved from the hypervisor
1513
  @raise RPCFail: If the migration status cannot be retrieved
1514

1515
  """
1516
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1517
  try:
1518
    return hyper.GetMigrationStatus(instance)
1519
  except Exception, err:  # pylint: disable=W0703
1520
    _Fail("Failed to get migration status: %s", err, exc=True)
1521

    
1522
def HotAddDisk(instance, disk, dev_path, seq):
1523
  """Hot add a nic
1524

1525
  """
1526
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1527
  return hyper.HotAddDisk(instance, disk, dev_path, seq)
1528

    
1529
def HotDelDisk(instance, disk, seq):
1530
  """Hot add a nic
1531

1532
  """
1533
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1534
  return hyper.HotDelDisk(instance, disk, seq)
1535

    
1536
def HotAddNic(instance, nic, seq):
1537
  """Hot add a nic
1538

1539
  """
1540
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1541
  return hyper.HotAddNic(instance, nic, seq)
1542

    
1543
def HotDelNic(instance, nic, seq):
1544
  """Hot add a nic
1545

1546
  """
1547
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1548
  return hyper.HotDelNic(instance, nic, seq)
1549

    
1550

    
1551
def BlockdevCreate(disk, size, owner, on_primary, info):
1552
  """Creates a block device for an instance.
1553

1554
  @type disk: L{objects.Disk}
1555
  @param disk: the object describing the disk we should create
1556
  @type size: int
1557
  @param size: the size of the physical underlying device, in MiB
1558
  @type owner: str
1559
  @param owner: the name of the instance for which disk is created,
1560
      used for device cache data
1561
  @type on_primary: boolean
1562
  @param on_primary:  indicates if it is the primary node or not
1563
  @type info: string
1564
  @param info: string that will be sent to the physical device
1565
      creation, used for example to set (LVM) tags on LVs
1566

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

1571
  """
1572
  # TODO: remove the obsolete "size" argument
1573
  # pylint: disable=W0613
1574
  clist = []
1575
  if disk.children:
1576
    for child in disk.children:
1577
      try:
1578
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1579
      except errors.BlockDeviceError, err:
1580
        _Fail("Can't assemble device %s: %s", child, err)
1581
      if on_primary or disk.AssembleOnSecondary():
1582
        # we need the children open in case the device itself has to
1583
        # be assembled
1584
        try:
1585
          # pylint: disable=E1103
1586
          crdev.Open()
1587
        except errors.BlockDeviceError, err:
1588
          _Fail("Can't make child '%s' read-write: %s", child, err)
1589
      clist.append(crdev)
1590

    
1591
  try:
1592
    device = bdev.Create(disk, clist)
1593
  except errors.BlockDeviceError, err:
1594
    _Fail("Can't create block device: %s", err)
1595

    
1596
  if on_primary or disk.AssembleOnSecondary():
1597
    try:
1598
      device.Assemble()
1599
    except errors.BlockDeviceError, err:
1600
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1601
    if on_primary or disk.OpenOnSecondary():
1602
      try:
1603
        device.Open(force=True)
1604
      except errors.BlockDeviceError, err:
1605
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1606
    DevCacheManager.UpdateCache(device.dev_path, owner,
1607
                                on_primary, disk.iv_name)
1608

    
1609
  device.SetInfo(info)
1610

    
1611
  return device.unique_id
1612

    
1613

    
1614
def _WipeDevice(path, offset, size):
1615
  """This function actually wipes the device.
1616

1617
  @param path: The path to the device to wipe
1618
  @param offset: The offset in MiB in the file
1619
  @param size: The size in MiB to write
1620

1621
  """
1622
  cmd = [constants.DD_CMD, "if=/dev/zero", "seek=%d" % offset,
1623
         "bs=%d" % constants.WIPE_BLOCK_SIZE, "oflag=direct", "of=%s" % path,
1624
         "count=%d" % size]
1625
  result = utils.RunCmd(cmd)
1626

    
1627
  if result.failed:
1628
    _Fail("Wipe command '%s' exited with error: %s; output: %s", result.cmd,
1629
          result.fail_reason, result.output)
1630

    
1631

    
1632
def BlockdevWipe(disk, offset, size):
1633
  """Wipes a block device.
1634

1635
  @type disk: L{objects.Disk}
1636
  @param disk: the disk object we want to wipe
1637
  @type offset: int
1638
  @param offset: The offset in MiB in the file
1639
  @type size: int
1640
  @param size: The size in MiB to write
1641

1642
  """
1643
  try:
1644
    rdev = _RecursiveFindBD(disk)
1645
  except errors.BlockDeviceError:
1646
    rdev = None
1647

    
1648
  if not rdev:
1649
    _Fail("Cannot execute wipe for device %s: device not found", disk.iv_name)
1650

    
1651
  # Do cross verify some of the parameters
1652
  if offset > rdev.size:
1653
    _Fail("Offset is bigger than device size")
1654
  if (offset + size) > rdev.size:
1655
    _Fail("The provided offset and size to wipe is bigger than device size")
1656

    
1657
  _WipeDevice(rdev.dev_path, offset, size)
1658

    
1659

    
1660
def BlockdevPauseResumeSync(disks, pause):
1661
  """Pause or resume the sync of the block device.
1662

1663
  @type disks: list of L{objects.Disk}
1664
  @param disks: the disks object we want to pause/resume
1665
  @type pause: bool
1666
  @param pause: Wheater to pause or resume
1667

1668
  """
1669
  success = []
1670
  for disk in disks:
1671
    try:
1672
      rdev = _RecursiveFindBD(disk)
1673
    except errors.BlockDeviceError:
1674
      rdev = None
1675

    
1676
    if not rdev:
1677
      success.append((False, ("Cannot change sync for device %s:"
1678
                              " device not found" % disk.iv_name)))
1679
      continue
1680

    
1681
    result = rdev.PauseResumeSync(pause)
1682

    
1683
    if result:
1684
      success.append((result, None))
1685
    else:
1686
      if pause:
1687
        msg = "Pause"
1688
      else:
1689
        msg = "Resume"
1690
      success.append((result, "%s for device %s failed" % (msg, disk.iv_name)))
1691

    
1692
  return success
1693

    
1694

    
1695
def BlockdevRemove(disk):
1696
  """Remove a block device.
1697

1698
  @note: This is intended to be called recursively.
1699

1700
  @type disk: L{objects.Disk}
1701
  @param disk: the disk object we should remove
1702
  @rtype: boolean
1703
  @return: the success of the operation
1704

1705
  """
1706
  msgs = []
1707
  try:
1708
    rdev = _RecursiveFindBD(disk)
1709
  except errors.BlockDeviceError, err:
1710
    # probably can't attach
1711
    logging.info("Can't attach to device %s in remove", disk)
1712
    rdev = None
1713
  if rdev is not None:
1714
    r_path = rdev.dev_path
1715
    try:
1716
      rdev.Remove()
1717
    except errors.BlockDeviceError, err:
1718
      msgs.append(str(err))
1719
    if not msgs:
1720
      DevCacheManager.RemoveCache(r_path)
1721

    
1722
  if disk.children:
1723
    for child in disk.children:
1724
      try:
1725
        BlockdevRemove(child)
1726
      except RPCFail, err:
1727
        msgs.append(str(err))
1728

    
1729
  if msgs:
1730
    _Fail("; ".join(msgs))
1731

    
1732

    
1733
def _RecursiveAssembleBD(disk, owner, as_primary):
1734
  """Activate a block device for an instance.
1735

1736
  This is run on the primary and secondary nodes for an instance.
1737

1738
  @note: this function is called recursively.
1739

1740
  @type disk: L{objects.Disk}
1741
  @param disk: the disk we try to assemble
1742
  @type owner: str
1743
  @param owner: the name of the instance which owns the disk
1744
  @type as_primary: boolean
1745
  @param as_primary: if we should make the block device
1746
      read/write
1747

1748
  @return: the assembled device or None (in case no device
1749
      was assembled)
1750
  @raise errors.BlockDeviceError: in case there is an error
1751
      during the activation of the children or the device
1752
      itself
1753

1754
  """
1755
  children = []
1756
  if disk.children:
1757
    mcn = disk.ChildrenNeeded()
1758
    if mcn == -1:
1759
      mcn = 0 # max number of Nones allowed
1760
    else:
1761
      mcn = len(disk.children) - mcn # max number of Nones
1762
    for chld_disk in disk.children:
1763
      try:
1764
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1765
      except errors.BlockDeviceError, err:
1766
        if children.count(None) >= mcn:
1767
          raise
1768
        cdev = None
1769
        logging.error("Error in child activation (but continuing): %s",
1770
                      str(err))
1771
      children.append(cdev)
1772

    
1773
  if as_primary or disk.AssembleOnSecondary():
1774
    r_dev = bdev.Assemble(disk, children)
1775
    result = r_dev
1776
    if as_primary or disk.OpenOnSecondary():
1777
      r_dev.Open()
1778
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1779
                                as_primary, disk.iv_name)
1780

    
1781
  else:
1782
    result = True
1783
  return result
1784

    
1785

    
1786
def BlockdevAssemble(disk, owner, as_primary, idx):
1787
  """Activate a block device for an instance.
1788

1789
  This is a wrapper over _RecursiveAssembleBD.
1790

1791
  @rtype: str or boolean
1792
  @return: a C{/dev/...} path for primary nodes, and
1793
      C{True} for secondary nodes
1794

1795
  """
1796
  try:
1797
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1798
    if isinstance(result, bdev.BlockDev):
1799
      # pylint: disable=E1103
1800
      result = result.dev_path
1801
      if as_primary:
1802
        _SymlinkBlockDev(owner, result, idx)
1803
  except errors.BlockDeviceError, err:
1804
    _Fail("Error while assembling disk: %s", err, exc=True)
1805
  except OSError, err:
1806
    _Fail("Error while symlinking disk: %s", err, exc=True)
1807

    
1808
  return result
1809

    
1810

    
1811
def BlockdevShutdown(disk):
1812
  """Shut down a block device.
1813

1814
  First, if the device is assembled (Attach() is successful), then
1815
  the device is shutdown. Then the children of the device are
1816
  shutdown.
1817

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

1822
  @type disk: L{objects.Disk}
1823
  @param disk: the description of the disk we should
1824
      shutdown
1825
  @rtype: None
1826

1827
  """
1828
  msgs = []
1829
  r_dev = _RecursiveFindBD(disk)
1830
  if r_dev is not None:
1831
    r_path = r_dev.dev_path
1832
    try:
1833
      r_dev.Shutdown()
1834
      DevCacheManager.RemoveCache(r_path)
1835
    except errors.BlockDeviceError, err:
1836
      msgs.append(str(err))
1837

    
1838
  if disk.children:
1839
    for child in disk.children:
1840
      try:
1841
        BlockdevShutdown(child)
1842
      except RPCFail, err:
1843
        msgs.append(str(err))
1844

    
1845
  if msgs:
1846
    _Fail("; ".join(msgs))
1847

    
1848

    
1849
def BlockdevAddchildren(parent_cdev, new_cdevs):
1850
  """Extend a mirrored block device.
1851

1852
  @type parent_cdev: L{objects.Disk}
1853
  @param parent_cdev: the disk to which we should add children
1854
  @type new_cdevs: list of L{objects.Disk}
1855
  @param new_cdevs: the list of children which we should add
1856
  @rtype: None
1857

1858
  """
1859
  parent_bdev = _RecursiveFindBD(parent_cdev)
1860
  if parent_bdev is None:
1861
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1862
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1863
  if new_bdevs.count(None) > 0:
1864
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1865
  parent_bdev.AddChildren(new_bdevs)
1866

    
1867

    
1868
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1869
  """Shrink a mirrored block device.
1870

1871
  @type parent_cdev: L{objects.Disk}
1872
  @param parent_cdev: the disk from which we should remove children
1873
  @type new_cdevs: list of L{objects.Disk}
1874
  @param new_cdevs: the list of children which we should remove
1875
  @rtype: None
1876

1877
  """
1878
  parent_bdev = _RecursiveFindBD(parent_cdev)
1879
  if parent_bdev is None:
1880
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1881
  devs = []
1882
  for disk in new_cdevs:
1883
    rpath = disk.StaticDevPath()
1884
    if rpath is None:
1885
      bd = _RecursiveFindBD(disk)
1886
      if bd is None:
1887
        _Fail("Can't find device %s while removing children", disk)
1888
      else:
1889
        devs.append(bd.dev_path)
1890
    else:
1891
      if not utils.IsNormAbsPath(rpath):
1892
        _Fail("Strange path returned from StaticDevPath: '%s'", rpath)
1893
      devs.append(rpath)
1894
  parent_bdev.RemoveChildren(devs)
1895

    
1896

    
1897
def BlockdevGetmirrorstatus(disks):
1898
  """Get the mirroring status of a list of devices.
1899

1900
  @type disks: list of L{objects.Disk}
1901
  @param disks: the list of disks which we should query
1902
  @rtype: disk
1903
  @return: List of L{objects.BlockDevStatus}, one for each disk
1904
  @raise errors.BlockDeviceError: if any of the disks cannot be
1905
      found
1906

1907
  """
1908
  stats = []
1909
  for dsk in disks:
1910
    rbd = _RecursiveFindBD(dsk)
1911
    if rbd is None:
1912
      _Fail("Can't find device %s", dsk)
1913

    
1914
    stats.append(rbd.CombinedSyncStatus())
1915

    
1916
  return stats
1917

    
1918

    
1919
def BlockdevGetmirrorstatusMulti(disks):
1920
  """Get the mirroring status of a list of devices.
1921

1922
  @type disks: list of L{objects.Disk}
1923
  @param disks: the list of disks which we should query
1924
  @rtype: disk
1925
  @return: List of tuples, (bool, status), one for each disk; bool denotes
1926
    success/failure, status is L{objects.BlockDevStatus} on success, string
1927
    otherwise
1928

1929
  """
1930
  result = []
1931
  for disk in disks:
1932
    try:
1933
      rbd = _RecursiveFindBD(disk)
1934
      if rbd is None:
1935
        result.append((False, "Can't find device %s" % disk))
1936
        continue
1937

    
1938
      status = rbd.CombinedSyncStatus()
1939
    except errors.BlockDeviceError, err:
1940
      logging.exception("Error while getting disk status")
1941
      result.append((False, str(err)))
1942
    else:
1943
      result.append((True, status))
1944

    
1945
  assert len(disks) == len(result)
1946

    
1947
  return result
1948

    
1949

    
1950
def _RecursiveFindBD(disk):
1951
  """Check if a device is activated.
1952

1953
  If so, return information about the real device.
1954

1955
  @type disk: L{objects.Disk}
1956
  @param disk: the disk object we need to find
1957

1958
  @return: None if the device can't be found,
1959
      otherwise the device instance
1960

1961
  """
1962
  children = []
1963
  if disk.children:
1964
    for chdisk in disk.children:
1965
      children.append(_RecursiveFindBD(chdisk))
1966

    
1967
  return bdev.FindDevice(disk, children)
1968

    
1969

    
1970
def _OpenRealBD(disk):
1971
  """Opens the underlying block device of a disk.
1972

1973
  @type disk: L{objects.Disk}
1974
  @param disk: the disk object we want to open
1975

1976
  """
1977
  real_disk = _RecursiveFindBD(disk)
1978
  if real_disk is None:
1979
    _Fail("Block device '%s' is not set up", disk)
1980

    
1981
  real_disk.Open()
1982

    
1983
  return real_disk
1984

    
1985

    
1986
def BlockdevFind(disk):
1987
  """Check if a device is activated.
1988

1989
  If it is, return information about the real device.
1990

1991
  @type disk: L{objects.Disk}
1992
  @param disk: the disk to find
1993
  @rtype: None or objects.BlockDevStatus
1994
  @return: None if the disk cannot be found, otherwise a the current
1995
           information
1996

1997
  """
1998
  try:
1999
    rbd = _RecursiveFindBD(disk)
2000
  except errors.BlockDeviceError, err:
2001
    _Fail("Failed to find device: %s", err, exc=True)
2002

    
2003
  if rbd is None:
2004
    return None
2005

    
2006
  return rbd.GetSyncStatus()
2007

    
2008

    
2009
def BlockdevGetsize(disks):
2010
  """Computes the size of the given disks.
2011

2012
  If a disk is not found, returns None instead.
2013

2014
  @type disks: list of L{objects.Disk}
2015
  @param disks: the list of disk to compute the size for
2016
  @rtype: list
2017
  @return: list with elements None if the disk cannot be found,
2018
      otherwise the size
2019

2020
  """
2021
  result = []
2022
  for cf in disks:
2023
    try:
2024
      rbd = _RecursiveFindBD(cf)
2025
    except errors.BlockDeviceError:
2026
      result.append(None)
2027
      continue
2028
    if rbd is None:
2029
      result.append(None)
2030
    else:
2031
      result.append(rbd.GetActualSize())
2032
  return result
2033

    
2034

    
2035
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
2036
  """Export a block device to a remote node.
2037

2038
  @type disk: L{objects.Disk}
2039
  @param disk: the description of the disk to export
2040
  @type dest_node: str
2041
  @param dest_node: the destination node to export to
2042
  @type dest_path: str
2043
  @param dest_path: the destination path on the target node
2044
  @type cluster_name: str
2045
  @param cluster_name: the cluster name, needed for SSH hostalias
2046
  @rtype: None
2047

2048
  """
2049
  real_disk = _OpenRealBD(disk)
2050

    
2051
  # the block size on the read dd is 1MiB to match our units
2052
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
2053
                               "dd if=%s bs=1048576 count=%s",
2054
                               real_disk.dev_path, str(disk.size))
2055

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

    
2065
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2066
                                                   constants.GANETI_RUNAS,
2067
                                                   destcmd)
2068

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

    
2072
  result = utils.RunCmd(["bash", "-c", command])
2073

    
2074
  if result.failed:
2075
    _Fail("Disk copy command '%s' returned error: %s"
2076
          " output: %s", command, result.fail_reason, result.output)
2077

    
2078

    
2079
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
2080
  """Write a file to the filesystem.
2081

2082
  This allows the master to overwrite(!) a file. It will only perform
2083
  the operation if the file belongs to a list of configuration files.
2084

2085
  @type file_name: str
2086
  @param file_name: the target file name
2087
  @type data: str
2088
  @param data: the new contents of the file
2089
  @type mode: int
2090
  @param mode: the mode to give the file (can be None)
2091
  @type uid: string
2092
  @param uid: the owner of the file
2093
  @type gid: string
2094
  @param gid: the group of the file
2095
  @type atime: float
2096
  @param atime: the atime to set on the file (can be None)
2097
  @type mtime: float
2098
  @param mtime: the mtime to set on the file (can be None)
2099
  @rtype: None
2100

2101
  """
2102
  if not os.path.isabs(file_name):
2103
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
2104

    
2105
  if file_name not in _ALLOWED_UPLOAD_FILES:
2106
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
2107
          file_name)
2108

    
2109
  raw_data = _Decompress(data)
2110

    
2111
  if not (isinstance(uid, basestring) and isinstance(gid, basestring)):
2112
    _Fail("Invalid username/groupname type")
2113

    
2114
  getents = runtime.GetEnts()
2115
  uid = getents.LookupUser(uid)
2116
  gid = getents.LookupGroup(gid)
2117

    
2118
  utils.SafeWriteFile(file_name, None,
2119
                      data=raw_data, mode=mode, uid=uid, gid=gid,
2120
                      atime=atime, mtime=mtime)
2121

    
2122

    
2123
def RunOob(oob_program, command, node, timeout):
2124
  """Executes oob_program with given command on given node.
2125

2126
  @param oob_program: The path to the executable oob_program
2127
  @param command: The command to invoke on oob_program
2128
  @param node: The node given as an argument to the program
2129
  @param timeout: Timeout after which we kill the oob program
2130

2131
  @return: stdout
2132
  @raise RPCFail: If execution fails for some reason
2133

2134
  """
2135
  result = utils.RunCmd([oob_program, command, node], timeout=timeout)
2136

    
2137
  if result.failed:
2138
    _Fail("'%s' failed with reason '%s'; output: %s", result.cmd,
2139
          result.fail_reason, result.output)
2140

    
2141
  return result.stdout
2142

    
2143

    
2144
def WriteSsconfFiles(values):
2145
  """Update all ssconf files.
2146

2147
  Wrapper around the SimpleStore.WriteFiles.
2148

2149
  """
2150
  ssconf.SimpleStore().WriteFiles(values)
2151

    
2152

    
2153
def _OSOndiskAPIVersion(os_dir):
2154
  """Compute and return the API version of a given OS.
2155

2156
  This function will try to read the API version of the OS residing in
2157
  the 'os_dir' directory.
2158

2159
  @type os_dir: str
2160
  @param os_dir: the directory in which we should look for the OS
2161
  @rtype: tuple
2162
  @return: tuple (status, data) with status denoting the validity and
2163
      data holding either the vaid versions or an error message
2164

2165
  """
2166
  api_file = utils.PathJoin(os_dir, constants.OS_API_FILE)
2167

    
2168
  try:
2169
    st = os.stat(api_file)
2170
  except EnvironmentError, err:
2171
    return False, ("Required file '%s' not found under path %s: %s" %
2172
                   (constants.OS_API_FILE, os_dir, utils.ErrnoOrStr(err)))
2173

    
2174
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2175
    return False, ("File '%s' in %s is not a regular file" %
2176
                   (constants.OS_API_FILE, os_dir))
2177

    
2178
  try:
2179
    api_versions = utils.ReadFile(api_file).splitlines()
2180
  except EnvironmentError, err:
2181
    return False, ("Error while reading the API version file at %s: %s" %
2182
                   (api_file, utils.ErrnoOrStr(err)))
2183

    
2184
  try:
2185
    api_versions = [int(version.strip()) for version in api_versions]
2186
  except (TypeError, ValueError), err:
2187
    return False, ("API version(s) can't be converted to integer: %s" %
2188
                   str(err))
2189

    
2190
  return True, api_versions
2191

    
2192

    
2193
def DiagnoseOS(top_dirs=None):
2194
  """Compute the validity for all OSes.
2195

2196
  @type top_dirs: list
2197
  @param top_dirs: the list of directories in which to
2198
      search (if not given defaults to
2199
      L{constants.OS_SEARCH_PATH})
2200
  @rtype: list of L{objects.OS}
2201
  @return: a list of tuples (name, path, status, diagnose, variants,
2202
      parameters, api_version) for all (potential) OSes under all
2203
      search paths, where:
2204
          - name is the (potential) OS name
2205
          - path is the full path to the OS
2206
          - status True/False is the validity of the OS
2207
          - diagnose is the error message for an invalid OS, otherwise empty
2208
          - variants is a list of supported OS variants, if any
2209
          - parameters is a list of (name, help) parameters, if any
2210
          - api_version is a list of support OS API versions
2211

2212
  """
2213
  if top_dirs is None:
2214
    top_dirs = constants.OS_SEARCH_PATH
2215

    
2216
  result = []
2217
  for dir_name in top_dirs:
2218
    if os.path.isdir(dir_name):
2219
      try:
2220
        f_names = utils.ListVisibleFiles(dir_name)
2221
      except EnvironmentError, err:
2222
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
2223
        break
2224
      for name in f_names:
2225
        os_path = utils.PathJoin(dir_name, name)
2226
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
2227
        if status:
2228
          diagnose = ""
2229
          variants = os_inst.supported_variants
2230
          parameters = os_inst.supported_parameters
2231
          api_versions = os_inst.api_versions
2232
        else:
2233
          diagnose = os_inst
2234
          variants = parameters = api_versions = []
2235
        result.append((name, os_path, status, diagnose, variants,
2236
                       parameters, api_versions))
2237

    
2238
  return result
2239

    
2240

    
2241
def _TryOSFromDisk(name, base_dir=None):
2242
  """Create an OS instance from disk.
2243

2244
  This function will return an OS instance if the given name is a
2245
  valid OS name.
2246

2247
  @type base_dir: string
2248
  @keyword base_dir: Base directory containing OS installations.
2249
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2250
  @rtype: tuple
2251
  @return: success and either the OS instance if we find a valid one,
2252
      or error message
2253

2254
  """
2255
  if base_dir is None:
2256
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
2257
  else:
2258
    os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
2259

    
2260
  if os_dir is None:
2261
    return False, "Directory for OS %s not found in search path" % name
2262

    
2263
  status, api_versions = _OSOndiskAPIVersion(os_dir)
2264
  if not status:
2265
    # push the error up
2266
    return status, api_versions
2267

    
2268
  if not constants.OS_API_VERSIONS.intersection(api_versions):
2269
    return False, ("API version mismatch for path '%s': found %s, want %s." %
2270
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
2271

    
2272
  # OS Files dictionary, we will populate it with the absolute path
2273
  # names; if the value is True, then it is a required file, otherwise
2274
  # an optional one
2275
  os_files = dict.fromkeys(constants.OS_SCRIPTS, True)
2276

    
2277
  if max(api_versions) >= constants.OS_API_V15:
2278
    os_files[constants.OS_VARIANTS_FILE] = False
2279

    
2280
  if max(api_versions) >= constants.OS_API_V20:
2281
    os_files[constants.OS_PARAMETERS_FILE] = True
2282
  else:
2283
    del os_files[constants.OS_SCRIPT_VERIFY]
2284

    
2285
  for (filename, required) in os_files.items():
2286
    os_files[filename] = utils.PathJoin(os_dir, filename)
2287

    
2288
    try:
2289
      st = os.stat(os_files[filename])
2290
    except EnvironmentError, err:
2291
      if err.errno == errno.ENOENT and not required:
2292
        del os_files[filename]
2293
        continue
2294
      return False, ("File '%s' under path '%s' is missing (%s)" %
2295
                     (filename, os_dir, utils.ErrnoOrStr(err)))
2296

    
2297
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
2298
      return False, ("File '%s' under path '%s' is not a regular file" %
2299
                     (filename, os_dir))
2300

    
2301
    if filename in constants.OS_SCRIPTS:
2302
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
2303
        return False, ("File '%s' under path '%s' is not executable" %
2304
                       (filename, os_dir))
2305

    
2306
  variants = []
2307
  if constants.OS_VARIANTS_FILE in os_files:
2308
    variants_file = os_files[constants.OS_VARIANTS_FILE]
2309
    try:
2310
      variants = utils.ReadFile(variants_file).splitlines()
2311
    except EnvironmentError, err:
2312
      # we accept missing files, but not other errors
2313
      if err.errno != errno.ENOENT:
2314
        return False, ("Error while reading the OS variants file at %s: %s" %
2315
                       (variants_file, utils.ErrnoOrStr(err)))
2316

    
2317
  parameters = []
2318
  if constants.OS_PARAMETERS_FILE in os_files:
2319
    parameters_file = os_files[constants.OS_PARAMETERS_FILE]
2320
    try:
2321
      parameters = utils.ReadFile(parameters_file).splitlines()
2322
    except EnvironmentError, err:
2323
      return False, ("Error while reading the OS parameters file at %s: %s" %
2324
                     (parameters_file, utils.ErrnoOrStr(err)))
2325
    parameters = [v.split(None, 1) for v in parameters]
2326

    
2327
  os_obj = objects.OS(name=name, path=os_dir,
2328
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
2329
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
2330
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
2331
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
2332
                      verify_script=os_files.get(constants.OS_SCRIPT_VERIFY,
2333
                                                 None),
2334
                      supported_variants=variants,
2335
                      supported_parameters=parameters,
2336
                      api_versions=api_versions)
2337
  return True, os_obj
2338

    
2339

    
2340
def OSFromDisk(name, base_dir=None):
2341
  """Create an OS instance from disk.
2342

2343
  This function will return an OS instance if the given name is a
2344
  valid OS name. Otherwise, it will raise an appropriate
2345
  L{RPCFail} exception, detailing why this is not a valid OS.
2346

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

2350
  @type base_dir: string
2351
  @keyword base_dir: Base directory containing OS installations.
2352
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
2353
  @rtype: L{objects.OS}
2354
  @return: the OS instance if we find a valid one
2355
  @raise RPCFail: if we don't find a valid OS
2356

2357
  """
2358
  name_only = objects.OS.GetName(name)
2359
  status, payload = _TryOSFromDisk(name_only, base_dir)
2360

    
2361
  if not status:
2362
    _Fail(payload)
2363

    
2364
  return payload
2365

    
2366

    
2367
def OSCoreEnv(os_name, inst_os, os_params, debug=0):
2368
  """Calculate the basic environment for an os script.
2369

2370
  @type os_name: str
2371
  @param os_name: full operating system name (including variant)
2372
  @type inst_os: L{objects.OS}
2373
  @param inst_os: operating system for which the environment is being built
2374
  @type os_params: dict
2375
  @param os_params: the OS parameters
2376
  @type debug: integer
2377
  @param debug: debug level (0 or 1, for OS Api 10)
2378
  @rtype: dict
2379
  @return: dict of environment variables
2380
  @raise errors.BlockDeviceError: if the block device
2381
      cannot be found
2382

2383
  """
2384
  result = {}
2385
  api_version = \
2386
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
2387
  result["OS_API_VERSION"] = "%d" % api_version
2388
  result["OS_NAME"] = inst_os.name
2389
  result["DEBUG_LEVEL"] = "%d" % debug
2390

    
2391
  # OS variants
2392
  if api_version >= constants.OS_API_V15 and inst_os.supported_variants:
2393
    variant = objects.OS.GetVariant(os_name)
2394
    if not variant:
2395
      variant = inst_os.supported_variants[0]
2396
  else:
2397
    variant = ""
2398
  result["OS_VARIANT"] = variant
2399

    
2400
  # OS params
2401
  for pname, pvalue in os_params.items():
2402
    result["OSP_%s" % pname.upper()] = pvalue
2403

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

    
2409
  return result
2410

    
2411

    
2412
def OSEnvironment(instance, inst_os, debug=0):
2413
  """Calculate the environment for an os script.
2414

2415
  @type instance: L{objects.Instance}
2416
  @param instance: target instance for the os script run
2417
  @type inst_os: L{objects.OS}
2418
  @param inst_os: operating system for which the environment is being built
2419
  @type debug: integer
2420
  @param debug: debug level (0 or 1, for OS Api 10)
2421
  @rtype: dict
2422
  @return: dict of environment variables
2423
  @raise errors.BlockDeviceError: if the block device
2424
      cannot be found
2425

2426
  """
2427
  result = OSCoreEnv(instance.os, inst_os, instance.osparams, debug=debug)
2428

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

    
2432
  result["HYPERVISOR"] = instance.hypervisor
2433
  result["DISK_COUNT"] = "%d" % len(instance.disks)
2434
  result["NIC_COUNT"] = "%d" % len(instance.nics)
2435
  result["INSTANCE_SECONDARY_NODES"] = \
2436
      ("%s" % " ".join(instance.secondary_nodes))
2437

    
2438
  # Disks
2439
  for idx, disk in enumerate(instance.disks):
2440
    real_disk = _OpenRealBD(disk)
2441
    result["DISK_%d_PATH" % idx] = real_disk.dev_path
2442
    result["DISK_%d_ACCESS" % idx] = disk.mode
2443
    if constants.HV_DISK_TYPE in instance.hvparams:
2444
      result["DISK_%d_FRONTEND_TYPE" % idx] = \
2445
        instance.hvparams[constants.HV_DISK_TYPE]
2446
    if disk.dev_type in constants.LDS_BLOCK:
2447
      result["DISK_%d_BACKEND_TYPE" % idx] = "block"
2448
    elif disk.dev_type == constants.LD_FILE:
2449
      result["DISK_%d_BACKEND_TYPE" % idx] = \
2450
        "file:%s" % disk.physical_id[0]
2451

    
2452
  # NICs
2453
  for idx, nic in enumerate(instance.nics):
2454
    result["NIC_%d_MAC" % idx] = nic.mac
2455
    if nic.ip:
2456
      result["NIC_%d_IP" % idx] = nic.ip
2457
    result["NIC_%d_MODE" % idx] = nic.nicparams[constants.NIC_MODE]
2458
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2459
      result["NIC_%d_BRIDGE" % idx] = nic.nicparams[constants.NIC_LINK]
2460
    if nic.nicparams[constants.NIC_LINK]:
2461
      result["NIC_%d_LINK" % idx] = nic.nicparams[constants.NIC_LINK]
2462
    if nic.network:
2463
      result["NIC_%d_NETWORK" % idx] = nic.network
2464
    if constants.HV_NIC_TYPE in instance.hvparams:
2465
      result["NIC_%d_FRONTEND_TYPE" % idx] = \
2466
        instance.hvparams[constants.HV_NIC_TYPE]
2467

    
2468
  # HV/BE params
2469
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
2470
    for key, value in source.items():
2471
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
2472

    
2473
  return result
2474

    
2475

    
2476
def DiagnoseExtStorage(top_dirs=None):
2477
  """Compute the validity for all ExtStorage Providers.
2478

2479
  @type top_dirs: list
2480
  @param top_dirs: the list of directories in which to
2481
      search (if not given defaults to
2482
      L{constants.ES_SEARCH_PATH})
2483
  @rtype: list of L{objects.ExtStorage}
2484
  @return: a list of tuples (name, path, status, diagnose, parameters)
2485
      for all (potential) ExtStorage Providers under all
2486
      search paths, where:
2487
          - name is the (potential) ExtStorage Provider
2488
          - path is the full path to the ExtStorage Provider
2489
          - status True/False is the validity of the ExtStorage Provider
2490
          - diagnose is the error message for an invalid ExtStorage Provider,
2491
            otherwise empty
2492
          - parameters is a list of (name, help) parameters, if any
2493

2494
  """
2495
  if top_dirs is None:
2496
    top_dirs = constants.ES_SEARCH_PATH
2497

    
2498
  result = []
2499
  for dir_name in top_dirs:
2500
    if os.path.isdir(dir_name):
2501
      try:
2502
        f_names = utils.ListVisibleFiles(dir_name)
2503
      except EnvironmentError, err:
2504
        logging.exception("Can't list the ExtStorage directory %s: %s",
2505
                          dir_name, err)
2506
        break
2507
      for name in f_names:
2508
        es_path = utils.PathJoin(dir_name, name)
2509
        status, es_inst = bdev.ExtStorageFromDisk(name, base_dir=dir_name)
2510
        if status:
2511
          diagnose = ""
2512
          parameters = es_inst.supported_parameters
2513
        else:
2514
          diagnose = es_inst
2515
          parameters = []
2516
        result.append((name, es_path, status, diagnose, parameters))
2517

    
2518
  return result
2519

    
2520

    
2521
def BlockdevGrow(disk, amount, dryrun):
2522
  """Grow a stack of block devices.
2523

2524
  This function is called recursively, with the childrens being the
2525
  first ones to resize.
2526

2527
  @type disk: L{objects.Disk}
2528
  @param disk: the disk to be grown
2529
  @type amount: integer
2530
  @param amount: the amount (in mebibytes) to grow with
2531
  @type dryrun: boolean
2532
  @param dryrun: whether to execute the operation in simulation mode
2533
      only, without actually increasing the size
2534
  @rtype: (status, result)
2535
  @return: a tuple with the status of the operation (True/False), and
2536
      the errors message if status is False
2537

2538
  """
2539
  r_dev = _RecursiveFindBD(disk)
2540
  if r_dev is None:
2541
    _Fail("Cannot find block device %s", disk)
2542

    
2543
  try:
2544
    r_dev.Grow(amount, dryrun)
2545
  except errors.BlockDeviceError, err:
2546
    _Fail("Failed to grow block device: %s", err, exc=True)
2547

    
2548

    
2549
def BlockdevSnapshot(disk):
2550
  """Create a snapshot copy of a block device.
2551

2552
  This function is called recursively, and the snapshot is actually created
2553
  just for the leaf lvm backend device.
2554

2555
  @type disk: L{objects.Disk}
2556
  @param disk: the disk to be snapshotted
2557
  @rtype: string
2558
  @return: snapshot disk ID as (vg, lv)
2559

2560
  """
2561
  if disk.dev_type == constants.LD_DRBD8:
2562
    if not disk.children:
2563
      _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
2564
            disk.unique_id)
2565
    return BlockdevSnapshot(disk.children[0])
2566
  elif disk.dev_type == constants.LD_LV:
2567
    r_dev = _RecursiveFindBD(disk)
2568
    if r_dev is not None:
2569
      # FIXME: choose a saner value for the snapshot size
2570
      # let's stay on the safe side and ask for the full size, for now
2571
      return r_dev.Snapshot(disk.size)
2572
    else:
2573
      _Fail("Cannot find block device %s", disk)
2574
  else:
2575
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
2576
          disk.unique_id, disk.dev_type)
2577

    
2578

    
2579
def FinalizeExport(instance, snap_disks):
2580
  """Write out the export configuration information.
2581

2582
  @type instance: L{objects.Instance}
2583
  @param instance: the instance which we export, used for
2584
      saving configuration
2585
  @type snap_disks: list of L{objects.Disk}
2586
  @param snap_disks: list of snapshot block devices, which
2587
      will be used to get the actual name of the dump file
2588

2589
  @rtype: None
2590

2591
  """
2592
  destdir = utils.PathJoin(constants.EXPORT_DIR, instance.name + ".new")
2593
  finaldestdir = utils.PathJoin(constants.EXPORT_DIR, instance.name)
2594

    
2595
  config = objects.SerializableConfigParser()
2596

    
2597
  config.add_section(constants.INISECT_EXP)
2598
  config.set(constants.INISECT_EXP, "version", "0")
2599
  config.set(constants.INISECT_EXP, "timestamp", "%d" % int(time.time()))
2600
  config.set(constants.INISECT_EXP, "source", instance.primary_node)
2601
  config.set(constants.INISECT_EXP, "os", instance.os)
2602
  config.set(constants.INISECT_EXP, "compression", "none")
2603

    
2604
  config.add_section(constants.INISECT_INS)
2605
  config.set(constants.INISECT_INS, "name", instance.name)
2606
  config.set(constants.INISECT_INS, "maxmem", "%d" %
2607
             instance.beparams[constants.BE_MAXMEM])
2608
  config.set(constants.INISECT_INS, "minmem", "%d" %
2609
             instance.beparams[constants.BE_MINMEM])
2610
  # "memory" is deprecated, but useful for exporting to old ganeti versions
2611
  config.set(constants.INISECT_INS, "memory", "%d" %
2612
             instance.beparams[constants.BE_MAXMEM])
2613
  config.set(constants.INISECT_INS, "vcpus", "%d" %
2614
             instance.beparams[constants.BE_VCPUS])
2615
  config.set(constants.INISECT_INS, "disk_template", instance.disk_template)
2616
  config.set(constants.INISECT_INS, "hypervisor", instance.hypervisor)
2617
  config.set(constants.INISECT_INS, "tags", " ".join(instance.GetTags()))
2618

    
2619
  nic_total = 0
2620
  for nic_count, nic in enumerate(instance.nics):
2621
    nic_total += 1
2622
    config.set(constants.INISECT_INS, "nic%d_mac" %
2623
               nic_count, "%s" % nic.mac)
2624
    config.set(constants.INISECT_INS, "nic%d_ip" % nic_count, "%s" % nic.ip)
2625
    config.set(constants.INISECT_INS, "nic%d_network" % nic_count,
2626
               "%s" % nic.network)
2627
    for param in constants.NICS_PARAMETER_TYPES:
2628
      config.set(constants.INISECT_INS, "nic%d_%s" % (nic_count, param),
2629
                 "%s" % nic.nicparams.get(param, None))
2630
  # TODO: redundant: on load can read nics until it doesn't exist
2631
  config.set(constants.INISECT_INS, "nic_count", "%d" % nic_total)
2632

    
2633
  disk_total = 0
2634
  for disk_count, disk in enumerate(snap_disks):
2635
    if disk:
2636
      disk_total += 1
2637
      config.set(constants.INISECT_INS, "disk%d_ivname" % disk_count,
2638
                 ("%s" % disk.iv_name))
2639
      config.set(constants.INISECT_INS, "disk%d_dump" % disk_count,
2640
                 ("%s" % disk.physical_id[1]))
2641
      config.set(constants.INISECT_INS, "disk%d_size" % disk_count,
2642
                 ("%d" % disk.size))
2643

    
2644
  config.set(constants.INISECT_INS, "disk_count", "%d" % disk_total)
2645

    
2646
  # New-style hypervisor/backend parameters
2647

    
2648
  config.add_section(constants.INISECT_HYP)
2649
  for name, value in instance.hvparams.items():
2650
    if name not in constants.HVC_GLOBALS:
2651
      config.set(constants.INISECT_HYP, name, str(value))
2652

    
2653
  config.add_section(constants.INISECT_BEP)
2654
  for name, value in instance.beparams.items():
2655
    config.set(constants.INISECT_BEP, name, str(value))
2656

    
2657
  config.add_section(constants.INISECT_OSP)
2658
  for name, value in instance.osparams.items():
2659
    config.set(constants.INISECT_OSP, name, str(value))
2660

    
2661
  utils.WriteFile(utils.PathJoin(destdir, constants.EXPORT_CONF_FILE),
2662
                  data=config.Dumps())
2663
  shutil.rmtree(finaldestdir, ignore_errors=True)
2664
  shutil.move(destdir, finaldestdir)
2665

    
2666

    
2667
def ExportInfo(dest):
2668
  """Get export configuration information.
2669

2670
  @type dest: str
2671
  @param dest: directory containing the export
2672

2673
  @rtype: L{objects.SerializableConfigParser}
2674
  @return: a serializable config file containing the
2675
      export info
2676

2677
  """
2678
  cff = utils.PathJoin(dest, constants.EXPORT_CONF_FILE)
2679

    
2680
  config = objects.SerializableConfigParser()
2681
  config.read(cff)
2682

    
2683
  if (not config.has_section(constants.INISECT_EXP) or
2684
      not config.has_section(constants.INISECT_INS)):
2685
    _Fail("Export info file doesn't have the required fields")
2686

    
2687
  return config.Dumps()
2688

    
2689

    
2690
def ListExports():
2691
  """Return a list of exports currently available on this machine.
2692

2693
  @rtype: list
2694
  @return: list of the exports
2695

2696
  """
2697
  if os.path.isdir(constants.EXPORT_DIR):
2698
    return sorted(utils.ListVisibleFiles(constants.EXPORT_DIR))
2699
  else:
2700
    _Fail("No exports directory")
2701

    
2702

    
2703
def RemoveExport(export):
2704
  """Remove an existing export from the node.
2705

2706
  @type export: str
2707
  @param export: the name of the export to remove
2708
  @rtype: None
2709

2710
  """
2711
  target = utils.PathJoin(constants.EXPORT_DIR, export)
2712

    
2713
  try:
2714
    shutil.rmtree(target)
2715
  except EnvironmentError, err:
2716
    _Fail("Error while removing the export: %s", err, exc=True)
2717

    
2718

    
2719
def BlockdevRename(devlist):
2720
  """Rename a list of block devices.
2721

2722
  @type devlist: list of tuples
2723
  @param devlist: list of tuples of the form  (disk,
2724
      new_logical_id, new_physical_id); disk is an
2725
      L{objects.Disk} object describing the current disk,
2726
      and new logical_id/physical_id is the name we
2727
      rename it to
2728
  @rtype: boolean
2729
  @return: True if all renames succeeded, False otherwise
2730

2731
  """
2732
  msgs = []
2733
  result = True
2734
  for disk, unique_id in devlist:
2735
    dev = _RecursiveFindBD(disk)
2736
    if dev is None:
2737
      msgs.append("Can't find device %s in rename" % str(disk))
2738
      result = False
2739
      continue
2740
    try:
2741
      old_rpath = dev.dev_path
2742
      dev.Rename(unique_id)
2743
      new_rpath = dev.dev_path
2744
      if old_rpath != new_rpath:
2745
        DevCacheManager.RemoveCache(old_rpath)
2746
        # FIXME: we should add the new cache information here, like:
2747
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2748
        # but we don't have the owner here - maybe parse from existing
2749
        # cache? for now, we only lose lvm data when we rename, which
2750
        # is less critical than DRBD or MD
2751
    except errors.BlockDeviceError, err:
2752
      msgs.append("Can't rename device '%s' to '%s': %s" %
2753
                  (dev, unique_id, err))
2754
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2755
      result = False
2756
  if not result:
2757
    _Fail("; ".join(msgs))
2758

    
2759

    
2760
def _TransformFileStorageDir(fs_dir):
2761
  """Checks whether given file_storage_dir is valid.
2762

2763
  Checks wheter the given fs_dir is within the cluster-wide default
2764
  file_storage_dir or the shared_file_storage_dir, which are stored in
2765
  SimpleStore. Only paths under those directories are allowed.
2766

2767
  @type fs_dir: str
2768
  @param fs_dir: the path to check
2769

2770
  @return: the normalized path if valid, None otherwise
2771

2772
  """
2773
  if not constants.ENABLE_FILE_STORAGE:
2774
    _Fail("File storage disabled at configure time")
2775
  cfg = _GetConfig()
2776
  fs_dir = os.path.normpath(fs_dir)
2777
  base_fstore = cfg.GetFileStorageDir()
2778
  base_shared = cfg.GetSharedFileStorageDir()
2779
  if not (utils.IsBelowDir(base_fstore, fs_dir) or
2780
          utils.IsBelowDir(base_shared, fs_dir)):
2781
    _Fail("File storage directory '%s' is not under base file"
2782
          " storage directory '%s' or shared storage directory '%s'",
2783
          fs_dir, base_fstore, base_shared)
2784
  return fs_dir
2785

    
2786

    
2787
def CreateFileStorageDir(file_storage_dir):
2788
  """Create file storage directory.
2789

2790
  @type file_storage_dir: str
2791
  @param file_storage_dir: directory to create
2792

2793
  @rtype: tuple
2794
  @return: tuple with first element a boolean indicating wheter dir
2795
      creation was successful or not
2796

2797
  """
2798
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2799
  if os.path.exists(file_storage_dir):
2800
    if not os.path.isdir(file_storage_dir):
2801
      _Fail("Specified storage dir '%s' is not a directory",
2802
            file_storage_dir)
2803
  else:
2804
    try:
2805
      os.makedirs(file_storage_dir, 0750)
2806
    except OSError, err:
2807
      _Fail("Cannot create file storage directory '%s': %s",
2808
            file_storage_dir, err, exc=True)
2809

    
2810

    
2811
def RemoveFileStorageDir(file_storage_dir):
2812
  """Remove file storage directory.
2813

2814
  Remove it only if it's empty. If not log an error and return.
2815

2816
  @type file_storage_dir: str
2817
  @param file_storage_dir: the directory we should cleanup
2818
  @rtype: tuple (success,)
2819
  @return: tuple of one element, C{success}, denoting
2820
      whether the operation was successful
2821

2822
  """
2823
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2824
  if os.path.exists(file_storage_dir):
2825
    if not os.path.isdir(file_storage_dir):
2826
      _Fail("Specified Storage directory '%s' is not a directory",
2827
            file_storage_dir)
2828
    # deletes dir only if empty, otherwise we want to fail the rpc call
2829
    try:
2830
      os.rmdir(file_storage_dir)
2831
    except OSError, err:
2832
      _Fail("Cannot remove file storage directory '%s': %s",
2833
            file_storage_dir, err)
2834

    
2835

    
2836
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2837
  """Rename the file storage directory.
2838

2839
  @type old_file_storage_dir: str
2840
  @param old_file_storage_dir: the current path
2841
  @type new_file_storage_dir: str
2842
  @param new_file_storage_dir: the name we should rename to
2843
  @rtype: tuple (success,)
2844
  @return: tuple of one element, C{success}, denoting
2845
      whether the operation was successful
2846

2847
  """
2848
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2849
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2850
  if not os.path.exists(new_file_storage_dir):
2851
    if os.path.isdir(old_file_storage_dir):
2852
      try:
2853
        os.rename(old_file_storage_dir, new_file_storage_dir)
2854
      except OSError, err:
2855
        _Fail("Cannot rename '%s' to '%s': %s",
2856
              old_file_storage_dir, new_file_storage_dir, err)
2857
    else:
2858
      _Fail("Specified storage dir '%s' is not a directory",
2859
            old_file_storage_dir)
2860
  else:
2861
    if os.path.exists(old_file_storage_dir):
2862
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2863
            old_file_storage_dir, new_file_storage_dir)
2864

    
2865

    
2866
def _EnsureJobQueueFile(file_name):
2867
  """Checks whether the given filename is in the queue directory.
2868

2869
  @type file_name: str
2870
  @param file_name: the file name we should check
2871
  @rtype: None
2872
  @raises RPCFail: if the file is not valid
2873

2874
  """
2875
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2876
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2877

    
2878
  if not result:
2879
    _Fail("Passed job queue file '%s' does not belong to"
2880
          " the queue directory '%s'", file_name, queue_dir)
2881

    
2882

    
2883
def JobQueueUpdate(file_name, content):
2884
  """Updates a file in the queue directory.
2885

2886
  This is just a wrapper over L{utils.io.WriteFile}, with proper
2887
  checking.
2888

2889
  @type file_name: str
2890
  @param file_name: the job file name
2891
  @type content: str
2892
  @param content: the new job contents
2893
  @rtype: boolean
2894
  @return: the success of the operation
2895

2896
  """
2897
  _EnsureJobQueueFile(file_name)
2898
  getents = runtime.GetEnts()
2899

    
2900
  # Write and replace the file atomically
2901
  utils.WriteFile(file_name, data=_Decompress(content), uid=getents.masterd_uid,
2902
                  gid=getents.masterd_gid)
2903

    
2904

    
2905
def JobQueueRename(old, new):
2906
  """Renames a job queue file.
2907

2908
  This is just a wrapper over os.rename with proper checking.
2909

2910
  @type old: str
2911
  @param old: the old (actual) file name
2912
  @type new: str
2913
  @param new: the desired file name
2914
  @rtype: tuple
2915
  @return: the success of the operation and payload
2916

2917
  """
2918
  _EnsureJobQueueFile(old)
2919
  _EnsureJobQueueFile(new)
2920

    
2921
  getents = runtime.GetEnts()
2922

    
2923
  utils.RenameFile(old, new, mkdir=True, mkdir_mode=0700,
2924
                   dir_uid=getents.masterd_uid, dir_gid=getents.masterd_gid)
2925

    
2926

    
2927
def BlockdevClose(instance_name, disks):
2928
  """Closes the given block devices.
2929

2930
  This means they will be switched to secondary mode (in case of
2931
  DRBD).
2932

2933
  @param instance_name: if the argument is not empty, the symlinks
2934
      of this instance will be removed
2935
  @type disks: list of L{objects.Disk}
2936
  @param disks: the list of disks to be closed
2937
  @rtype: tuple (success, message)
2938
  @return: a tuple of success and message, where success
2939
      indicates the succes of the operation, and message
2940
      which will contain the error details in case we
2941
      failed
2942

2943
  """
2944
  bdevs = []
2945
  for cf in disks:
2946
    rd = _RecursiveFindBD(cf)
2947
    if rd is None:
2948
      _Fail("Can't find device %s", cf)
2949
    bdevs.append(rd)
2950

    
2951
  msg = []
2952
  for rd in bdevs:
2953
    try:
2954
      rd.Close()
2955
    except errors.BlockDeviceError, err:
2956
      msg.append(str(err))
2957
  if msg:
2958
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2959
  else:
2960
    if instance_name:
2961
      _RemoveBlockDevLinks(instance_name, disks)
2962

    
2963

    
2964
def ValidateHVParams(hvname, hvparams):
2965
  """Validates the given hypervisor parameters.
2966

2967
  @type hvname: string
2968
  @param hvname: the hypervisor name
2969
  @type hvparams: dict
2970
  @param hvparams: the hypervisor parameters to be validated
2971
  @rtype: None
2972

2973
  """
2974
  try:
2975
    hv_type = hypervisor.GetHypervisor(hvname)
2976
    hv_type.ValidateParameters(hvparams)
2977
  except errors.HypervisorError, err:
2978
    _Fail(str(err), log=False)
2979

    
2980

    
2981
def _CheckOSPList(os_obj, parameters):
2982
  """Check whether a list of parameters is supported by the OS.
2983

2984
  @type os_obj: L{objects.OS}
2985
  @param os_obj: OS object to check
2986
  @type parameters: list
2987
  @param parameters: the list of parameters to check
2988

2989
  """
2990
  supported = [v[0] for v in os_obj.supported_parameters]
2991
  delta = frozenset(parameters).difference(supported)
2992
  if delta:
2993
    _Fail("The following parameters are not supported"
2994
          " by the OS %s: %s" % (os_obj.name, utils.CommaJoin(delta)))
2995

    
2996

    
2997
def ValidateOS(required, osname, checks, osparams):
2998
  """Validate the given OS' parameters.
2999

3000
  @type required: boolean
3001
  @param required: whether absence of the OS should translate into
3002
      failure or not
3003
  @type osname: string
3004
  @param osname: the OS to be validated
3005
  @type checks: list
3006
  @param checks: list of the checks to run (currently only 'parameters')
3007
  @type osparams: dict
3008
  @param osparams: dictionary with OS parameters
3009
  @rtype: boolean
3010
  @return: True if the validation passed, or False if the OS was not
3011
      found and L{required} was false
3012

3013
  """
3014
  if not constants.OS_VALIDATE_CALLS.issuperset(checks):
3015
    _Fail("Unknown checks required for OS %s: %s", osname,
3016
          set(checks).difference(constants.OS_VALIDATE_CALLS))
3017

    
3018
  name_only = objects.OS.GetName(osname)
3019
  status, tbv = _TryOSFromDisk(name_only, None)
3020

    
3021
  if not status:
3022
    if required:
3023
      _Fail(tbv)
3024
    else:
3025
      return False
3026

    
3027
  if max(tbv.api_versions) < constants.OS_API_V20:
3028
    return True
3029

    
3030
  if constants.OS_VALIDATE_PARAMETERS in checks:
3031
    _CheckOSPList(tbv, osparams.keys())
3032

    
3033
  validate_env = OSCoreEnv(osname, tbv, osparams)
3034
  result = utils.RunCmd([tbv.verify_script] + checks, env=validate_env,
3035
                        cwd=tbv.path, reset_env=True)
3036
  if result.failed:
3037
    logging.error("os validate command '%s' returned error: %s output: %s",
3038
                  result.cmd, result.fail_reason, result.output)
3039
    _Fail("OS validation script failed (%s), output: %s",
3040
          result.fail_reason, result.output, log=False)
3041

    
3042
  return True
3043

    
3044

    
3045
def DemoteFromMC():
3046
  """Demotes the current node from master candidate role.
3047

3048
  """
3049
  # try to ensure we're not the master by mistake
3050
  master, myself = ssconf.GetMasterAndMyself()
3051
  if master == myself:
3052
    _Fail("ssconf status shows I'm the master node, will not demote")
3053

    
3054
  result = utils.RunCmd([constants.DAEMON_UTIL, "check", constants.MASTERD])
3055
  if not result.failed:
3056
    _Fail("The master daemon is running, will not demote")
3057

    
3058
  try:
3059
    if os.path.isfile(constants.CLUSTER_CONF_FILE):
3060
      utils.CreateBackup(constants.CLUSTER_CONF_FILE)
3061
  except EnvironmentError, err:
3062
    if err.errno != errno.ENOENT:
3063
      _Fail("Error while backing up cluster file: %s", err, exc=True)
3064

    
3065
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
3066

    
3067

    
3068
def _GetX509Filenames(cryptodir, name):
3069
  """Returns the full paths for the private key and certificate.
3070

3071
  """
3072
  return (utils.PathJoin(cryptodir, name),
3073
          utils.PathJoin(cryptodir, name, _X509_KEY_FILE),
3074
          utils.PathJoin(cryptodir, name, _X509_CERT_FILE))
3075

    
3076

    
3077
def CreateX509Certificate(validity, cryptodir=constants.CRYPTO_KEYS_DIR):
3078
  """Creates a new X509 certificate for SSL/TLS.
3079

3080
  @type validity: int
3081
  @param validity: Validity in seconds
3082
  @rtype: tuple; (string, string)
3083
  @return: Certificate name and public part
3084

3085
  """
3086
  (key_pem, cert_pem) = \
3087
    utils.GenerateSelfSignedX509Cert(netutils.Hostname.GetSysName(),
3088
                                     min(validity, _MAX_SSL_CERT_VALIDITY))
3089

    
3090
  cert_dir = tempfile.mkdtemp(dir=cryptodir,
3091
                              prefix="x509-%s-" % utils.TimestampForFilename())
3092
  try:
3093
    name = os.path.basename(cert_dir)
3094
    assert len(name) > 5
3095

    
3096
    (_, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3097

    
3098
    utils.WriteFile(key_file, mode=0400, data=key_pem)
3099
    utils.WriteFile(cert_file, mode=0400, data=cert_pem)
3100

    
3101
    # Never return private key as it shouldn't leave the node
3102
    return (name, cert_pem)
3103
  except Exception:
3104
    shutil.rmtree(cert_dir, ignore_errors=True)
3105
    raise
3106

    
3107

    
3108
def RemoveX509Certificate(name, cryptodir=constants.CRYPTO_KEYS_DIR):
3109
  """Removes a X509 certificate.
3110

3111
  @type name: string
3112
  @param name: Certificate name
3113

3114
  """
3115
  (cert_dir, key_file, cert_file) = _GetX509Filenames(cryptodir, name)
3116

    
3117
  utils.RemoveFile(key_file)
3118
  utils.RemoveFile(cert_file)
3119

    
3120
  try:
3121
    os.rmdir(cert_dir)
3122
  except EnvironmentError, err:
3123
    _Fail("Cannot remove certificate directory '%s': %s",
3124
          cert_dir, err)
3125

    
3126

    
3127
def _GetImportExportIoCommand(instance, mode, ieio, ieargs):
3128
  """Returns the command for the requested input/output.
3129

3130
  @type instance: L{objects.Instance}
3131
  @param instance: The instance object
3132
  @param mode: Import/export mode
3133
  @param ieio: Input/output type
3134
  @param ieargs: Input/output arguments
3135

3136
  """
3137
  assert mode in (constants.IEM_IMPORT, constants.IEM_EXPORT)
3138

    
3139
  env = None
3140
  prefix = None
3141
  suffix = None
3142
  exp_size = None
3143

    
3144
  if ieio == constants.IEIO_FILE:
3145
    (filename, ) = ieargs
3146

    
3147
    if not utils.IsNormAbsPath(filename):
3148
      _Fail("Path '%s' is not normalized or absolute", filename)
3149

    
3150
    real_filename = os.path.realpath(filename)
3151
    directory = os.path.dirname(real_filename)
3152

    
3153
    if not utils.IsBelowDir(constants.EXPORT_DIR, real_filename):
3154
      _Fail("File '%s' is not under exports directory '%s': %s",
3155
            filename, constants.EXPORT_DIR, real_filename)
3156

    
3157
    # Create directory
3158
    utils.Makedirs(directory, mode=0750)
3159

    
3160
    quoted_filename = utils.ShellQuote(filename)
3161

    
3162
    if mode == constants.IEM_IMPORT:
3163
      suffix = "> %s" % quoted_filename
3164
    elif mode == constants.IEM_EXPORT:
3165
      suffix = "< %s" % quoted_filename
3166

    
3167
      # Retrieve file size
3168
      try:
3169
        st = os.stat(filename)
3170
      except EnvironmentError, err:
3171
        logging.error("Can't stat(2) %s: %s", filename, err)
3172
      else:
3173
        exp_size = utils.BytesToMebibyte(st.st_size)
3174

    
3175
  elif ieio == constants.IEIO_RAW_DISK:
3176
    (disk, ) = ieargs
3177

    
3178
    real_disk = _OpenRealBD(disk)
3179

    
3180
    if mode == constants.IEM_IMPORT:
3181
      # we set here a smaller block size as, due to transport buffering, more
3182
      # than 64-128k will mostly ignored; we use nocreat to fail if the device
3183
      # is not already there or we pass a wrong path; we use notrunc to no
3184
      # attempt truncate on an LV device; we use oflag=dsync to not buffer too
3185
      # much memory; this means that at best, we flush every 64k, which will
3186
      # not be very fast
3187
      suffix = utils.BuildShellCmd(("| dd of=%s conv=nocreat,notrunc"
3188
                                    " bs=%s oflag=dsync"),
3189
                                    real_disk.dev_path,
3190
                                    str(64 * 1024))
3191

    
3192
    elif mode == constants.IEM_EXPORT:
3193
      # the block size on the read dd is 1MiB to match our units
3194
      prefix = utils.BuildShellCmd("dd if=%s bs=%s count=%s |",
3195
                                   real_disk.dev_path,
3196
                                   str(1024 * 1024), # 1 MB
3197
                                   str(disk.size))
3198
      exp_size = disk.size
3199

    
3200
  elif ieio == constants.IEIO_SCRIPT:
3201
    (disk, disk_index, ) = ieargs
3202

    
3203
    assert isinstance(disk_index, (int, long))
3204

    
3205
    real_disk = _OpenRealBD(disk)
3206

    
3207
    inst_os = OSFromDisk(instance.os)
3208
    env = OSEnvironment(instance, inst_os)
3209

    
3210
    if mode == constants.IEM_IMPORT:
3211
      env["IMPORT_DEVICE"] = env["DISK_%d_PATH" % disk_index]
3212
      env["IMPORT_INDEX"] = str(disk_index)
3213
      script = inst_os.import_script
3214

    
3215
    elif mode == constants.IEM_EXPORT:
3216
      env["EXPORT_DEVICE"] = real_disk.dev_path
3217
      env["EXPORT_INDEX"] = str(disk_index)
3218
      script = inst_os.export_script
3219

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

    
3223
    if mode == constants.IEM_IMPORT:
3224
      suffix = "| %s" % script_cmd
3225

    
3226
    elif mode == constants.IEM_EXPORT:
3227
      prefix = "%s |" % script_cmd
3228

    
3229
    # Let script predict size
3230
    exp_size = constants.IE_CUSTOM_SIZE
3231

    
3232
  else:
3233
    _Fail("Invalid %s I/O mode %r", mode, ieio)
3234

    
3235
  return (env, prefix, suffix, exp_size)
3236

    
3237

    
3238
def _CreateImportExportStatusDir(prefix):
3239
  """Creates status directory for import/export.
3240

3241
  """
3242
  return tempfile.mkdtemp(dir=constants.IMPORT_EXPORT_DIR,
3243
                          prefix=("%s-%s-" %
3244
                                  (prefix, utils.TimestampForFilename())))
3245

    
3246

    
3247
def StartImportExportDaemon(mode, opts, host, port, instance, component,
3248
                            ieio, ieioargs):
3249
  """Starts an import or export daemon.
3250

3251
  @param mode: Import/output mode
3252
  @type opts: L{objects.ImportExportOptions}
3253
  @param opts: Daemon options
3254
  @type host: string
3255
  @param host: Remote host for export (None for import)
3256
  @type port: int
3257
  @param port: Remote port for export (None for import)
3258
  @type instance: L{objects.Instance}
3259
  @param instance: Instance object
3260
  @type component: string
3261
  @param component: which part of the instance is transferred now,
3262
      e.g. 'disk/0'
3263
  @param ieio: Input/output type
3264
  @param ieioargs: Input/output arguments
3265

3266
  """
3267
  if mode == constants.IEM_IMPORT:
3268
    prefix = "import"
3269

    
3270
    if not (host is None and port is None):
3271
      _Fail("Can not specify host or port on import")
3272

    
3273
  elif mode == constants.IEM_EXPORT:
3274
    prefix = "export"
3275

    
3276
    if host is None or port is None:
3277
      _Fail("Host and port must be specified for an export")
3278

    
3279
  else:
3280
    _Fail("Invalid mode %r", mode)
3281

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

    
3285
  (cmd_env, cmd_prefix, cmd_suffix, exp_size) = \
3286
    _GetImportExportIoCommand(instance, mode, ieio, ieioargs)
3287

    
3288
  if opts.key_name is None:
3289
    # Use server.pem
3290
    key_path = constants.NODED_CERT_FILE
3291
    cert_path = constants.NODED_CERT_FILE
3292
    assert opts.ca_pem is None
3293
  else:
3294
    (_, key_path, cert_path) = _GetX509Filenames(constants.CRYPTO_KEYS_DIR,
3295
                                                 opts.key_name)
3296
    assert opts.ca_pem is not None
3297

    
3298
  for i in [key_path, cert_path]:
3299
    if not os.path.exists(i):
3300
      _Fail("File '%s' does not exist" % i)
3301

    
3302
  status_dir = _CreateImportExportStatusDir("%s-%s" % (prefix, component))
3303
  try:
3304
    status_file = utils.PathJoin(status_dir, _IES_STATUS_FILE)
3305
    pid_file = utils.PathJoin(status_dir, _IES_PID_FILE)
3306
    ca_file = utils.PathJoin(status_dir, _IES_CA_FILE)
3307

    
3308
    if opts.ca_pem is None:
3309
      # Use server.pem
3310
      ca = utils.ReadFile(constants.NODED_CERT_FILE)
3311
    else:
3312
      ca = opts.ca_pem
3313

    
3314
    # Write CA file
3315
    utils.WriteFile(ca_file, data=ca, mode=0400)
3316

    
3317
    cmd = [
3318
      constants.IMPORT_EXPORT_DAEMON,
3319
      status_file, mode,
3320
      "--key=%s" % key_path,
3321
      "--cert=%s" % cert_path,
3322
      "--ca=%s" % ca_file,
3323
      ]
3324

    
3325
    if host:
3326
      cmd.append("--host=%s" % host)
3327

    
3328
    if port:
3329
      cmd.append("--port=%s" % port)
3330

    
3331
    if opts.ipv6:
3332
      cmd.append("--ipv6")
3333
    else:
3334
      cmd.append("--ipv4")
3335

    
3336
    if opts.compress:
3337
      cmd.append("--compress=%s" % opts.compress)
3338

    
3339
    if opts.magic:
3340
      cmd.append("--magic=%s" % opts.magic)
3341

    
3342
    if exp_size is not None:
3343
      cmd.append("--expected-size=%s" % exp_size)
3344

    
3345
    if cmd_prefix:
3346
      cmd.append("--cmd-prefix=%s" % cmd_prefix)
3347

    
3348
    if cmd_suffix:
3349
      cmd.append("--cmd-suffix=%s" % cmd_suffix)
3350

    
3351
    if mode == constants.IEM_EXPORT:
3352
      # Retry connection a few times when connecting to remote peer
3353
      cmd.append("--connect-retries=%s" % constants.RIE_CONNECT_RETRIES)
3354
      cmd.append("--connect-timeout=%s" % constants.RIE_CONNECT_ATTEMPT_TIMEOUT)
3355
    elif opts.connect_timeout is not None:
3356
      assert mode == constants.IEM_IMPORT
3357
      # Overall timeout for establishing connection while listening
3358
      cmd.append("--connect-timeout=%s" % opts.connect_timeout)
3359

    
3360
    logfile = _InstanceLogName(prefix, instance.os, instance.name, component)
3361

    
3362
    # TODO: Once _InstanceLogName uses tempfile.mkstemp, StartDaemon has
3363
    # support for receiving a file descriptor for output
3364
    utils.StartDaemon(cmd, env=cmd_env, pidfile=pid_file,
3365
                      output=logfile)
3366

    
3367
    # The import/export name is simply the status directory name
3368
    return os.path.basename(status_dir)
3369

    
3370
  except Exception:
3371
    shutil.rmtree(status_dir, ignore_errors=True)
3372
    raise
3373

    
3374

    
3375
def GetImportExportStatus(names):
3376
  """Returns import/export daemon status.
3377

3378
  @type names: sequence
3379
  @param names: List of names
3380
  @rtype: List of dicts
3381
  @return: Returns a list of the state of each named import/export or None if a
3382
           status couldn't be read
3383

3384
  """
3385
  result = []
3386

    
3387
  for name in names:
3388
    status_file = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name,
3389
                                 _IES_STATUS_FILE)
3390

    
3391
    try:
3392
      data = utils.ReadFile(status_file)
3393
    except EnvironmentError, err:
3394
      if err.errno != errno.ENOENT:
3395
        raise
3396
      data = None
3397

    
3398
    if not data:
3399
      result.append(None)
3400
      continue
3401

    
3402
    result.append(serializer.LoadJson(data))
3403

    
3404
  return result
3405

    
3406

    
3407
def AbortImportExport(name):
3408
  """Sends SIGTERM to a running import/export daemon.
3409

3410
  """
3411
  logging.info("Abort import/export %s", name)
3412

    
3413
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3414
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3415

    
3416
  if pid:
3417
    logging.info("Import/export %s is running with PID %s, sending SIGTERM",
3418
                 name, pid)
3419
    utils.IgnoreProcessNotFound(os.kill, pid, signal.SIGTERM)
3420

    
3421

    
3422
def CleanupImportExport(name):
3423
  """Cleanup after an import or export.
3424

3425
  If the import/export daemon is still running it's killed. Afterwards the
3426
  whole status directory is removed.
3427

3428
  """
3429
  logging.info("Finalizing import/export %s", name)
3430

    
3431
  status_dir = utils.PathJoin(constants.IMPORT_EXPORT_DIR, name)
3432

    
3433
  pid = utils.ReadLockedPidFile(utils.PathJoin(status_dir, _IES_PID_FILE))
3434

    
3435
  if pid:
3436
    logging.info("Import/export %s is still running with PID %s",
3437
                 name, pid)
3438
    utils.KillProcess(pid, waitpid=False)
3439

    
3440
  shutil.rmtree(status_dir, ignore_errors=True)
3441

    
3442

    
3443
def _FindDisks(nodes_ip, disks):
3444
  """Sets the physical ID on disks and returns the block devices.
3445

3446
  """
3447
  # set the correct physical ID
3448
  my_name = netutils.Hostname.GetSysName()
3449
  for cf in disks:
3450
    cf.SetPhysicalID(my_name, nodes_ip)
3451

    
3452
  bdevs = []
3453

    
3454
  for cf in disks:
3455
    rd = _RecursiveFindBD(cf)
3456
    if rd is None:
3457
      _Fail("Can't find device %s", cf)
3458
    bdevs.append(rd)
3459
  return bdevs
3460

    
3461

    
3462
def DrbdDisconnectNet(nodes_ip, disks):
3463
  """Disconnects the network on a list of drbd devices.
3464

3465
  """
3466
  bdevs = _FindDisks(nodes_ip, disks)
3467

    
3468
  # disconnect disks
3469
  for rd in bdevs:
3470
    try:
3471
      rd.DisconnectNet()
3472
    except errors.BlockDeviceError, err:
3473
      _Fail("Can't change network configuration to standalone mode: %s",
3474
            err, exc=True)
3475

    
3476

    
3477
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
3478
  """Attaches the network on a list of drbd devices.
3479

3480
  """
3481
  bdevs = _FindDisks(nodes_ip, disks)
3482

    
3483
  if multimaster:
3484
    for idx, rd in enumerate(bdevs):
3485
      try:
3486
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
3487
      except EnvironmentError, err:
3488
        _Fail("Can't create symlink: %s", err)
3489
  # reconnect disks, switch to new master configuration and if
3490
  # needed primary mode
3491
  for rd in bdevs:
3492
    try:
3493
      rd.AttachNet(multimaster)
3494
    except errors.BlockDeviceError, err:
3495
      _Fail("Can't change network configuration: %s", err)
3496

    
3497
  # wait until the disks are connected; we need to retry the re-attach
3498
  # if the device becomes standalone, as this might happen if the one
3499
  # node disconnects and reconnects in a different mode before the
3500
  # other node reconnects; in this case, one or both of the nodes will
3501
  # decide it has wrong configuration and switch to standalone
3502

    
3503
  def _Attach():
3504
    all_connected = True
3505

    
3506
    for rd in bdevs:
3507
      stats = rd.GetProcStatus()
3508

    
3509
      all_connected = (all_connected and
3510
                       (stats.is_connected or stats.is_in_resync))
3511

    
3512
      if stats.is_standalone:
3513
        # peer had different config info and this node became
3514
        # standalone, even though this should not happen with the
3515
        # new staged way of changing disk configs
3516
        try:
3517
          rd.AttachNet(multimaster)
3518
        except errors.BlockDeviceError, err:
3519
          _Fail("Can't change network configuration: %s", err)
3520

    
3521
    if not all_connected:
3522
      raise utils.RetryAgain()
3523

    
3524
  try:
3525
    # Start with a delay of 100 miliseconds and go up to 5 seconds
3526
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
3527
  except utils.RetryTimeout:
3528
    _Fail("Timeout in disk reconnecting")
3529

    
3530
  if multimaster:
3531
    # change to primary mode
3532
    for rd in bdevs:
3533
      try:
3534
        rd.Open()
3535
      except errors.BlockDeviceError, err:
3536
        _Fail("Can't change to primary mode: %s", err)
3537

    
3538

    
3539
def DrbdWaitSync(nodes_ip, disks):
3540
  """Wait until DRBDs have synchronized.
3541

3542
  """
3543
  def _helper(rd):
3544
    stats = rd.GetProcStatus()
3545
    if not (stats.is_connected or stats.is_in_resync):
3546
      raise utils.RetryAgain()
3547
    return stats
3548

    
3549
  bdevs = _FindDisks(nodes_ip, disks)
3550

    
3551
  min_resync = 100
3552
  alldone = True
3553
  for rd in bdevs:
3554
    try:
3555
      # poll each second for 15 seconds
3556
      stats = utils.Retry(_helper, 1, 15, args=[rd])
3557
    except utils.RetryTimeout:
3558
      stats = rd.GetProcStatus()
3559
      # last check
3560
      if not (stats.is_connected or stats.is_in_resync):
3561
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
3562
    alldone = alldone and (not stats.is_in_resync)
3563
    if stats.sync_percent is not None:
3564
      min_resync = min(min_resync, stats.sync_percent)
3565

    
3566
  return (alldone, min_resync)
3567

    
3568

    
3569
def GetDrbdUsermodeHelper():
3570
  """Returns DRBD usermode helper currently configured.
3571

3572
  """
3573
  try:
3574
    return bdev.BaseDRBD.GetUsermodeHelper()
3575
  except errors.BlockDeviceError, err:
3576
    _Fail(str(err))
3577

    
3578

    
3579
def PowercycleNode(hypervisor_type):
3580
  """Hard-powercycle the node.
3581

3582
  Because we need to return first, and schedule the powercycle in the
3583
  background, we won't be able to report failures nicely.
3584

3585
  """
3586
  hyper = hypervisor.GetHypervisor(hypervisor_type)
3587
  try:
3588
    pid = os.fork()
3589
  except OSError:
3590
    # if we can't fork, we'll pretend that we're in the child process
3591
    pid = 0
3592
  if pid > 0:
3593
    return "Reboot scheduled in 5 seconds"
3594
  # ensure the child is running on ram
3595
  try:
3596
    utils.Mlockall()
3597
  except Exception: # pylint: disable=W0703
3598
    pass
3599
  time.sleep(5)
3600
  hyper.PowercycleNode()
3601

    
3602

    
3603
class HooksRunner(object):
3604
  """Hook runner.
3605

3606
  This class is instantiated on the node side (ganeti-noded) and not
3607
  on the master side.
3608

3609
  """
3610
  def __init__(self, hooks_base_dir=None):
3611
    """Constructor for hooks runner.
3612

3613
    @type hooks_base_dir: str or None
3614
    @param hooks_base_dir: if not None, this overrides the
3615
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
3616

3617
    """
3618
    if hooks_base_dir is None:
3619
      hooks_base_dir = constants.HOOKS_BASE_DIR
3620
    # yeah, _BASE_DIR is not valid for attributes, we use it like a
3621
    # constant
3622
    self._BASE_DIR = hooks_base_dir # pylint: disable=C0103
3623

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

3627
    """
3628
    assert len(node_list) == 1
3629
    node = node_list[0]
3630
    _, myself = ssconf.GetMasterAndMyself()
3631
    assert node == myself
3632

    
3633
    results = self.RunHooks(hpath, phase, env)
3634

    
3635
    # Return values in the form expected by HooksMaster
3636
    return {node: (None, False, results)}
3637

    
3638
  def RunHooks(self, hpath, phase, env):
3639
    """Run the scripts in the hooks directory.
3640

3641
    @type hpath: str
3642
    @param hpath: the path to the hooks directory which
3643
        holds the scripts
3644
    @type phase: str
3645
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
3646
        L{constants.HOOKS_PHASE_POST}
3647
    @type env: dict
3648
    @param env: dictionary with the environment for the hook
3649
    @rtype: list
3650
    @return: list of 3-element tuples:
3651
      - script path
3652
      - script result, either L{constants.HKR_SUCCESS} or
3653
        L{constants.HKR_FAIL}
3654
      - output of the script
3655

3656
    @raise errors.ProgrammerError: for invalid input
3657
        parameters
3658

3659
    """
3660
    if phase == constants.HOOKS_PHASE_PRE:
3661
      suffix = "pre"
3662
    elif phase == constants.HOOKS_PHASE_POST:
3663
      suffix = "post"
3664
    else:
3665
      _Fail("Unknown hooks phase '%s'", phase)
3666

    
3667
    subdir = "%s-%s.d" % (hpath, suffix)
3668
    dir_name = utils.PathJoin(self._BASE_DIR, subdir)
3669

    
3670
    results = []
3671

    
3672
    if not os.path.isdir(dir_name):
3673
      # for non-existing/non-dirs, we simply exit instead of logging a
3674
      # warning at every operation
3675
      return results
3676

    
3677
    runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
3678

    
3679
    for (relname, relstatus, runresult)  in runparts_results:
3680
      if relstatus == constants.RUNPARTS_SKIP:
3681
        rrval = constants.HKR_SKIP
3682
        output = ""
3683
      elif relstatus == constants.RUNPARTS_ERR:
3684
        rrval = constants.HKR_FAIL
3685
        output = "Hook script execution error: %s" % runresult
3686
      elif relstatus == constants.RUNPARTS_RUN:
3687
        if runresult.failed:
3688
          rrval = constants.HKR_FAIL
3689
        else:
3690
          rrval = constants.HKR_SUCCESS
3691
        output = utils.SafeEncode(runresult.output.strip())
3692
      results.append(("%s/%s" % (subdir, relname), rrval, output))
3693

    
3694
    return results
3695

    
3696

    
3697
class IAllocatorRunner(object):
3698
  """IAllocator runner.
3699

3700
  This class is instantiated on the node side (ganeti-noded) and not on
3701
  the master side.
3702

3703
  """
3704
  @staticmethod
3705
  def Run(name, idata):
3706
    """Run an iallocator script.
3707

3708
    @type name: str
3709
    @param name: the iallocator script name
3710
    @type idata: str
3711
    @param idata: the allocator input data
3712

3713
    @rtype: tuple
3714
    @return: two element tuple of:
3715
       - status
3716
       - either error message or stdout of allocator (for success)
3717

3718
    """
3719
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
3720
                                  os.path.isfile)
3721
    if alloc_script is None:
3722
      _Fail("iallocator module '%s' not found in the search path", name)
3723

    
3724
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
3725
    try:
3726
      os.write(fd, idata)
3727
      os.close(fd)
3728
      result = utils.RunCmd([alloc_script, fin_name])
3729
      if result.failed:
3730
        _Fail("iallocator module '%s' failed: %s, output '%s'",
3731
              name, result.fail_reason, result.output)
3732
    finally:
3733
      os.unlink(fin_name)
3734

    
3735
    return result.stdout
3736

    
3737

    
3738
class DevCacheManager(object):
3739
  """Simple class for managing a cache of block device information.
3740

3741
  """
3742
  _DEV_PREFIX = "/dev/"
3743
  _ROOT_DIR = constants.BDEV_CACHE_DIR
3744

    
3745
  @classmethod
3746
  def _ConvertPath(cls, dev_path):
3747
    """Converts a /dev/name path to the cache file name.
3748

3749
    This replaces slashes with underscores and strips the /dev
3750
    prefix. It then returns the full path to the cache file.
3751

3752
    @type dev_path: str
3753
    @param dev_path: the C{/dev/} path name
3754
    @rtype: str
3755
    @return: the converted path name
3756

3757
    """
3758
    if dev_path.startswith(cls._DEV_PREFIX):
3759
      dev_path = dev_path[len(cls._DEV_PREFIX):]
3760
    dev_path = dev_path.replace("/", "_")
3761
    fpath = utils.PathJoin(cls._ROOT_DIR, "bdev_%s" % dev_path)
3762
    return fpath
3763

    
3764
  @classmethod
3765
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
3766
    """Updates the cache information for a given device.
3767

3768
    @type dev_path: str
3769
    @param dev_path: the pathname of the device
3770
    @type owner: str
3771
    @param owner: the owner (instance name) of the device
3772
    @type on_primary: bool
3773
    @param on_primary: whether this is the primary
3774
        node nor not
3775
    @type iv_name: str
3776
    @param iv_name: the instance-visible name of the
3777
        device, as in objects.Disk.iv_name
3778

3779
    @rtype: None
3780

3781
    """
3782
    if dev_path is None:
3783
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
3784
      return
3785
    fpath = cls._ConvertPath(dev_path)
3786
    if on_primary:
3787
      state = "primary"
3788
    else:
3789
      state = "secondary"
3790
    if iv_name is None:
3791
      iv_name = "not_visible"
3792
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
3793
    try:
3794
      utils.WriteFile(fpath, data=fdata)
3795
    except EnvironmentError, err:
3796
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
3797

    
3798
  @classmethod
3799
  def RemoveCache(cls, dev_path):
3800
    """Remove data for a dev_path.
3801

3802
    This is just a wrapper over L{utils.io.RemoveFile} with a converted
3803
    path name and logging.
3804

3805
    @type dev_path: str
3806
    @param dev_path: the pathname of the device
3807

3808
    @rtype: None
3809

3810
    """
3811
    if dev_path is None:
3812
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
3813
      return
3814
    fpath = cls._ConvertPath(dev_path)
3815
    try:
3816
      utils.RemoveFile(fpath)
3817
    except EnvironmentError, err:
3818
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)