Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 1f864b60

History | View | Annotate | Download (86.7 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007 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

27
"""
28

    
29
# pylint: disable-msg=E1103
30

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

    
35

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

    
50
from ganeti import errors
51
from ganeti import utils
52
from ganeti import ssh
53
from ganeti import hypervisor
54
from ganeti import constants
55
from ganeti import bdev
56
from ganeti import objects
57
from ganeti import ssconf
58

    
59

    
60
_BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id"
61

    
62

    
63
class RPCFail(Exception):
64
  """Class denoting RPC failure.
65

66
  Its argument is the error message.
67

68
  """
69

    
70

    
71
def _Fail(msg, *args, **kwargs):
72
  """Log an error and the raise an RPCFail exception.
73

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

79
  @type msg: string
80
  @param msg: the text of the exception
81
  @raise RPCFail
82

83
  """
84
  if args:
85
    msg = msg % args
86
  if "log" not in kwargs or kwargs["log"]: # if we should log this error
87
    if "exc" in kwargs and kwargs["exc"]:
88
      logging.exception(msg)
89
    else:
90
      logging.error(msg)
91
  raise RPCFail(msg)
92

    
93

    
94
def _GetConfig():
95
  """Simple wrapper to return a SimpleStore.
96

97
  @rtype: L{ssconf.SimpleStore}
98
  @return: a SimpleStore instance
99

100
  """
101
  return ssconf.SimpleStore()
102

    
103

    
104
def _GetSshRunner(cluster_name):
105
  """Simple wrapper to return an SshRunner.
106

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

113
  """
114
  return ssh.SshRunner(cluster_name)
115

    
116

    
117
def _Decompress(data):
118
  """Unpacks data compressed by the RPC client.
119

120
  @type data: list or tuple
121
  @param data: Data sent by RPC client
122
  @rtype: str
123
  @return: Decompressed data
124

125
  """
126
  assert isinstance(data, (list, tuple))
127
  assert len(data) == 2
128
  (encoding, content) = data
129
  if encoding == constants.RPC_ENCODING_NONE:
130
    return content
131
  elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
132
    return zlib.decompress(base64.b64decode(content))
133
  else:
134
    raise AssertionError("Unknown data encoding")
135

    
136

    
137
def _CleanDirectory(path, exclude=None):
138
  """Removes all regular files in a directory.
139

140
  @type path: str
141
  @param path: the directory to clean
142
  @type exclude: list
143
  @param exclude: list of files to be excluded, defaults
144
      to the empty list
145

146
  """
147
  if not os.path.isdir(path):
148
    return
149
  if exclude is None:
150
    exclude = []
151
  else:
152
    # Normalize excluded paths
153
    exclude = [os.path.normpath(i) for i in exclude]
154

    
155
  for rel_name in utils.ListVisibleFiles(path):
156
    full_name = os.path.normpath(os.path.join(path, rel_name))
157
    if full_name in exclude:
158
      continue
159
    if os.path.isfile(full_name) and not os.path.islink(full_name):
160
      utils.RemoveFile(full_name)
161

    
162

    
163
def _BuildUploadFileList():
164
  """Build the list of allowed upload files.
165

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

168
  """
169
  allowed_files = set([
170
    constants.CLUSTER_CONF_FILE,
171
    constants.ETC_HOSTS,
172
    constants.SSH_KNOWN_HOSTS_FILE,
173
    constants.VNC_PASSWORD_FILE,
174
    constants.RAPI_CERT_FILE,
175
    constants.RAPI_USERS_FILE,
176
    constants.HMAC_CLUSTER_KEY,
177
    ])
178

    
179
  for hv_name in constants.HYPER_TYPES:
180
    hv_class = hypervisor.GetHypervisorClass(hv_name)
181
    allowed_files.update(hv_class.GetAncillaryFiles())
182

    
183
  return frozenset(allowed_files)
184

    
185

    
186
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
187

    
188

    
189
def JobQueuePurge():
190
  """Removes job queue files and archived jobs.
191

192
  @rtype: tuple
193
  @return: True, None
194

195
  """
196
  _CleanDirectory(constants.QUEUE_DIR, exclude=[constants.JOB_QUEUE_LOCK_FILE])
197
  _CleanDirectory(constants.JOB_QUEUE_ARCHIVE_DIR)
198

    
199

    
200
def GetMasterInfo():
201
  """Returns master information.
202

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

206
  @rtype: tuple
207
  @return: master_netdev, master_ip, master_name
208
  @raise RPCFail: in case of errors
209

210
  """
211
  try:
212
    cfg = _GetConfig()
213
    master_netdev = cfg.GetMasterNetdev()
214
    master_ip = cfg.GetMasterIP()
215
    master_node = cfg.GetMasterNode()
216
  except errors.ConfigurationError, err:
217
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
218
  return (master_netdev, master_ip, master_node)
219

    
220

    
221
def StartMaster(start_daemons, no_voting):
222
  """Activate local node as master node.
223

224
  The function will always try activate the IP address of the master
225
  (unless someone else has it). It will also start the master daemons,
226
  based on the start_daemons parameter.
227

228
  @type start_daemons: boolean
229
  @param start_daemons: whether to also start the master
230
      daemons (ganeti-masterd and ganeti-rapi)
231
  @type no_voting: boolean
232
  @param no_voting: whether to start ganeti-masterd without a node vote
233
      (if start_daemons is True), but still non-interactively
234
  @rtype: None
235

236
  """
237
  # GetMasterInfo will raise an exception if not able to return data
238
  master_netdev, master_ip, _ = GetMasterInfo()
239

    
240
  err_msgs = []
241
  if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
242
    if utils.OwnIpAddress(master_ip):
243
      # we already have the ip:
244
      logging.debug("Master IP already configured, doing nothing")
245
    else:
246
      msg = "Someone else has the master ip, not activating"
247
      logging.error(msg)
248
      err_msgs.append(msg)
249
  else:
250
    result = utils.RunCmd(["ip", "address", "add", "%s/32" % master_ip,
251
                           "dev", master_netdev, "label",
252
                           "%s:0" % master_netdev])
253
    if result.failed:
254
      msg = "Can't activate master IP: %s" % result.output
255
      logging.error(msg)
256
      err_msgs.append(msg)
257

    
258
    result = utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev,
259
                           "-s", master_ip, master_ip])
260
    # we'll ignore the exit code of arping
261

    
262
  # and now start the master and rapi daemons
263
  if start_daemons:
264
    if no_voting:
265
      masterd_args = "--no-voting --yes-do-it"
266
    else:
267
      masterd_args = ""
268

    
269
    env = {
270
      "EXTRA_MASTERD_ARGS": masterd_args,
271
      }
272

    
273
    result = utils.RunCmd([constants.DAEMON_UTIL, "start-master"], env=env)
274
    if result.failed:
275
      msg = "Can't start Ganeti master: %s" % result.output
276
      logging.error(msg)
277
      err_msgs.append(msg)
278

    
279
  if err_msgs:
280
    _Fail("; ".join(err_msgs))
281

    
282

    
283
def StopMaster(stop_daemons):
284
  """Deactivate this node as master.
285

286
  The function will always try to deactivate the IP address of the
287
  master. It will also stop the master daemons depending on the
288
  stop_daemons parameter.
289

290
  @type stop_daemons: boolean
291
  @param stop_daemons: whether to also stop the master daemons
292
      (ganeti-masterd and ganeti-rapi)
293
  @rtype: None
294

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

    
299
  # GetMasterInfo will raise an exception if not able to return data
300
  master_netdev, master_ip, _ = GetMasterInfo()
301

    
302
  result = utils.RunCmd(["ip", "address", "del", "%s/32" % master_ip,
303
                         "dev", master_netdev])
304
  if result.failed:
305
    logging.error("Can't remove the master IP, error: %s", result.output)
306
    # but otherwise ignore the failure
307

    
308
  if stop_daemons:
309
    result = utils.RunCmd([constants.DAEMON_UTIL, "stop-master"])
310
    if result.failed:
311
      logging.error("Could not stop Ganeti master, command %s had exitcode %s"
312
                    " and error %s",
313
                    result.cmd, result.exit_code, result.output)
314

    
315

    
316
def AddNode(dsa, dsapub, rsa, rsapub, sshkey, sshpub):
317
  """Joins this node to the cluster.
318

319
  This does the following:
320
      - updates the hostkeys of the machine (rsa and dsa)
321
      - adds the ssh private key to the user
322
      - adds the ssh public key to the users' authorized_keys file
323

324
  @type dsa: str
325
  @param dsa: the DSA private key to write
326
  @type dsapub: str
327
  @param dsapub: the DSA public key to write
328
  @type rsa: str
329
  @param rsa: the RSA private key to write
330
  @type rsapub: str
331
  @param rsapub: the RSA public key to write
332
  @type sshkey: str
333
  @param sshkey: the SSH private key to write
334
  @type sshpub: str
335
  @param sshpub: the SSH public key to write
336
  @rtype: boolean
337
  @return: the success of the operation
338

339
  """
340
  sshd_keys =  [(constants.SSH_HOST_RSA_PRIV, rsa, 0600),
341
                (constants.SSH_HOST_RSA_PUB, rsapub, 0644),
342
                (constants.SSH_HOST_DSA_PRIV, dsa, 0600),
343
                (constants.SSH_HOST_DSA_PUB, dsapub, 0644)]
344
  for name, content, mode in sshd_keys:
345
    utils.WriteFile(name, data=content, mode=mode)
346

    
347
  try:
348
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS,
349
                                                    mkdir=True)
350
  except errors.OpExecError, err:
351
    _Fail("Error while processing user ssh files: %s", err, exc=True)
352

    
353
  for name, content in [(priv_key, sshkey), (pub_key, sshpub)]:
354
    utils.WriteFile(name, data=content, mode=0600)
355

    
356
  utils.AddAuthorizedKey(auth_keys, sshpub)
357

    
358
  result = utils.RunCmd([constants.DAEMON_UTIL, "reload-ssh-keys"])
359
  if result.failed:
360
    _Fail("Unable to reload SSH keys (command %r, exit code %s, output %r)",
361
          result.cmd, result.exit_code, result.output)
362

    
363

    
364
def LeaveCluster(modify_ssh_setup):
365
  """Cleans up and remove the current node.
366

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

370
  If processing is successful, then it raises an
371
  L{errors.QuitGanetiException} which is used as a special case to
372
  shutdown the node daemon.
373

374
  @param modify_ssh_setup: boolean
375

376
  """
377
  _CleanDirectory(constants.DATA_DIR)
378
  JobQueuePurge()
379

    
380
  if modify_ssh_setup:
381
    try:
382
      priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
383

    
384
      utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
385

    
386
      utils.RemoveFile(priv_key)
387
      utils.RemoveFile(pub_key)
388
    except errors.OpExecError:
389
      logging.exception("Error while processing ssh files")
390

    
391
  try:
392
    utils.RemoveFile(constants.HMAC_CLUSTER_KEY)
393
    utils.RemoveFile(constants.RAPI_CERT_FILE)
394
    utils.RemoveFile(constants.SSL_CERT_FILE)
395
  except:
396
    logging.exception("Error while removing cluster secrets")
397

    
398
  result = utils.RunCmd([constants.DAEMON_UTIL, "stop", constants.CONFD])
399
  if result.failed:
400
    logging.error("Command %s failed with exitcode %s and error %s",
401
                  result.cmd, result.exit_code, result.output)
402

    
403
  # Raise a custom exception (handled in ganeti-noded)
404
  raise errors.QuitGanetiException(True, 'Shutdown scheduled')
405

    
406

    
407
def GetNodeInfo(vgname, hypervisor_type):
408
  """Gives back a hash with different information about the node.
409

410
  @type vgname: C{string}
411
  @param vgname: the name of the volume group to ask for disk space information
412
  @type hypervisor_type: C{str}
413
  @param hypervisor_type: the name of the hypervisor to ask for
414
      memory information
415
  @rtype: C{dict}
416
  @return: dictionary with the following keys:
417
      - vg_size is the size of the configured volume group in MiB
418
      - vg_free is the free size of the volume group in MiB
419
      - memory_dom0 is the memory allocated for domain0 in MiB
420
      - memory_free is the currently available (free) ram in MiB
421
      - memory_total is the total number of ram in MiB
422

423
  """
424
  outputarray = {}
425
  vginfo = _GetVGInfo(vgname)
426
  outputarray['vg_size'] = vginfo['vg_size']
427
  outputarray['vg_free'] = vginfo['vg_free']
428

    
429
  hyper = hypervisor.GetHypervisor(hypervisor_type)
430
  hyp_info = hyper.GetNodeInfo()
431
  if hyp_info is not None:
432
    outputarray.update(hyp_info)
433

    
434
  outputarray["bootid"] = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
435

    
436
  return outputarray
437

    
438

    
439
def VerifyNode(what, cluster_name):
440
  """Verify the status of the local node.
441

442
  Based on the input L{what} parameter, various checks are done on the
443
  local node.
444

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

448
  If the I{nodelist} key is present, we check that we have
449
  connectivity via ssh with the target nodes (and check the hostname
450
  report).
451

452
  If the I{node-net-test} key is present, we check that we have
453
  connectivity to the given nodes via both primary IP and, if
454
  applicable, secondary IPs.
455

456
  @type what: C{dict}
457
  @param what: a dictionary of things to check:
458
      - filelist: list of files for which to compute checksums
459
      - nodelist: list of nodes we should check ssh communication with
460
      - node-net-test: list of nodes we should check node daemon port
461
        connectivity with
462
      - hypervisor: list with hypervisors to run the verify for
463
  @rtype: dict
464
  @return: a dictionary with the same keys as the input dict, and
465
      values representing the result of the checks
466

467
  """
468
  result = {}
469

    
470
  if constants.NV_HYPERVISOR in what:
471
    result[constants.NV_HYPERVISOR] = tmp = {}
472
    for hv_name in what[constants.NV_HYPERVISOR]:
473
      tmp[hv_name] = hypervisor.GetHypervisor(hv_name).Verify()
474

    
475
  if constants.NV_FILELIST in what:
476
    result[constants.NV_FILELIST] = utils.FingerprintFiles(
477
      what[constants.NV_FILELIST])
478

    
479
  if constants.NV_NODELIST in what:
480
    result[constants.NV_NODELIST] = tmp = {}
481
    random.shuffle(what[constants.NV_NODELIST])
482
    for node in what[constants.NV_NODELIST]:
483
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
484
      if not success:
485
        tmp[node] = message
486

    
487
  if constants.NV_NODENETTEST in what:
488
    result[constants.NV_NODENETTEST] = tmp = {}
489
    my_name = utils.HostInfo().name
490
    my_pip = my_sip = None
491
    for name, pip, sip in what[constants.NV_NODENETTEST]:
492
      if name == my_name:
493
        my_pip = pip
494
        my_sip = sip
495
        break
496
    if not my_pip:
497
      tmp[my_name] = ("Can't find my own primary/secondary IP"
498
                      " in the node list")
499
    else:
500
      port = utils.GetDaemonPort(constants.NODED)
501
      for name, pip, sip in what[constants.NV_NODENETTEST]:
502
        fail = []
503
        if not utils.TcpPing(pip, port, source=my_pip):
504
          fail.append("primary")
505
        if sip != pip:
506
          if not utils.TcpPing(sip, port, source=my_sip):
507
            fail.append("secondary")
508
        if fail:
509
          tmp[name] = ("failure using the %s interface(s)" %
510
                       " and ".join(fail))
511

    
512
  if constants.NV_LVLIST in what:
513
    result[constants.NV_LVLIST] = GetVolumeList(what[constants.NV_LVLIST])
514

    
515
  if constants.NV_INSTANCELIST in what:
516
    result[constants.NV_INSTANCELIST] = GetInstanceList(
517
      what[constants.NV_INSTANCELIST])
518

    
519
  if constants.NV_VGLIST in what:
520
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
521

    
522
  if constants.NV_PVLIST in what:
523
    result[constants.NV_PVLIST] = \
524
      bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
525
                                   filter_allocatable=False)
526

    
527
  if constants.NV_VERSION in what:
528
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
529
                                    constants.RELEASE_VERSION)
530

    
531
  if constants.NV_HVINFO in what:
532
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
533
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
534

    
535
  if constants.NV_DRBDLIST in what:
536
    try:
537
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
538
    except errors.BlockDeviceError, err:
539
      logging.warning("Can't get used minors list", exc_info=True)
540
      used_minors = str(err)
541
    result[constants.NV_DRBDLIST] = used_minors
542

    
543
  if constants.NV_NODESETUP in what:
544
    result[constants.NV_NODESETUP] = tmpr = []
545
    if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
546
      tmpr.append("The sysfs filesytem doesn't seem to be mounted"
547
                  " under /sys, missing required directories /sys/block"
548
                  " and /sys/class/net")
549
    if (not os.path.isdir("/proc/sys") or
550
        not os.path.isfile("/proc/sysrq-trigger")):
551
      tmpr.append("The procfs filesystem doesn't seem to be mounted"
552
                  " under /proc, missing required directory /proc/sys and"
553
                  " the file /proc/sysrq-trigger")
554
  return result
555

    
556

    
557
def GetVolumeList(vg_name):
558
  """Compute list of logical volumes and their size.
559

560
  @type vg_name: str
561
  @param vg_name: the volume group whose LVs we should list
562
  @rtype: dict
563
  @return:
564
      dictionary of all partions (key) with value being a tuple of
565
      their size (in MiB), inactive and online status::
566

567
        {'test1': ('20.06', True, True)}
568

569
      in case of errors, a string is returned with the error
570
      details.
571

572
  """
573
  lvs = {}
574
  sep = '|'
575
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
576
                         "--separator=%s" % sep,
577
                         "-olv_name,lv_size,lv_attr", vg_name])
578
  if result.failed:
579
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
580

    
581
  valid_line_re = re.compile("^ *([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
582
  for line in result.stdout.splitlines():
583
    line = line.strip()
584
    match = valid_line_re.match(line)
585
    if not match:
586
      logging.error("Invalid line returned from lvs output: '%s'", line)
587
      continue
588
    name, size, attr = match.groups()
589
    inactive = attr[4] == '-'
590
    online = attr[5] == 'o'
591
    virtual = attr[0] == 'v'
592
    if virtual:
593
      # we don't want to report such volumes as existing, since they
594
      # don't really hold data
595
      continue
596
    lvs[name] = (size, inactive, online)
597

    
598
  return lvs
599

    
600

    
601
def ListVolumeGroups():
602
  """List the volume groups and their size.
603

604
  @rtype: dict
605
  @return: dictionary with keys volume name and values the
606
      size of the volume
607

608
  """
609
  return utils.ListVolumeGroups()
610

    
611

    
612
def NodeVolumes():
613
  """List all volumes on this node.
614

615
  @rtype: list
616
  @return:
617
    A list of dictionaries, each having four keys:
618
      - name: the logical volume name,
619
      - size: the size of the logical volume
620
      - dev: the physical device on which the LV lives
621
      - vg: the volume group to which it belongs
622

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

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

630
  """
631
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
632
                         "--separator=|",
633
                         "--options=lv_name,lv_size,devices,vg_name"])
634
  if result.failed:
635
    _Fail("Failed to list logical volumes, lvs output: %s",
636
          result.output)
637

    
638
  def parse_dev(dev):
639
    if '(' in dev:
640
      return dev.split('(')[0]
641
    else:
642
      return dev
643

    
644
  def map_line(line):
645
    return {
646
      'name': line[0].strip(),
647
      'size': line[1].strip(),
648
      'dev': parse_dev(line[2].strip()),
649
      'vg': line[3].strip(),
650
    }
651

    
652
  return [map_line(line.split('|')) for line in result.stdout.splitlines()
653
          if line.count('|') >= 3]
654

    
655

    
656
def BridgesExist(bridges_list):
657
  """Check if a list of bridges exist on the current node.
658

659
  @rtype: boolean
660
  @return: C{True} if all of them exist, C{False} otherwise
661

662
  """
663
  missing = []
664
  for bridge in bridges_list:
665
    if not utils.BridgeExists(bridge):
666
      missing.append(bridge)
667

    
668
  if missing:
669
    _Fail("Missing bridges %s", utils.CommaJoin(missing))
670

    
671

    
672
def GetInstanceList(hypervisor_list):
673
  """Provides a list of instances.
674

675
  @type hypervisor_list: list
676
  @param hypervisor_list: the list of hypervisors to query information
677

678
  @rtype: list
679
  @return: a list of all running instances on the current node
680
    - instance1.example.com
681
    - instance2.example.com
682

683
  """
684
  results = []
685
  for hname in hypervisor_list:
686
    try:
687
      names = hypervisor.GetHypervisor(hname).ListInstances()
688
      results.extend(names)
689
    except errors.HypervisorError, err:
690
      _Fail("Error enumerating instances (hypervisor %s): %s",
691
            hname, err, exc=True)
692

    
693
  return results
694

    
695

    
696
def GetInstanceInfo(instance, hname):
697
  """Gives back the information about an instance as a dictionary.
698

699
  @type instance: string
700
  @param instance: the instance name
701
  @type hname: string
702
  @param hname: the hypervisor type of the instance
703

704
  @rtype: dict
705
  @return: dictionary with the following keys:
706
      - memory: memory size of instance (int)
707
      - state: xen state of instance (string)
708
      - time: cpu time of instance (float)
709

710
  """
711
  output = {}
712

    
713
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
714
  if iinfo is not None:
715
    output['memory'] = iinfo[2]
716
    output['state'] = iinfo[4]
717
    output['time'] = iinfo[5]
718

    
719
  return output
720

    
721

    
722
def GetInstanceMigratable(instance):
723
  """Gives whether an instance can be migrated.
724

725
  @type instance: L{objects.Instance}
726
  @param instance: object representing the instance to be checked.
727

728
  @rtype: tuple
729
  @return: tuple of (result, description) where:
730
      - result: whether the instance can be migrated or not
731
      - description: a description of the issue, if relevant
732

733
  """
734
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
735
  iname = instance.name
736
  if iname not in hyper.ListInstances():
737
    _Fail("Instance %s is not running", iname)
738

    
739
  for idx in range(len(instance.disks)):
740
    link_name = _GetBlockDevSymlinkPath(iname, idx)
741
    if not os.path.islink(link_name):
742
      _Fail("Instance %s was not restarted since ganeti 1.2.5", iname)
743

    
744

    
745
def GetAllInstancesInfo(hypervisor_list):
746
  """Gather data about all instances.
747

748
  This is the equivalent of L{GetInstanceInfo}, except that it
749
  computes data for all instances at once, thus being faster if one
750
  needs data about more than one instance.
751

752
  @type hypervisor_list: list
753
  @param hypervisor_list: list of hypervisors to query for instance data
754

755
  @rtype: dict
756
  @return: dictionary of instance: data, with data having the following keys:
757
      - memory: memory size of instance (int)
758
      - state: xen state of instance (string)
759
      - time: cpu time of instance (float)
760
      - vcpus: the number of vcpus
761

762
  """
763
  output = {}
764

    
765
  for hname in hypervisor_list:
766
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
767
    if iinfo:
768
      for name, _, memory, vcpus, state, times in iinfo:
769
        value = {
770
          'memory': memory,
771
          'vcpus': vcpus,
772
          'state': state,
773
          'time': times,
774
          }
775
        if name in output:
776
          # we only check static parameters, like memory and vcpus,
777
          # and not state and time which can change between the
778
          # invocations of the different hypervisors
779
          for key in 'memory', 'vcpus':
780
            if value[key] != output[name][key]:
781
              _Fail("Instance %s is running twice"
782
                    " with different parameters", name)
783
        output[name] = value
784

    
785
  return output
786

    
787

    
788
def InstanceOsAdd(instance, reinstall):
789
  """Add an OS to an instance.
790

791
  @type instance: L{objects.Instance}
792
  @param instance: Instance whose OS is to be installed
793
  @type reinstall: boolean
794
  @param reinstall: whether this is an instance reinstall
795
  @rtype: None
796

797
  """
798
  inst_os = OSFromDisk(instance.os)
799

    
800
  create_env = OSEnvironment(instance, inst_os)
801
  if reinstall:
802
    create_env['INSTANCE_REINSTALL'] = "1"
803

    
804
  logfile = "%s/add-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
805
                                     instance.name, int(time.time()))
806

    
807
  result = utils.RunCmd([inst_os.create_script], env=create_env,
808
                        cwd=inst_os.path, output=logfile,)
809
  if result.failed:
810
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
811
                  " output: %s", result.cmd, result.fail_reason, logfile,
812
                  result.output)
813
    lines = [utils.SafeEncode(val)
814
             for val in utils.TailFile(logfile, lines=20)]
815
    _Fail("OS create script failed (%s), last lines in the"
816
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
817

    
818

    
819
def RunRenameInstance(instance, old_name):
820
  """Run the OS rename script for an instance.
821

822
  @type instance: L{objects.Instance}
823
  @param instance: Instance whose OS is to be installed
824
  @type old_name: string
825
  @param old_name: previous instance name
826
  @rtype: boolean
827
  @return: the success of the operation
828

829
  """
830
  inst_os = OSFromDisk(instance.os)
831

    
832
  rename_env = OSEnvironment(instance, inst_os)
833
  rename_env['OLD_INSTANCE_NAME'] = old_name
834

    
835
  logfile = "%s/rename-%s-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
836
                                           old_name,
837
                                           instance.name, int(time.time()))
838

    
839
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
840
                        cwd=inst_os.path, output=logfile)
841

    
842
  if result.failed:
843
    logging.error("os create command '%s' returned error: %s output: %s",
844
                  result.cmd, result.fail_reason, result.output)
845
    lines = [utils.SafeEncode(val)
846
             for val in utils.TailFile(logfile, lines=20)]
847
    _Fail("OS rename script failed (%s), last lines in the"
848
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
849

    
850

    
851
def _GetVGInfo(vg_name):
852
  """Get information about the volume group.
853

854
  @type vg_name: str
855
  @param vg_name: the volume group which we query
856
  @rtype: dict
857
  @return:
858
    A dictionary with the following keys:
859
      - C{vg_size} is the total size of the volume group in MiB
860
      - C{vg_free} is the free size of the volume group in MiB
861
      - C{pv_count} are the number of physical disks in that VG
862

863
    If an error occurs during gathering of data, we return the same dict
864
    with keys all set to None.
865

866
  """
867
  retdic = dict.fromkeys(["vg_size", "vg_free", "pv_count"])
868

    
869
  retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings",
870
                         "--nosuffix", "--units=m", "--separator=:", vg_name])
871

    
872
  if retval.failed:
873
    logging.error("volume group %s not present", vg_name)
874
    return retdic
875
  valarr = retval.stdout.strip().rstrip(':').split(':')
876
  if len(valarr) == 3:
877
    try:
878
      retdic = {
879
        "vg_size": int(round(float(valarr[0]), 0)),
880
        "vg_free": int(round(float(valarr[1]), 0)),
881
        "pv_count": int(valarr[2]),
882
        }
883
    except ValueError, err:
884
      logging.exception("Fail to parse vgs output: %s", err)
885
  else:
886
    logging.error("vgs output has the wrong number of fields (expected"
887
                  " three): %s", str(valarr))
888
  return retdic
889

    
890

    
891
def _GetBlockDevSymlinkPath(instance_name, idx):
892
  return os.path.join(constants.DISK_LINKS_DIR,
893
                      "%s:%d" % (instance_name, idx))
894

    
895

    
896
def _SymlinkBlockDev(instance_name, device_path, idx):
897
  """Set up symlinks to a instance's block device.
898

899
  This is an auxiliary function run when an instance is start (on the primary
900
  node) or when an instance is migrated (on the target node).
901

902

903
  @param instance_name: the name of the target instance
904
  @param device_path: path of the physical block device, on the node
905
  @param idx: the disk index
906
  @return: absolute path to the disk's symlink
907

908
  """
909
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
910
  try:
911
    os.symlink(device_path, link_name)
912
  except OSError, err:
913
    if err.errno == errno.EEXIST:
914
      if (not os.path.islink(link_name) or
915
          os.readlink(link_name) != device_path):
916
        os.remove(link_name)
917
        os.symlink(device_path, link_name)
918
    else:
919
      raise
920

    
921
  return link_name
922

    
923

    
924
def _RemoveBlockDevLinks(instance_name, disks):
925
  """Remove the block device symlinks belonging to the given instance.
926

927
  """
928
  for idx, _ in enumerate(disks):
929
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
930
    if os.path.islink(link_name):
931
      try:
932
        os.remove(link_name)
933
      except OSError:
934
        logging.exception("Can't remove symlink '%s'", link_name)
935

    
936

    
937
def _GatherAndLinkBlockDevs(instance):
938
  """Set up an instance's block device(s).
939

940
  This is run on the primary node at instance startup. The block
941
  devices must be already assembled.
942

943
  @type instance: L{objects.Instance}
944
  @param instance: the instance whose disks we shoul assemble
945
  @rtype: list
946
  @return: list of (disk_object, device_path)
947

948
  """
949
  block_devices = []
950
  for idx, disk in enumerate(instance.disks):
951
    device = _RecursiveFindBD(disk)
952
    if device is None:
953
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
954
                                    str(disk))
955
    device.Open()
956
    try:
957
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
958
    except OSError, e:
959
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
960
                                    e.strerror)
961

    
962
    block_devices.append((disk, link_name))
963

    
964
  return block_devices
965

    
966

    
967
def StartInstance(instance):
968
  """Start an instance.
969

970
  @type instance: L{objects.Instance}
971
  @param instance: the instance object
972
  @rtype: None
973

974
  """
975
  running_instances = GetInstanceList([instance.hypervisor])
976

    
977
  if instance.name in running_instances:
978
    logging.info("Instance %s already running, not starting", instance.name)
979
    return
980

    
981
  try:
982
    block_devices = _GatherAndLinkBlockDevs(instance)
983
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
984
    hyper.StartInstance(instance, block_devices)
985
  except errors.BlockDeviceError, err:
986
    _Fail("Block device error: %s", err, exc=True)
987
  except errors.HypervisorError, err:
988
    _RemoveBlockDevLinks(instance.name, instance.disks)
989
    _Fail("Hypervisor error: %s", err, exc=True)
990

    
991

    
992
def InstanceShutdown(instance, timeout):
993
  """Shut an instance down.
994

995
  @note: this functions uses polling with a hardcoded timeout.
996

997
  @type instance: L{objects.Instance}
998
  @param instance: the instance object
999
  @type timeout: integer
1000
  @param timeout: maximum timeout for soft shutdown
1001
  @rtype: None
1002

1003
  """
1004
  hv_name = instance.hypervisor
1005
  hyper = hypervisor.GetHypervisor(hv_name)
1006
  iname = instance.name
1007

    
1008
  if instance.name not in hyper.ListInstances():
1009
    logging.info("Instance %s not running, doing nothing", iname)
1010
    return
1011

    
1012
  class _TryShutdown:
1013
    def __init__(self):
1014
      self.tried_once = False
1015

    
1016
    def __call__(self):
1017
      if iname not in hyper.ListInstances():
1018
        return
1019

    
1020
      try:
1021
        hyper.StopInstance(instance, retry=self.tried_once)
1022
      except errors.HypervisorError, err:
1023
        if iname not in hyper.ListInstances():
1024
          # if the instance is no longer existing, consider this a
1025
          # success and go to cleanup
1026
          return
1027

    
1028
        _Fail("Failed to stop instance %s: %s", iname, err)
1029

    
1030
      self.tried_once = True
1031

    
1032
      raise utils.RetryAgain()
1033

    
1034
  try:
1035
    utils.Retry(_TryShutdown(), 5, timeout)
1036
  except utils.RetryTimeout:
1037
    # the shutdown did not succeed
1038
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1039

    
1040
    try:
1041
      hyper.StopInstance(instance, force=True)
1042
    except errors.HypervisorError, err:
1043
      if iname in hyper.ListInstances():
1044
        # only raise an error if the instance still exists, otherwise
1045
        # the error could simply be "instance ... unknown"!
1046
        _Fail("Failed to force stop instance %s: %s", iname, err)
1047

    
1048
    time.sleep(1)
1049

    
1050
    if iname in hyper.ListInstances():
1051
      _Fail("Could not shutdown instance %s even by destroy", iname)
1052

    
1053
  _RemoveBlockDevLinks(iname, instance.disks)
1054

    
1055

    
1056
def InstanceReboot(instance, reboot_type, shutdown_timeout):
1057
  """Reboot an instance.
1058

1059
  @type instance: L{objects.Instance}
1060
  @param instance: the instance object to reboot
1061
  @type reboot_type: str
1062
  @param reboot_type: the type of reboot, one the following
1063
    constants:
1064
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1065
        instance OS, do not recreate the VM
1066
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1067
        restart the VM (at the hypervisor level)
1068
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1069
        not accepted here, since that mode is handled differently, in
1070
        cmdlib, and translates into full stop and start of the
1071
        instance (instead of a call_instance_reboot RPC)
1072
  @type shutdown_timeout: integer
1073
  @param shutdown_timeout: maximum timeout for soft shutdown
1074
  @rtype: None
1075

1076
  """
1077
  running_instances = GetInstanceList([instance.hypervisor])
1078

    
1079
  if instance.name not in running_instances:
1080
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1081

    
1082
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1083
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1084
    try:
1085
      hyper.RebootInstance(instance)
1086
    except errors.HypervisorError, err:
1087
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1088
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1089
    try:
1090
      InstanceShutdown(instance, shutdown_timeout)
1091
      return StartInstance(instance)
1092
    except errors.HypervisorError, err:
1093
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1094
  else:
1095
    _Fail("Invalid reboot_type received: %s", reboot_type)
1096

    
1097

    
1098
def MigrationInfo(instance):
1099
  """Gather information about an instance to be migrated.
1100

1101
  @type instance: L{objects.Instance}
1102
  @param instance: the instance definition
1103

1104
  """
1105
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1106
  try:
1107
    info = hyper.MigrationInfo(instance)
1108
  except errors.HypervisorError, err:
1109
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1110
  return info
1111

    
1112

    
1113
def AcceptInstance(instance, info, target):
1114
  """Prepare the node to accept an instance.
1115

1116
  @type instance: L{objects.Instance}
1117
  @param instance: the instance definition
1118
  @type info: string/data (opaque)
1119
  @param info: migration information, from the source node
1120
  @type target: string
1121
  @param target: target host (usually ip), on this node
1122

1123
  """
1124
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1125
  try:
1126
    hyper.AcceptInstance(instance, info, target)
1127
  except errors.HypervisorError, err:
1128
    _Fail("Failed to accept instance: %s", err, exc=True)
1129

    
1130

    
1131
def FinalizeMigration(instance, info, success):
1132
  """Finalize any preparation to accept an instance.
1133

1134
  @type instance: L{objects.Instance}
1135
  @param instance: the instance definition
1136
  @type info: string/data (opaque)
1137
  @param info: migration information, from the source node
1138
  @type success: boolean
1139
  @param success: whether the migration was a success or a failure
1140

1141
  """
1142
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1143
  try:
1144
    hyper.FinalizeMigration(instance, info, success)
1145
  except errors.HypervisorError, err:
1146
    _Fail("Failed to finalize migration: %s", err, exc=True)
1147

    
1148

    
1149
def MigrateInstance(instance, target, live):
1150
  """Migrates an instance to another node.
1151

1152
  @type instance: L{objects.Instance}
1153
  @param instance: the instance definition
1154
  @type target: string
1155
  @param target: the target node name
1156
  @type live: boolean
1157
  @param live: whether the migration should be done live or not (the
1158
      interpretation of this parameter is left to the hypervisor)
1159
  @rtype: tuple
1160
  @return: a tuple of (success, msg) where:
1161
      - succes is a boolean denoting the success/failure of the operation
1162
      - msg is a string with details in case of failure
1163

1164
  """
1165
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1166

    
1167
  try:
1168
    hyper.MigrateInstance(instance, target, live)
1169
  except errors.HypervisorError, err:
1170
    _Fail("Failed to migrate instance: %s", err, exc=True)
1171

    
1172

    
1173
def BlockdevCreate(disk, size, owner, on_primary, info):
1174
  """Creates a block device for an instance.
1175

1176
  @type disk: L{objects.Disk}
1177
  @param disk: the object describing the disk we should create
1178
  @type size: int
1179
  @param size: the size of the physical underlying device, in MiB
1180
  @type owner: str
1181
  @param owner: the name of the instance for which disk is created,
1182
      used for device cache data
1183
  @type on_primary: boolean
1184
  @param on_primary:  indicates if it is the primary node or not
1185
  @type info: string
1186
  @param info: string that will be sent to the physical device
1187
      creation, used for example to set (LVM) tags on LVs
1188

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

1193
  """
1194
  clist = []
1195
  if disk.children:
1196
    for child in disk.children:
1197
      try:
1198
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1199
      except errors.BlockDeviceError, err:
1200
        _Fail("Can't assemble device %s: %s", child, err)
1201
      if on_primary or disk.AssembleOnSecondary():
1202
        # we need the children open in case the device itself has to
1203
        # be assembled
1204
        try:
1205
          crdev.Open()
1206
        except errors.BlockDeviceError, err:
1207
          _Fail("Can't make child '%s' read-write: %s", child, err)
1208
      clist.append(crdev)
1209

    
1210
  try:
1211
    device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
1212
  except errors.BlockDeviceError, err:
1213
    _Fail("Can't create block device: %s", err)
1214

    
1215
  if on_primary or disk.AssembleOnSecondary():
1216
    try:
1217
      device.Assemble()
1218
    except errors.BlockDeviceError, err:
1219
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1220
    device.SetSyncSpeed(constants.SYNC_SPEED)
1221
    if on_primary or disk.OpenOnSecondary():
1222
      try:
1223
        device.Open(force=True)
1224
      except errors.BlockDeviceError, err:
1225
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1226
    DevCacheManager.UpdateCache(device.dev_path, owner,
1227
                                on_primary, disk.iv_name)
1228

    
1229
  device.SetInfo(info)
1230

    
1231
  return device.unique_id
1232

    
1233

    
1234
def BlockdevRemove(disk):
1235
  """Remove a block device.
1236

1237
  @note: This is intended to be called recursively.
1238

1239
  @type disk: L{objects.Disk}
1240
  @param disk: the disk object we should remove
1241
  @rtype: boolean
1242
  @return: the success of the operation
1243

1244
  """
1245
  msgs = []
1246
  try:
1247
    rdev = _RecursiveFindBD(disk)
1248
  except errors.BlockDeviceError, err:
1249
    # probably can't attach
1250
    logging.info("Can't attach to device %s in remove", disk)
1251
    rdev = None
1252
  if rdev is not None:
1253
    r_path = rdev.dev_path
1254
    try:
1255
      rdev.Remove()
1256
    except errors.BlockDeviceError, err:
1257
      msgs.append(str(err))
1258
    if not msgs:
1259
      DevCacheManager.RemoveCache(r_path)
1260

    
1261
  if disk.children:
1262
    for child in disk.children:
1263
      try:
1264
        BlockdevRemove(child)
1265
      except RPCFail, err:
1266
        msgs.append(str(err))
1267

    
1268
  if msgs:
1269
    _Fail("; ".join(msgs))
1270

    
1271

    
1272
def _RecursiveAssembleBD(disk, owner, as_primary):
1273
  """Activate a block device for an instance.
1274

1275
  This is run on the primary and secondary nodes for an instance.
1276

1277
  @note: this function is called recursively.
1278

1279
  @type disk: L{objects.Disk}
1280
  @param disk: the disk we try to assemble
1281
  @type owner: str
1282
  @param owner: the name of the instance which owns the disk
1283
  @type as_primary: boolean
1284
  @param as_primary: if we should make the block device
1285
      read/write
1286

1287
  @return: the assembled device or None (in case no device
1288
      was assembled)
1289
  @raise errors.BlockDeviceError: in case there is an error
1290
      during the activation of the children or the device
1291
      itself
1292

1293
  """
1294
  children = []
1295
  if disk.children:
1296
    mcn = disk.ChildrenNeeded()
1297
    if mcn == -1:
1298
      mcn = 0 # max number of Nones allowed
1299
    else:
1300
      mcn = len(disk.children) - mcn # max number of Nones
1301
    for chld_disk in disk.children:
1302
      try:
1303
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1304
      except errors.BlockDeviceError, err:
1305
        if children.count(None) >= mcn:
1306
          raise
1307
        cdev = None
1308
        logging.error("Error in child activation (but continuing): %s",
1309
                      str(err))
1310
      children.append(cdev)
1311

    
1312
  if as_primary or disk.AssembleOnSecondary():
1313
    r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
1314
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1315
    result = r_dev
1316
    if as_primary or disk.OpenOnSecondary():
1317
      r_dev.Open()
1318
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1319
                                as_primary, disk.iv_name)
1320

    
1321
  else:
1322
    result = True
1323
  return result
1324

    
1325

    
1326
def BlockdevAssemble(disk, owner, as_primary):
1327
  """Activate a block device for an instance.
1328

1329
  This is a wrapper over _RecursiveAssembleBD.
1330

1331
  @rtype: str or boolean
1332
  @return: a C{/dev/...} path for primary nodes, and
1333
      C{True} for secondary nodes
1334

1335
  """
1336
  try:
1337
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1338
    if isinstance(result, bdev.BlockDev):
1339
      result = result.dev_path
1340
  except errors.BlockDeviceError, err:
1341
    _Fail("Error while assembling disk: %s", err, exc=True)
1342

    
1343
  return result
1344

    
1345

    
1346
def BlockdevShutdown(disk):
1347
  """Shut down a block device.
1348

1349
  First, if the device is assembled (Attach() is successful), then
1350
  the device is shutdown. Then the children of the device are
1351
  shutdown.
1352

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

1357
  @type disk: L{objects.Disk}
1358
  @param disk: the description of the disk we should
1359
      shutdown
1360
  @rtype: None
1361

1362
  """
1363
  msgs = []
1364
  r_dev = _RecursiveFindBD(disk)
1365
  if r_dev is not None:
1366
    r_path = r_dev.dev_path
1367
    try:
1368
      r_dev.Shutdown()
1369
      DevCacheManager.RemoveCache(r_path)
1370
    except errors.BlockDeviceError, err:
1371
      msgs.append(str(err))
1372

    
1373
  if disk.children:
1374
    for child in disk.children:
1375
      try:
1376
        BlockdevShutdown(child)
1377
      except RPCFail, err:
1378
        msgs.append(str(err))
1379

    
1380
  if msgs:
1381
    _Fail("; ".join(msgs))
1382

    
1383

    
1384
def BlockdevAddchildren(parent_cdev, new_cdevs):
1385
  """Extend a mirrored block device.
1386

1387
  @type parent_cdev: L{objects.Disk}
1388
  @param parent_cdev: the disk to which we should add children
1389
  @type new_cdevs: list of L{objects.Disk}
1390
  @param new_cdevs: the list of children which we should add
1391
  @rtype: None
1392

1393
  """
1394
  parent_bdev = _RecursiveFindBD(parent_cdev)
1395
  if parent_bdev is None:
1396
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1397
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1398
  if new_bdevs.count(None) > 0:
1399
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1400
  parent_bdev.AddChildren(new_bdevs)
1401

    
1402

    
1403
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1404
  """Shrink a mirrored block device.
1405

1406
  @type parent_cdev: L{objects.Disk}
1407
  @param parent_cdev: the disk from which we should remove children
1408
  @type new_cdevs: list of L{objects.Disk}
1409
  @param new_cdevs: the list of children which we should remove
1410
  @rtype: None
1411

1412
  """
1413
  parent_bdev = _RecursiveFindBD(parent_cdev)
1414
  if parent_bdev is None:
1415
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1416
  devs = []
1417
  for disk in new_cdevs:
1418
    rpath = disk.StaticDevPath()
1419
    if rpath is None:
1420
      bd = _RecursiveFindBD(disk)
1421
      if bd is None:
1422
        _Fail("Can't find device %s while removing children", disk)
1423
      else:
1424
        devs.append(bd.dev_path)
1425
    else:
1426
      devs.append(rpath)
1427
  parent_bdev.RemoveChildren(devs)
1428

    
1429

    
1430
def BlockdevGetmirrorstatus(disks):
1431
  """Get the mirroring status of a list of devices.
1432

1433
  @type disks: list of L{objects.Disk}
1434
  @param disks: the list of disks which we should query
1435
  @rtype: disk
1436
  @return:
1437
      a list of (mirror_done, estimated_time) tuples, which
1438
      are the result of L{bdev.BlockDev.CombinedSyncStatus}
1439
  @raise errors.BlockDeviceError: if any of the disks cannot be
1440
      found
1441

1442
  """
1443
  stats = []
1444
  for dsk in disks:
1445
    rbd = _RecursiveFindBD(dsk)
1446
    if rbd is None:
1447
      _Fail("Can't find device %s", dsk)
1448

    
1449
    stats.append(rbd.CombinedSyncStatus())
1450

    
1451
  return stats
1452

    
1453

    
1454
def _RecursiveFindBD(disk):
1455
  """Check if a device is activated.
1456

1457
  If so, return information about the real device.
1458

1459
  @type disk: L{objects.Disk}
1460
  @param disk: the disk object we need to find
1461

1462
  @return: None if the device can't be found,
1463
      otherwise the device instance
1464

1465
  """
1466
  children = []
1467
  if disk.children:
1468
    for chdisk in disk.children:
1469
      children.append(_RecursiveFindBD(chdisk))
1470

    
1471
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1472

    
1473

    
1474
def BlockdevFind(disk):
1475
  """Check if a device is activated.
1476

1477
  If it is, return information about the real device.
1478

1479
  @type disk: L{objects.Disk}
1480
  @param disk: the disk to find
1481
  @rtype: None or objects.BlockDevStatus
1482
  @return: None if the disk cannot be found, otherwise a the current
1483
           information
1484

1485
  """
1486
  try:
1487
    rbd = _RecursiveFindBD(disk)
1488
  except errors.BlockDeviceError, err:
1489
    _Fail("Failed to find device: %s", err, exc=True)
1490

    
1491
  if rbd is None:
1492
    return None
1493

    
1494
  return rbd.GetSyncStatus()
1495

    
1496

    
1497
def BlockdevGetsize(disks):
1498
  """Computes the size of the given disks.
1499

1500
  If a disk is not found, returns None instead.
1501

1502
  @type disks: list of L{objects.Disk}
1503
  @param disks: the list of disk to compute the size for
1504
  @rtype: list
1505
  @return: list with elements None if the disk cannot be found,
1506
      otherwise the size
1507

1508
  """
1509
  result = []
1510
  for cf in disks:
1511
    try:
1512
      rbd = _RecursiveFindBD(cf)
1513
    except errors.BlockDeviceError, err:
1514
      result.append(None)
1515
      continue
1516
    if rbd is None:
1517
      result.append(None)
1518
    else:
1519
      result.append(rbd.GetActualSize())
1520
  return result
1521

    
1522

    
1523
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
1524
  """Export a block device to a remote node.
1525

1526
  @type disk: L{objects.Disk}
1527
  @param disk: the description of the disk to export
1528
  @type dest_node: str
1529
  @param dest_node: the destination node to export to
1530
  @type dest_path: str
1531
  @param dest_path: the destination path on the target node
1532
  @type cluster_name: str
1533
  @param cluster_name: the cluster name, needed for SSH hostalias
1534
  @rtype: None
1535

1536
  """
1537
  real_disk = _RecursiveFindBD(disk)
1538
  if real_disk is None:
1539
    _Fail("Block device '%s' is not set up", disk)
1540

    
1541
  real_disk.Open()
1542

    
1543
  # the block size on the read dd is 1MiB to match our units
1544
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
1545
                               "dd if=%s bs=1048576 count=%s",
1546
                               real_disk.dev_path, str(disk.size))
1547

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

    
1557
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1558
                                                   constants.GANETI_RUNAS,
1559
                                                   destcmd)
1560

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

    
1564
  result = utils.RunCmd(["bash", "-c", command])
1565

    
1566
  if result.failed:
1567
    _Fail("Disk copy command '%s' returned error: %s"
1568
          " output: %s", command, result.fail_reason, result.output)
1569

    
1570

    
1571
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1572
  """Write a file to the filesystem.
1573

1574
  This allows the master to overwrite(!) a file. It will only perform
1575
  the operation if the file belongs to a list of configuration files.
1576

1577
  @type file_name: str
1578
  @param file_name: the target file name
1579
  @type data: str
1580
  @param data: the new contents of the file
1581
  @type mode: int
1582
  @param mode: the mode to give the file (can be None)
1583
  @type uid: int
1584
  @param uid: the owner of the file (can be -1 for default)
1585
  @type gid: int
1586
  @param gid: the group of the file (can be -1 for default)
1587
  @type atime: float
1588
  @param atime: the atime to set on the file (can be None)
1589
  @type mtime: float
1590
  @param mtime: the mtime to set on the file (can be None)
1591
  @rtype: None
1592

1593
  """
1594
  if not os.path.isabs(file_name):
1595
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
1596

    
1597
  if file_name not in _ALLOWED_UPLOAD_FILES:
1598
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
1599
          file_name)
1600

    
1601
  raw_data = _Decompress(data)
1602

    
1603
  utils.WriteFile(file_name, data=raw_data, mode=mode, uid=uid, gid=gid,
1604
                  atime=atime, mtime=mtime)
1605

    
1606

    
1607
def WriteSsconfFiles(values):
1608
  """Update all ssconf files.
1609

1610
  Wrapper around the SimpleStore.WriteFiles.
1611

1612
  """
1613
  ssconf.SimpleStore().WriteFiles(values)
1614

    
1615

    
1616
def _ErrnoOrStr(err):
1617
  """Format an EnvironmentError exception.
1618

1619
  If the L{err} argument has an errno attribute, it will be looked up
1620
  and converted into a textual C{E...} description. Otherwise the
1621
  string representation of the error will be returned.
1622

1623
  @type err: L{EnvironmentError}
1624
  @param err: the exception to format
1625

1626
  """
1627
  if hasattr(err, 'errno'):
1628
    detail = errno.errorcode[err.errno]
1629
  else:
1630
    detail = str(err)
1631
  return detail
1632

    
1633

    
1634
def _OSOndiskAPIVersion(name, os_dir):
1635
  """Compute and return the API version of a given OS.
1636

1637
  This function will try to read the API version of the OS given by
1638
  the 'name' parameter and residing in the 'os_dir' directory.
1639

1640
  @type name: str
1641
  @param name: the OS name we should look for
1642
  @type os_dir: str
1643
  @param os_dir: the directory inwhich we should look for the OS
1644
  @rtype: tuple
1645
  @return: tuple (status, data) with status denoting the validity and
1646
      data holding either the vaid versions or an error message
1647

1648
  """
1649
  api_file = os.path.sep.join([os_dir, constants.OS_API_FILE])
1650

    
1651
  try:
1652
    st = os.stat(api_file)
1653
  except EnvironmentError, err:
1654
    return False, ("Required file '%s' not found under path %s: %s" %
1655
                   (constants.OS_API_FILE, os_dir, _ErrnoOrStr(err)))
1656

    
1657
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1658
    return False, ("File '%s' in %s is not a regular file" %
1659
                   (constants.OS_API_FILE, os_dir))
1660

    
1661
  try:
1662
    api_versions = utils.ReadFile(api_file).splitlines()
1663
  except EnvironmentError, err:
1664
    return False, ("Error while reading the API version file at %s: %s" %
1665
                   (api_file, _ErrnoOrStr(err)))
1666

    
1667
  try:
1668
    api_versions = [int(version.strip()) for version in api_versions]
1669
  except (TypeError, ValueError), err:
1670
    return False, ("API version(s) can't be converted to integer: %s" %
1671
                   str(err))
1672

    
1673
  return True, api_versions
1674

    
1675

    
1676
def DiagnoseOS(top_dirs=None):
1677
  """Compute the validity for all OSes.
1678

1679
  @type top_dirs: list
1680
  @param top_dirs: the list of directories in which to
1681
      search (if not given defaults to
1682
      L{constants.OS_SEARCH_PATH})
1683
  @rtype: list of L{objects.OS}
1684
  @return: a list of tuples (name, path, status, diagnose, variants)
1685
      for all (potential) OSes under all search paths, where:
1686
          - name is the (potential) OS name
1687
          - path is the full path to the OS
1688
          - status True/False is the validity of the OS
1689
          - diagnose is the error message for an invalid OS, otherwise empty
1690
          - variants is a list of supported OS variants, if any
1691

1692
  """
1693
  if top_dirs is None:
1694
    top_dirs = constants.OS_SEARCH_PATH
1695

    
1696
  result = []
1697
  for dir_name in top_dirs:
1698
    if os.path.isdir(dir_name):
1699
      try:
1700
        f_names = utils.ListVisibleFiles(dir_name)
1701
      except EnvironmentError, err:
1702
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
1703
        break
1704
      for name in f_names:
1705
        os_path = os.path.sep.join([dir_name, name])
1706
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
1707
        if status:
1708
          diagnose = ""
1709
          variants = os_inst.supported_variants
1710
        else:
1711
          diagnose = os_inst
1712
          variants = []
1713
        result.append((name, os_path, status, diagnose, variants))
1714

    
1715
  return result
1716

    
1717

    
1718
def _TryOSFromDisk(name, base_dir=None):
1719
  """Create an OS instance from disk.
1720

1721
  This function will return an OS instance if the given name is a
1722
  valid OS name.
1723

1724
  @type base_dir: string
1725
  @keyword base_dir: Base directory containing OS installations.
1726
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1727
  @rtype: tuple
1728
  @return: success and either the OS instance if we find a valid one,
1729
      or error message
1730

1731
  """
1732
  if base_dir is None:
1733
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1734
    if os_dir is None:
1735
      return False, "Directory for OS %s not found in search path" % name
1736
  else:
1737
    os_dir = os.path.sep.join([base_dir, name])
1738

    
1739
  status, api_versions = _OSOndiskAPIVersion(name, os_dir)
1740
  if not status:
1741
    # push the error up
1742
    return status, api_versions
1743

    
1744
  if not constants.OS_API_VERSIONS.intersection(api_versions):
1745
    return False, ("API version mismatch for path '%s': found %s, want %s." %
1746
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
1747

    
1748
  # OS Files dictionary, we will populate it with the absolute path names
1749
  os_files = dict.fromkeys(constants.OS_SCRIPTS)
1750

    
1751
  if max(api_versions) >= constants.OS_API_V15:
1752
    os_files[constants.OS_VARIANTS_FILE] = ''
1753

    
1754
  for filename in os_files:
1755
    os_files[filename] = os.path.sep.join([os_dir, filename])
1756

    
1757
    try:
1758
      st = os.stat(os_files[filename])
1759
    except EnvironmentError, err:
1760
      return False, ("File '%s' under path '%s' is missing (%s)" %
1761
                     (filename, os_dir, _ErrnoOrStr(err)))
1762

    
1763
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1764
      return False, ("File '%s' under path '%s' is not a regular file" %
1765
                     (filename, os_dir))
1766

    
1767
    if filename in constants.OS_SCRIPTS:
1768
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1769
        return False, ("File '%s' under path '%s' is not executable" %
1770
                       (filename, os_dir))
1771

    
1772
  variants = None
1773
  if constants.OS_VARIANTS_FILE in os_files:
1774
    variants_file = os_files[constants.OS_VARIANTS_FILE]
1775
    try:
1776
      variants = utils.ReadFile(variants_file).splitlines()
1777
    except EnvironmentError, err:
1778
      return False, ("Error while reading the OS variants file at %s: %s" %
1779
                     (variants_file, _ErrnoOrStr(err)))
1780
    if not variants:
1781
      return False, ("No supported os variant found")
1782

    
1783
  os_obj = objects.OS(name=name, path=os_dir,
1784
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
1785
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
1786
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
1787
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
1788
                      supported_variants=variants,
1789
                      api_versions=api_versions)
1790
  return True, os_obj
1791

    
1792

    
1793
def OSFromDisk(name, base_dir=None):
1794
  """Create an OS instance from disk.
1795

1796
  This function will return an OS instance if the given name is a
1797
  valid OS name. Otherwise, it will raise an appropriate
1798
  L{RPCFail} exception, detailing why this is not a valid OS.
1799

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

1803
  @type base_dir: string
1804
  @keyword base_dir: Base directory containing OS installations.
1805
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1806
  @rtype: L{objects.OS}
1807
  @return: the OS instance if we find a valid one
1808
  @raise RPCFail: if we don't find a valid OS
1809

1810
  """
1811
  name_only = name.split("+", 1)[0]
1812
  status, payload = _TryOSFromDisk(name_only, base_dir)
1813

    
1814
  if not status:
1815
    _Fail(payload)
1816

    
1817
  return payload
1818

    
1819

    
1820
def OSEnvironment(instance, inst_os, debug=0):
1821
  """Calculate the environment for an os script.
1822

1823
  @type instance: L{objects.Instance}
1824
  @param instance: target instance for the os script run
1825
  @type inst_os: L{objects.OS}
1826
  @param inst_os: operating system for which the environment is being built
1827
  @type debug: integer
1828
  @param debug: debug level (0 or 1, for OS Api 10)
1829
  @rtype: dict
1830
  @return: dict of environment variables
1831
  @raise errors.BlockDeviceError: if the block device
1832
      cannot be found
1833

1834
  """
1835
  result = {}
1836
  api_version = \
1837
    max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
1838
  result['OS_API_VERSION'] = '%d' % api_version
1839
  result['INSTANCE_NAME'] = instance.name
1840
  result['INSTANCE_OS'] = instance.os
1841
  result['HYPERVISOR'] = instance.hypervisor
1842
  result['DISK_COUNT'] = '%d' % len(instance.disks)
1843
  result['NIC_COUNT'] = '%d' % len(instance.nics)
1844
  result['DEBUG_LEVEL'] = '%d' % debug
1845
  if api_version >= constants.OS_API_V15:
1846
    try:
1847
      variant = instance.os.split('+', 1)[1]
1848
    except IndexError:
1849
      variant = inst_os.supported_variants[0]
1850
    result['OS_VARIANT'] = variant
1851
  for idx, disk in enumerate(instance.disks):
1852
    real_disk = _RecursiveFindBD(disk)
1853
    if real_disk is None:
1854
      raise errors.BlockDeviceError("Block device '%s' is not set up" %
1855
                                    str(disk))
1856
    real_disk.Open()
1857
    result['DISK_%d_PATH' % idx] = real_disk.dev_path
1858
    result['DISK_%d_ACCESS' % idx] = disk.mode
1859
    if constants.HV_DISK_TYPE in instance.hvparams:
1860
      result['DISK_%d_FRONTEND_TYPE' % idx] = \
1861
        instance.hvparams[constants.HV_DISK_TYPE]
1862
    if disk.dev_type in constants.LDS_BLOCK:
1863
      result['DISK_%d_BACKEND_TYPE' % idx] = 'block'
1864
    elif disk.dev_type == constants.LD_FILE:
1865
      result['DISK_%d_BACKEND_TYPE' % idx] = \
1866
        'file:%s' % disk.physical_id[0]
1867
  for idx, nic in enumerate(instance.nics):
1868
    result['NIC_%d_MAC' % idx] = nic.mac
1869
    if nic.ip:
1870
      result['NIC_%d_IP' % idx] = nic.ip
1871
    result['NIC_%d_MODE' % idx] = nic.nicparams[constants.NIC_MODE]
1872
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
1873
      result['NIC_%d_BRIDGE' % idx] = nic.nicparams[constants.NIC_LINK]
1874
    if nic.nicparams[constants.NIC_LINK]:
1875
      result['NIC_%d_LINK' % idx] = nic.nicparams[constants.NIC_LINK]
1876
    if constants.HV_NIC_TYPE in instance.hvparams:
1877
      result['NIC_%d_FRONTEND_TYPE' % idx] = \
1878
        instance.hvparams[constants.HV_NIC_TYPE]
1879

    
1880
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
1881
    for key, value in source.items():
1882
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
1883

    
1884
  return result
1885

    
1886
def BlockdevGrow(disk, amount):
1887
  """Grow a stack of block devices.
1888

1889
  This function is called recursively, with the childrens being the
1890
  first ones to resize.
1891

1892
  @type disk: L{objects.Disk}
1893
  @param disk: the disk to be grown
1894
  @rtype: (status, result)
1895
  @return: a tuple with the status of the operation
1896
      (True/False), and the errors message if status
1897
      is False
1898

1899
  """
1900
  r_dev = _RecursiveFindBD(disk)
1901
  if r_dev is None:
1902
    _Fail("Cannot find block device %s", disk)
1903

    
1904
  try:
1905
    r_dev.Grow(amount)
1906
  except errors.BlockDeviceError, err:
1907
    _Fail("Failed to grow block device: %s", err, exc=True)
1908

    
1909

    
1910
def BlockdevSnapshot(disk):
1911
  """Create a snapshot copy of a block device.
1912

1913
  This function is called recursively, and the snapshot is actually created
1914
  just for the leaf lvm backend device.
1915

1916
  @type disk: L{objects.Disk}
1917
  @param disk: the disk to be snapshotted
1918
  @rtype: string
1919
  @return: snapshot disk path
1920

1921
  """
1922
  if disk.children:
1923
    if len(disk.children) == 1:
1924
      # only one child, let's recurse on it
1925
      return BlockdevSnapshot(disk.children[0])
1926
    else:
1927
      # more than one child, choose one that matches
1928
      for child in disk.children:
1929
        if child.size == disk.size:
1930
          # return implies breaking the loop
1931
          return BlockdevSnapshot(child)
1932
  elif disk.dev_type == constants.LD_LV:
1933
    r_dev = _RecursiveFindBD(disk)
1934
    if r_dev is not None:
1935
      # let's stay on the safe side and ask for the full size, for now
1936
      return r_dev.Snapshot(disk.size)
1937
    else:
1938
      _Fail("Cannot find block device %s", disk)
1939
  else:
1940
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
1941
          disk.unique_id, disk.dev_type)
1942

    
1943

    
1944
def ExportSnapshot(disk, dest_node, instance, cluster_name, idx):
1945
  """Export a block device snapshot to a remote node.
1946

1947
  @type disk: L{objects.Disk}
1948
  @param disk: the description of the disk to export
1949
  @type dest_node: str
1950
  @param dest_node: the destination node to export to
1951
  @type instance: L{objects.Instance}
1952
  @param instance: the instance object to whom the disk belongs
1953
  @type cluster_name: str
1954
  @param cluster_name: the cluster name, needed for SSH hostalias
1955
  @type idx: int
1956
  @param idx: the index of the disk in the instance's disk list,
1957
      used to export to the OS scripts environment
1958
  @rtype: None
1959

1960
  """
1961
  inst_os = OSFromDisk(instance.os)
1962
  export_env = OSEnvironment(instance, inst_os)
1963

    
1964
  export_script = inst_os.export_script
1965

    
1966
  logfile = "%s/exp-%s-%s-%s.log" % (constants.LOG_OS_DIR, inst_os.name,
1967
                                     instance.name, int(time.time()))
1968
  if not os.path.exists(constants.LOG_OS_DIR):
1969
    os.mkdir(constants.LOG_OS_DIR, 0750)
1970
  real_disk = _RecursiveFindBD(disk)
1971
  if real_disk is None:
1972
    _Fail("Block device '%s' is not set up", disk)
1973

    
1974
  real_disk.Open()
1975

    
1976
  export_env['EXPORT_DEVICE'] = real_disk.dev_path
1977
  export_env['EXPORT_INDEX'] = str(idx)
1978

    
1979
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1980
  destfile = disk.physical_id[1]
1981

    
1982
  # the target command is built out of three individual commands,
1983
  # which are joined by pipes; we check each individual command for
1984
  # valid parameters
1985
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; cd %s; %s 2>%s",
1986
                               inst_os.path, export_script, logfile)
1987

    
1988
  comprcmd = "gzip"
1989

    
1990
  destcmd = utils.BuildShellCmd("mkdir -p %s && cat > %s/%s",
1991
                                destdir, destdir, destfile)
1992
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1993
                                                   constants.GANETI_RUNAS,
1994
                                                   destcmd)
1995

    
1996
  # all commands have been checked, so we're safe to combine them
1997
  command = '|'.join([expcmd, comprcmd, utils.ShellQuoteArgs(remotecmd)])
1998

    
1999
  result = utils.RunCmd(["bash", "-c", command], env=export_env)
2000

    
2001
  if result.failed:
2002
    _Fail("OS snapshot export command '%s' returned error: %s"
2003
          " output: %s", command, result.fail_reason, result.output)
2004

    
2005

    
2006
def FinalizeExport(instance, snap_disks):
2007
  """Write out the export configuration information.
2008

2009
  @type instance: L{objects.Instance}
2010
  @param instance: the instance which we export, used for
2011
      saving configuration
2012
  @type snap_disks: list of L{objects.Disk}
2013
  @param snap_disks: list of snapshot block devices, which
2014
      will be used to get the actual name of the dump file
2015

2016
  @rtype: None
2017

2018
  """
2019
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
2020
  finaldestdir = os.path.join(constants.EXPORT_DIR, instance.name)
2021

    
2022
  config = objects.SerializableConfigParser()
2023

    
2024
  config.add_section(constants.INISECT_EXP)
2025
  config.set(constants.INISECT_EXP, 'version', '0')
2026
  config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
2027
  config.set(constants.INISECT_EXP, 'source', instance.primary_node)
2028
  config.set(constants.INISECT_EXP, 'os', instance.os)
2029
  config.set(constants.INISECT_EXP, 'compression', 'gzip')
2030

    
2031
  config.add_section(constants.INISECT_INS)
2032
  config.set(constants.INISECT_INS, 'name', instance.name)
2033
  config.set(constants.INISECT_INS, 'memory', '%d' %
2034
             instance.beparams[constants.BE_MEMORY])
2035
  config.set(constants.INISECT_INS, 'vcpus', '%d' %
2036
             instance.beparams[constants.BE_VCPUS])
2037
  config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
2038

    
2039
  nic_total = 0
2040
  for nic_count, nic in enumerate(instance.nics):
2041
    nic_total += 1
2042
    config.set(constants.INISECT_INS, 'nic%d_mac' %
2043
               nic_count, '%s' % nic.mac)
2044
    config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
2045
    config.set(constants.INISECT_INS, 'nic%d_bridge' % nic_count,
2046
               '%s' % nic.bridge)
2047
  # TODO: redundant: on load can read nics until it doesn't exist
2048
  config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_total)
2049

    
2050
  disk_total = 0
2051
  for disk_count, disk in enumerate(snap_disks):
2052
    if disk:
2053
      disk_total += 1
2054
      config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
2055
                 ('%s' % disk.iv_name))
2056
      config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
2057
                 ('%s' % disk.physical_id[1]))
2058
      config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
2059
                 ('%d' % disk.size))
2060

    
2061
  config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_total)
2062

    
2063
  utils.WriteFile(os.path.join(destdir, constants.EXPORT_CONF_FILE),
2064
                  data=config.Dumps())
2065
  shutil.rmtree(finaldestdir, True)
2066
  shutil.move(destdir, finaldestdir)
2067

    
2068

    
2069
def ExportInfo(dest):
2070
  """Get export configuration information.
2071

2072
  @type dest: str
2073
  @param dest: directory containing the export
2074

2075
  @rtype: L{objects.SerializableConfigParser}
2076
  @return: a serializable config file containing the
2077
      export info
2078

2079
  """
2080
  cff = os.path.join(dest, constants.EXPORT_CONF_FILE)
2081

    
2082
  config = objects.SerializableConfigParser()
2083
  config.read(cff)
2084

    
2085
  if (not config.has_section(constants.INISECT_EXP) or
2086
      not config.has_section(constants.INISECT_INS)):
2087
    _Fail("Export info file doesn't have the required fields")
2088

    
2089
  return config.Dumps()
2090

    
2091

    
2092
def ImportOSIntoInstance(instance, src_node, src_images, cluster_name):
2093
  """Import an os image into an instance.
2094

2095
  @type instance: L{objects.Instance}
2096
  @param instance: instance to import the disks into
2097
  @type src_node: string
2098
  @param src_node: source node for the disk images
2099
  @type src_images: list of string
2100
  @param src_images: absolute paths of the disk images
2101
  @rtype: list of boolean
2102
  @return: each boolean represent the success of importing the n-th disk
2103

2104
  """
2105
  inst_os = OSFromDisk(instance.os)
2106
  import_env = OSEnvironment(instance, inst_os)
2107
  import_script = inst_os.import_script
2108

    
2109
  logfile = "%s/import-%s-%s-%s.log" % (constants.LOG_OS_DIR, instance.os,
2110
                                        instance.name, int(time.time()))
2111
  if not os.path.exists(constants.LOG_OS_DIR):
2112
    os.mkdir(constants.LOG_OS_DIR, 0750)
2113

    
2114
  comprcmd = "gunzip"
2115
  impcmd = utils.BuildShellCmd("(cd %s; %s >%s 2>&1)", inst_os.path,
2116
                               import_script, logfile)
2117

    
2118
  final_result = []
2119
  for idx, image in enumerate(src_images):
2120
    if image:
2121
      destcmd = utils.BuildShellCmd('cat %s', image)
2122
      remotecmd = _GetSshRunner(cluster_name).BuildCmd(src_node,
2123
                                                       constants.GANETI_RUNAS,
2124
                                                       destcmd)
2125
      command = '|'.join([utils.ShellQuoteArgs(remotecmd), comprcmd, impcmd])
2126
      import_env['IMPORT_DEVICE'] = import_env['DISK_%d_PATH' % idx]
2127
      import_env['IMPORT_INDEX'] = str(idx)
2128
      result = utils.RunCmd(command, env=import_env)
2129
      if result.failed:
2130
        logging.error("Disk import command '%s' returned error: %s"
2131
                      " output: %s", command, result.fail_reason,
2132
                      result.output)
2133
        final_result.append("error importing disk %d: %s, %s" %
2134
                            (idx, result.fail_reason, result.output[-100]))
2135

    
2136
  if final_result:
2137
    _Fail("; ".join(final_result), log=False)
2138

    
2139

    
2140
def ListExports():
2141
  """Return a list of exports currently available on this machine.
2142

2143
  @rtype: list
2144
  @return: list of the exports
2145

2146
  """
2147
  if os.path.isdir(constants.EXPORT_DIR):
2148
    return utils.ListVisibleFiles(constants.EXPORT_DIR)
2149
  else:
2150
    _Fail("No exports directory")
2151

    
2152

    
2153
def RemoveExport(export):
2154
  """Remove an existing export from the node.
2155

2156
  @type export: str
2157
  @param export: the name of the export to remove
2158
  @rtype: None
2159

2160
  """
2161
  target = os.path.join(constants.EXPORT_DIR, export)
2162

    
2163
  try:
2164
    shutil.rmtree(target)
2165
  except EnvironmentError, err:
2166
    _Fail("Error while removing the export: %s", err, exc=True)
2167

    
2168

    
2169
def BlockdevRename(devlist):
2170
  """Rename a list of block devices.
2171

2172
  @type devlist: list of tuples
2173
  @param devlist: list of tuples of the form  (disk,
2174
      new_logical_id, new_physical_id); disk is an
2175
      L{objects.Disk} object describing the current disk,
2176
      and new logical_id/physical_id is the name we
2177
      rename it to
2178
  @rtype: boolean
2179
  @return: True if all renames succeeded, False otherwise
2180

2181
  """
2182
  msgs = []
2183
  result = True
2184
  for disk, unique_id in devlist:
2185
    dev = _RecursiveFindBD(disk)
2186
    if dev is None:
2187
      msgs.append("Can't find device %s in rename" % str(disk))
2188
      result = False
2189
      continue
2190
    try:
2191
      old_rpath = dev.dev_path
2192
      dev.Rename(unique_id)
2193
      new_rpath = dev.dev_path
2194
      if old_rpath != new_rpath:
2195
        DevCacheManager.RemoveCache(old_rpath)
2196
        # FIXME: we should add the new cache information here, like:
2197
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2198
        # but we don't have the owner here - maybe parse from existing
2199
        # cache? for now, we only lose lvm data when we rename, which
2200
        # is less critical than DRBD or MD
2201
    except errors.BlockDeviceError, err:
2202
      msgs.append("Can't rename device '%s' to '%s': %s" %
2203
                  (dev, unique_id, err))
2204
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2205
      result = False
2206
  if not result:
2207
    _Fail("; ".join(msgs))
2208

    
2209

    
2210
def _TransformFileStorageDir(file_storage_dir):
2211
  """Checks whether given file_storage_dir is valid.
2212

2213
  Checks wheter the given file_storage_dir is within the cluster-wide
2214
  default file_storage_dir stored in SimpleStore. Only paths under that
2215
  directory are allowed.
2216

2217
  @type file_storage_dir: str
2218
  @param file_storage_dir: the path to check
2219

2220
  @return: the normalized path if valid, None otherwise
2221

2222
  """
2223
  cfg = _GetConfig()
2224
  file_storage_dir = os.path.normpath(file_storage_dir)
2225
  base_file_storage_dir = cfg.GetFileStorageDir()
2226
  if (not os.path.commonprefix([file_storage_dir, base_file_storage_dir]) ==
2227
      base_file_storage_dir):
2228
    _Fail("File storage directory '%s' is not under base file"
2229
          " storage directory '%s'", file_storage_dir, base_file_storage_dir)
2230
  return file_storage_dir
2231

    
2232

    
2233
def CreateFileStorageDir(file_storage_dir):
2234
  """Create file storage directory.
2235

2236
  @type file_storage_dir: str
2237
  @param file_storage_dir: directory to create
2238

2239
  @rtype: tuple
2240
  @return: tuple with first element a boolean indicating wheter dir
2241
      creation was successful or not
2242

2243
  """
2244
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2245
  if os.path.exists(file_storage_dir):
2246
    if not os.path.isdir(file_storage_dir):
2247
      _Fail("Specified storage dir '%s' is not a directory",
2248
            file_storage_dir)
2249
  else:
2250
    try:
2251
      os.makedirs(file_storage_dir, 0750)
2252
    except OSError, err:
2253
      _Fail("Cannot create file storage directory '%s': %s",
2254
            file_storage_dir, err, exc=True)
2255

    
2256

    
2257
def RemoveFileStorageDir(file_storage_dir):
2258
  """Remove file storage directory.
2259

2260
  Remove it only if it's empty. If not log an error and return.
2261

2262
  @type file_storage_dir: str
2263
  @param file_storage_dir: the directory we should cleanup
2264
  @rtype: tuple (success,)
2265
  @return: tuple of one element, C{success}, denoting
2266
      whether the operation was successful
2267

2268
  """
2269
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2270
  if os.path.exists(file_storage_dir):
2271
    if not os.path.isdir(file_storage_dir):
2272
      _Fail("Specified Storage directory '%s' is not a directory",
2273
            file_storage_dir)
2274
    # deletes dir only if empty, otherwise we want to fail the rpc call
2275
    try:
2276
      os.rmdir(file_storage_dir)
2277
    except OSError, err:
2278
      _Fail("Cannot remove file storage directory '%s': %s",
2279
            file_storage_dir, err)
2280

    
2281

    
2282
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2283
  """Rename the file storage directory.
2284

2285
  @type old_file_storage_dir: str
2286
  @param old_file_storage_dir: the current path
2287
  @type new_file_storage_dir: str
2288
  @param new_file_storage_dir: the name we should rename to
2289
  @rtype: tuple (success,)
2290
  @return: tuple of one element, C{success}, denoting
2291
      whether the operation was successful
2292

2293
  """
2294
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2295
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2296
  if not os.path.exists(new_file_storage_dir):
2297
    if os.path.isdir(old_file_storage_dir):
2298
      try:
2299
        os.rename(old_file_storage_dir, new_file_storage_dir)
2300
      except OSError, err:
2301
        _Fail("Cannot rename '%s' to '%s': %s",
2302
              old_file_storage_dir, new_file_storage_dir, err)
2303
    else:
2304
      _Fail("Specified storage dir '%s' is not a directory",
2305
            old_file_storage_dir)
2306
  else:
2307
    if os.path.exists(old_file_storage_dir):
2308
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2309
            old_file_storage_dir, new_file_storage_dir)
2310

    
2311

    
2312
def _EnsureJobQueueFile(file_name):
2313
  """Checks whether the given filename is in the queue directory.
2314

2315
  @type file_name: str
2316
  @param file_name: the file name we should check
2317
  @rtype: None
2318
  @raises RPCFail: if the file is not valid
2319

2320
  """
2321
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2322
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2323

    
2324
  if not result:
2325
    _Fail("Passed job queue file '%s' does not belong to"
2326
          " the queue directory '%s'", file_name, queue_dir)
2327

    
2328

    
2329
def JobQueueUpdate(file_name, content):
2330
  """Updates a file in the queue directory.
2331

2332
  This is just a wrapper over L{utils.WriteFile}, with proper
2333
  checking.
2334

2335
  @type file_name: str
2336
  @param file_name: the job file name
2337
  @type content: str
2338
  @param content: the new job contents
2339
  @rtype: boolean
2340
  @return: the success of the operation
2341

2342
  """
2343
  _EnsureJobQueueFile(file_name)
2344

    
2345
  # Write and replace the file atomically
2346
  utils.WriteFile(file_name, data=_Decompress(content))
2347

    
2348

    
2349
def JobQueueRename(old, new):
2350
  """Renames a job queue file.
2351

2352
  This is just a wrapper over os.rename with proper checking.
2353

2354
  @type old: str
2355
  @param old: the old (actual) file name
2356
  @type new: str
2357
  @param new: the desired file name
2358
  @rtype: tuple
2359
  @return: the success of the operation and payload
2360

2361
  """
2362
  _EnsureJobQueueFile(old)
2363
  _EnsureJobQueueFile(new)
2364

    
2365
  utils.RenameFile(old, new, mkdir=True)
2366

    
2367

    
2368
def JobQueueSetDrainFlag(drain_flag):
2369
  """Set the drain flag for the queue.
2370

2371
  This will set or unset the queue drain flag.
2372

2373
  @type drain_flag: boolean
2374
  @param drain_flag: if True, will set the drain flag, otherwise reset it.
2375
  @rtype: truple
2376
  @return: always True, None
2377
  @warning: the function always returns True
2378

2379
  """
2380
  if drain_flag:
2381
    utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True)
2382
  else:
2383
    utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
2384

    
2385

    
2386
def BlockdevClose(instance_name, disks):
2387
  """Closes the given block devices.
2388

2389
  This means they will be switched to secondary mode (in case of
2390
  DRBD).
2391

2392
  @param instance_name: if the argument is not empty, the symlinks
2393
      of this instance will be removed
2394
  @type disks: list of L{objects.Disk}
2395
  @param disks: the list of disks to be closed
2396
  @rtype: tuple (success, message)
2397
  @return: a tuple of success and message, where success
2398
      indicates the succes of the operation, and message
2399
      which will contain the error details in case we
2400
      failed
2401

2402
  """
2403
  bdevs = []
2404
  for cf in disks:
2405
    rd = _RecursiveFindBD(cf)
2406
    if rd is None:
2407
      _Fail("Can't find device %s", cf)
2408
    bdevs.append(rd)
2409

    
2410
  msg = []
2411
  for rd in bdevs:
2412
    try:
2413
      rd.Close()
2414
    except errors.BlockDeviceError, err:
2415
      msg.append(str(err))
2416
  if msg:
2417
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2418
  else:
2419
    if instance_name:
2420
      _RemoveBlockDevLinks(instance_name, disks)
2421

    
2422

    
2423
def ValidateHVParams(hvname, hvparams):
2424
  """Validates the given hypervisor parameters.
2425

2426
  @type hvname: string
2427
  @param hvname: the hypervisor name
2428
  @type hvparams: dict
2429
  @param hvparams: the hypervisor parameters to be validated
2430
  @rtype: None
2431

2432
  """
2433
  try:
2434
    hv_type = hypervisor.GetHypervisor(hvname)
2435
    hv_type.ValidateParameters(hvparams)
2436
  except errors.HypervisorError, err:
2437
    _Fail(str(err), log=False)
2438

    
2439

    
2440
def DemoteFromMC():
2441
  """Demotes the current node from master candidate role.
2442

2443
  """
2444
  # try to ensure we're not the master by mistake
2445
  master, myself = ssconf.GetMasterAndMyself()
2446
  if master == myself:
2447
    _Fail("ssconf status shows I'm the master node, will not demote")
2448

    
2449
  result = utils.RunCmd([constants.DAEMON_UTIL, "check", constants.MASTERD])
2450
  if not result.failed:
2451
    _Fail("The master daemon is running, will not demote")
2452

    
2453
  try:
2454
    if os.path.isfile(constants.CLUSTER_CONF_FILE):
2455
      utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2456
  except EnvironmentError, err:
2457
    if err.errno != errno.ENOENT:
2458
      _Fail("Error while backing up cluster file: %s", err, exc=True)
2459

    
2460
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2461

    
2462

    
2463
def _FindDisks(nodes_ip, disks):
2464
  """Sets the physical ID on disks and returns the block devices.
2465

2466
  """
2467
  # set the correct physical ID
2468
  my_name = utils.HostInfo().name
2469
  for cf in disks:
2470
    cf.SetPhysicalID(my_name, nodes_ip)
2471

    
2472
  bdevs = []
2473

    
2474
  for cf in disks:
2475
    rd = _RecursiveFindBD(cf)
2476
    if rd is None:
2477
      _Fail("Can't find device %s", cf)
2478
    bdevs.append(rd)
2479
  return bdevs
2480

    
2481

    
2482
def DrbdDisconnectNet(nodes_ip, disks):
2483
  """Disconnects the network on a list of drbd devices.
2484

2485
  """
2486
  bdevs = _FindDisks(nodes_ip, disks)
2487

    
2488
  # disconnect disks
2489
  for rd in bdevs:
2490
    try:
2491
      rd.DisconnectNet()
2492
    except errors.BlockDeviceError, err:
2493
      _Fail("Can't change network configuration to standalone mode: %s",
2494
            err, exc=True)
2495

    
2496

    
2497
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
2498
  """Attaches the network on a list of drbd devices.
2499

2500
  """
2501
  bdevs = _FindDisks(nodes_ip, disks)
2502

    
2503
  if multimaster:
2504
    for idx, rd in enumerate(bdevs):
2505
      try:
2506
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
2507
      except EnvironmentError, err:
2508
        _Fail("Can't create symlink: %s", err)
2509
  # reconnect disks, switch to new master configuration and if
2510
  # needed primary mode
2511
  for rd in bdevs:
2512
    try:
2513
      rd.AttachNet(multimaster)
2514
    except errors.BlockDeviceError, err:
2515
      _Fail("Can't change network configuration: %s", err)
2516

    
2517
  # wait until the disks are connected; we need to retry the re-attach
2518
  # if the device becomes standalone, as this might happen if the one
2519
  # node disconnects and reconnects in a different mode before the
2520
  # other node reconnects; in this case, one or both of the nodes will
2521
  # decide it has wrong configuration and switch to standalone
2522

    
2523
  def _Attach():
2524
    all_connected = True
2525

    
2526
    for rd in bdevs:
2527
      stats = rd.GetProcStatus()
2528

    
2529
      all_connected = (all_connected and
2530
                       (stats.is_connected or stats.is_in_resync))
2531

    
2532
      if stats.is_standalone:
2533
        # peer had different config info and this node became
2534
        # standalone, even though this should not happen with the
2535
        # new staged way of changing disk configs
2536
        try:
2537
          rd.AttachNet(multimaster)
2538
        except errors.BlockDeviceError, err:
2539
          _Fail("Can't change network configuration: %s", err)
2540

    
2541
    if not all_connected:
2542
      raise utils.RetryAgain()
2543

    
2544
  try:
2545
    # Start with a delay of 100 miliseconds and go up to 5 seconds
2546
    utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
2547
  except utils.RetryTimeout:
2548
    _Fail("Timeout in disk reconnecting")
2549

    
2550
  if multimaster:
2551
    # change to primary mode
2552
    for rd in bdevs:
2553
      try:
2554
        rd.Open()
2555
      except errors.BlockDeviceError, err:
2556
        _Fail("Can't change to primary mode: %s", err)
2557

    
2558

    
2559
def DrbdWaitSync(nodes_ip, disks):
2560
  """Wait until DRBDs have synchronized.
2561

2562
  """
2563
  def _helper(rd):
2564
    stats = rd.GetProcStatus()
2565
    if not (stats.is_connected or stats.is_in_resync):
2566
      raise utils.RetryAgain()
2567
    return stats
2568

    
2569
  bdevs = _FindDisks(nodes_ip, disks)
2570

    
2571
  min_resync = 100
2572
  alldone = True
2573
  for rd in bdevs:
2574
    try:
2575
      # poll each second for 15 seconds
2576
      stats = utils.Retry(_helper, 1, 15, args=[rd])
2577
    except utils.RetryTimeout:
2578
      stats = rd.GetProcStatus()
2579
      # last check
2580
      if not (stats.is_connected or stats.is_in_resync):
2581
        _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
2582
    alldone = alldone and (not stats.is_in_resync)
2583
    if stats.sync_percent is not None:
2584
      min_resync = min(min_resync, stats.sync_percent)
2585

    
2586
  return (alldone, min_resync)
2587

    
2588

    
2589
def PowercycleNode(hypervisor_type):
2590
  """Hard-powercycle the node.
2591

2592
  Because we need to return first, and schedule the powercycle in the
2593
  background, we won't be able to report failures nicely.
2594

2595
  """
2596
  hyper = hypervisor.GetHypervisor(hypervisor_type)
2597
  try:
2598
    pid = os.fork()
2599
  except OSError:
2600
    # if we can't fork, we'll pretend that we're in the child process
2601
    pid = 0
2602
  if pid > 0:
2603
    return "Reboot scheduled in 5 seconds"
2604
  time.sleep(5)
2605
  hyper.PowercycleNode()
2606

    
2607

    
2608
class HooksRunner(object):
2609
  """Hook runner.
2610

2611
  This class is instantiated on the node side (ganeti-noded) and not
2612
  on the master side.
2613

2614
  """
2615
  RE_MASK = re.compile("^[a-zA-Z0-9_-]+$")
2616

    
2617
  def __init__(self, hooks_base_dir=None):
2618
    """Constructor for hooks runner.
2619

2620
    @type hooks_base_dir: str or None
2621
    @param hooks_base_dir: if not None, this overrides the
2622
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
2623

2624
    """
2625
    if hooks_base_dir is None:
2626
      hooks_base_dir = constants.HOOKS_BASE_DIR
2627
    self._BASE_DIR = hooks_base_dir
2628

    
2629
  @staticmethod
2630
  def ExecHook(script, env):
2631
    """Exec one hook script.
2632

2633
    @type script: str
2634
    @param script: the full path to the script
2635
    @type env: dict
2636
    @param env: the environment with which to exec the script
2637
    @rtype: tuple (success, message)
2638
    @return: a tuple of success and message, where success
2639
        indicates the succes of the operation, and message
2640
        which will contain the error details in case we
2641
        failed
2642

2643
    """
2644
    # exec the process using subprocess and log the output
2645
    fdstdin = None
2646
    try:
2647
      fdstdin = open("/dev/null", "r")
2648
      child = subprocess.Popen([script], stdin=fdstdin, stdout=subprocess.PIPE,
2649
                               stderr=subprocess.STDOUT, close_fds=True,
2650
                               shell=False, cwd="/", env=env)
2651
      output = ""
2652
      try:
2653
        output = child.stdout.read(4096)
2654
        child.stdout.close()
2655
      except EnvironmentError, err:
2656
        output += "Hook script error: %s" % str(err)
2657

    
2658
      while True:
2659
        try:
2660
          result = child.wait()
2661
          break
2662
        except EnvironmentError, err:
2663
          if err.errno == errno.EINTR:
2664
            continue
2665
          raise
2666
    finally:
2667
      # try not to leak fds
2668
      for fd in (fdstdin, ):
2669
        if fd is not None:
2670
          try:
2671
            fd.close()
2672
          except EnvironmentError, err:
2673
            # just log the error
2674
            #logging.exception("Error while closing fd %s", fd)
2675
            pass
2676

    
2677
    return result == 0, utils.SafeEncode(output.strip())
2678

    
2679
  def RunHooks(self, hpath, phase, env):
2680
    """Run the scripts in the hooks directory.
2681

2682
    @type hpath: str
2683
    @param hpath: the path to the hooks directory which
2684
        holds the scripts
2685
    @type phase: str
2686
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
2687
        L{constants.HOOKS_PHASE_POST}
2688
    @type env: dict
2689
    @param env: dictionary with the environment for the hook
2690
    @rtype: list
2691
    @return: list of 3-element tuples:
2692
      - script path
2693
      - script result, either L{constants.HKR_SUCCESS} or
2694
        L{constants.HKR_FAIL}
2695
      - output of the script
2696

2697
    @raise errors.ProgrammerError: for invalid input
2698
        parameters
2699

2700
    """
2701
    if phase == constants.HOOKS_PHASE_PRE:
2702
      suffix = "pre"
2703
    elif phase == constants.HOOKS_PHASE_POST:
2704
      suffix = "post"
2705
    else:
2706
      _Fail("Unknown hooks phase '%s'", phase)
2707

    
2708
    rr = []
2709

    
2710
    subdir = "%s-%s.d" % (hpath, suffix)
2711
    dir_name = "%s/%s" % (self._BASE_DIR, subdir)
2712
    try:
2713
      dir_contents = utils.ListVisibleFiles(dir_name)
2714
    except OSError:
2715
      # FIXME: must log output in case of failures
2716
      return rr
2717

    
2718
    # we use the standard python sort order,
2719
    # so 00name is the recommended naming scheme
2720
    dir_contents.sort()
2721
    for relname in dir_contents:
2722
      fname = os.path.join(dir_name, relname)
2723
      if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and
2724
          self.RE_MASK.match(relname) is not None):
2725
        rrval = constants.HKR_SKIP
2726
        output = ""
2727
      else:
2728
        result, output = self.ExecHook(fname, env)
2729
        if not result:
2730
          rrval = constants.HKR_FAIL
2731
        else:
2732
          rrval = constants.HKR_SUCCESS
2733
      rr.append(("%s/%s" % (subdir, relname), rrval, output))
2734

    
2735
    return rr
2736

    
2737

    
2738
class IAllocatorRunner(object):
2739
  """IAllocator runner.
2740

2741
  This class is instantiated on the node side (ganeti-noded) and not on
2742
  the master side.
2743

2744
  """
2745
  def Run(self, name, idata):
2746
    """Run an iallocator script.
2747

2748
    @type name: str
2749
    @param name: the iallocator script name
2750
    @type idata: str
2751
    @param idata: the allocator input data
2752

2753
    @rtype: tuple
2754
    @return: two element tuple of:
2755
       - status
2756
       - either error message or stdout of allocator (for success)
2757

2758
    """
2759
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
2760
                                  os.path.isfile)
2761
    if alloc_script is None:
2762
      _Fail("iallocator module '%s' not found in the search path", name)
2763

    
2764
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
2765
    try:
2766
      os.write(fd, idata)
2767
      os.close(fd)
2768
      result = utils.RunCmd([alloc_script, fin_name])
2769
      if result.failed:
2770
        _Fail("iallocator module '%s' failed: %s, output '%s'",
2771
              name, result.fail_reason, result.output)
2772
    finally:
2773
      os.unlink(fin_name)
2774

    
2775
    return result.stdout
2776

    
2777

    
2778
class DevCacheManager(object):
2779
  """Simple class for managing a cache of block device information.
2780

2781
  """
2782
  _DEV_PREFIX = "/dev/"
2783
  _ROOT_DIR = constants.BDEV_CACHE_DIR
2784

    
2785
  @classmethod
2786
  def _ConvertPath(cls, dev_path):
2787
    """Converts a /dev/name path to the cache file name.
2788

2789
    This replaces slashes with underscores and strips the /dev
2790
    prefix. It then returns the full path to the cache file.
2791

2792
    @type dev_path: str
2793
    @param dev_path: the C{/dev/} path name
2794
    @rtype: str
2795
    @return: the converted path name
2796

2797
    """
2798
    if dev_path.startswith(cls._DEV_PREFIX):
2799
      dev_path = dev_path[len(cls._DEV_PREFIX):]
2800
    dev_path = dev_path.replace("/", "_")
2801
    fpath = "%s/bdev_%s" % (cls._ROOT_DIR, dev_path)
2802
    return fpath
2803

    
2804
  @classmethod
2805
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
2806
    """Updates the cache information for a given device.
2807

2808
    @type dev_path: str
2809
    @param dev_path: the pathname of the device
2810
    @type owner: str
2811
    @param owner: the owner (instance name) of the device
2812
    @type on_primary: bool
2813
    @param on_primary: whether this is the primary
2814
        node nor not
2815
    @type iv_name: str
2816
    @param iv_name: the instance-visible name of the
2817
        device, as in objects.Disk.iv_name
2818

2819
    @rtype: None
2820

2821
    """
2822
    if dev_path is None:
2823
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
2824
      return
2825
    fpath = cls._ConvertPath(dev_path)
2826
    if on_primary:
2827
      state = "primary"
2828
    else:
2829
      state = "secondary"
2830
    if iv_name is None:
2831
      iv_name = "not_visible"
2832
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
2833
    try:
2834
      utils.WriteFile(fpath, data=fdata)
2835
    except EnvironmentError, err:
2836
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
2837

    
2838
  @classmethod
2839
  def RemoveCache(cls, dev_path):
2840
    """Remove data for a dev_path.
2841

2842
    This is just a wrapper over L{utils.RemoveFile} with a converted
2843
    path name and logging.
2844

2845
    @type dev_path: str
2846
    @param dev_path: the pathname of the device
2847

2848
    @rtype: None
2849

2850
    """
2851
    if dev_path is None:
2852
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
2853
      return
2854
    fpath = cls._ConvertPath(dev_path)
2855
    try:
2856
      utils.RemoveFile(fpath)
2857
    except EnvironmentError, err:
2858
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)