Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 6263189c

History | View | Annotate | Download (84.8 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

    
30
import os
31
import os.path
32
import shutil
33
import time
34
import stat
35
import errno
36
import re
37
import subprocess
38
import random
39
import logging
40
import tempfile
41
import zlib
42
import base64
43

    
44
from ganeti import errors
45
from ganeti import utils
46
from ganeti import ssh
47
from ganeti import hypervisor
48
from ganeti import constants
49
from ganeti import bdev
50
from ganeti import objects
51
from ganeti import ssconf
52

    
53

    
54
_BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id"
55

    
56

    
57
class RPCFail(Exception):
58
  """Class denoting RPC failure.
59

60
  Its argument is the error message.
61

62
  """
63

    
64

    
65
def _Fail(msg, *args, **kwargs):
66
  """Log an error and the raise an RPCFail exception.
67

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

73
  @type msg: string
74
  @param msg: the text of the exception
75
  @raise RPCFail
76

77
  """
78
  if args:
79
    msg = msg % args
80
  if "log" not in kwargs or kwargs["log"]: # if we should log this error
81
    if "exc" in kwargs and kwargs["exc"]:
82
      logging.exception(msg)
83
    else:
84
      logging.error(msg)
85
  raise RPCFail(msg)
86

    
87

    
88
def _GetConfig():
89
  """Simple wrapper to return a SimpleStore.
90

91
  @rtype: L{ssconf.SimpleStore}
92
  @return: a SimpleStore instance
93

94
  """
95
  return ssconf.SimpleStore()
96

    
97

    
98
def _GetSshRunner(cluster_name):
99
  """Simple wrapper to return an SshRunner.
100

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

107
  """
108
  return ssh.SshRunner(cluster_name)
109

    
110

    
111
def _Decompress(data):
112
  """Unpacks data compressed by the RPC client.
113

114
  @type data: list or tuple
115
  @param data: Data sent by RPC client
116
  @rtype: str
117
  @return: Decompressed data
118

119
  """
120
  assert isinstance(data, (list, tuple))
121
  assert len(data) == 2
122
  (encoding, content) = data
123
  if encoding == constants.RPC_ENCODING_NONE:
124
    return content
125
  elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
126
    return zlib.decompress(base64.b64decode(content))
127
  else:
128
    raise AssertionError("Unknown data encoding")
129

    
130

    
131
def _CleanDirectory(path, exclude=None):
132
  """Removes all regular files in a directory.
133

134
  @type path: str
135
  @param path: the directory to clean
136
  @type exclude: list
137
  @param exclude: list of files to be excluded, defaults
138
      to the empty list
139

140
  """
141
  if not os.path.isdir(path):
142
    return
143
  if exclude is None:
144
    exclude = []
145
  else:
146
    # Normalize excluded paths
147
    exclude = [os.path.normpath(i) for i in exclude]
148

    
149
  for rel_name in utils.ListVisibleFiles(path):
150
    full_name = os.path.normpath(os.path.join(path, rel_name))
151
    if full_name in exclude:
152
      continue
153
    if os.path.isfile(full_name) and not os.path.islink(full_name):
154
      utils.RemoveFile(full_name)
155

    
156

    
157
def _BuildUploadFileList():
158
  """Build the list of allowed upload files.
159

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

162
  """
163
  allowed_files = set([
164
    constants.CLUSTER_CONF_FILE,
165
    constants.ETC_HOSTS,
166
    constants.SSH_KNOWN_HOSTS_FILE,
167
    constants.VNC_PASSWORD_FILE,
168
    constants.RAPI_CERT_FILE,
169
    constants.RAPI_USERS_FILE,
170
    constants.HMAC_CLUSTER_KEY,
171
    ])
172

    
173
  for hv_name in constants.HYPER_TYPES:
174
    hv_class = hypervisor.GetHypervisorClass(hv_name)
175
    allowed_files.update(hv_class.GetAncillaryFiles())
176

    
177
  return frozenset(allowed_files)
178

    
179

    
180
_ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
181

    
182

    
183
def JobQueuePurge():
184
  """Removes job queue files and archived jobs.
185

186
  @rtype: tuple
187
  @return: True, None
188

189
  """
190
  _CleanDirectory(constants.QUEUE_DIR, exclude=[constants.JOB_QUEUE_LOCK_FILE])
191
  _CleanDirectory(constants.JOB_QUEUE_ARCHIVE_DIR)
192

    
193

    
194
def GetMasterInfo():
195
  """Returns master information.
196

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

200
  @rtype: tuple
201
  @return: master_netdev, master_ip, master_name
202
  @raise RPCFail: in case of errors
203

204
  """
205
  try:
206
    cfg = _GetConfig()
207
    master_netdev = cfg.GetMasterNetdev()
208
    master_ip = cfg.GetMasterIP()
209
    master_node = cfg.GetMasterNode()
210
  except errors.ConfigurationError, err:
211
    _Fail("Cluster configuration incomplete: %s", err, exc=True)
212
  return (master_netdev, master_ip, master_node)
213

    
214

    
215
def StartMaster(start_daemons, no_voting):
216
  """Activate local node as master node.
217

218
  The function will always try activate the IP address of the master
219
  (unless someone else has it). It will also start the master daemons,
220
  based on the start_daemons parameter.
221

222
  @type start_daemons: boolean
223
  @param start_daemons: whether to also start the master
224
      daemons (ganeti-masterd and ganeti-rapi)
225
  @type no_voting: boolean
226
  @param no_voting: whether to start ganeti-masterd without a node vote
227
      (if start_daemons is True), but still non-interactively
228
  @rtype: None
229

230
  """
231
  # GetMasterInfo will raise an exception if not able to return data
232
  master_netdev, master_ip, _ = GetMasterInfo()
233

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

    
252
    result = utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev,
253
                           "-s", master_ip, master_ip])
254
    # we'll ignore the exit code of arping
255

    
256
  # and now start the master and rapi daemons
257
  if start_daemons:
258
    daemons_params = {
259
        'ganeti-masterd': [],
260
        'ganeti-rapi': [],
261
        }
262
    if no_voting:
263
      daemons_params['ganeti-masterd'].append('--no-voting')
264
      daemons_params['ganeti-masterd'].append('--yes-do-it')
265
    for daemon in daemons_params:
266
      cmd = [daemon]
267
      cmd.extend(daemons_params[daemon])
268
      result = utils.RunCmd(cmd)
269
      if result.failed:
270
        msg = "Can't start daemon %s: %s" % (daemon, result.output)
271
        logging.error(msg)
272
        err_msgs.append(msg)
273

    
274
  if err_msgs:
275
    _Fail("; ".join(err_msgs))
276

    
277

    
278
def StopMaster(stop_daemons):
279
  """Deactivate this node as master.
280

281
  The function will always try to deactivate the IP address of the
282
  master. It will also stop the master daemons depending on the
283
  stop_daemons parameter.
284

285
  @type stop_daemons: boolean
286
  @param stop_daemons: whether to also stop the master daemons
287
      (ganeti-masterd and ganeti-rapi)
288
  @rtype: None
289

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

    
294
  # GetMasterInfo will raise an exception if not able to return data
295
  master_netdev, master_ip, _ = GetMasterInfo()
296

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

    
303
  if stop_daemons:
304
    # stop/kill the rapi and the master daemon
305
    for daemon in constants.RAPI, constants.MASTERD:
306
      utils.KillProcess(utils.ReadPidFile(utils.DaemonPidFileName(daemon)))
307

    
308

    
309
def AddNode(dsa, dsapub, rsa, rsapub, sshkey, sshpub):
310
  """Joins this node to the cluster.
311

312
  This does the following:
313
      - updates the hostkeys of the machine (rsa and dsa)
314
      - adds the ssh private key to the user
315
      - adds the ssh public key to the users' authorized_keys file
316

317
  @type dsa: str
318
  @param dsa: the DSA private key to write
319
  @type dsapub: str
320
  @param dsapub: the DSA public key to write
321
  @type rsa: str
322
  @param rsa: the RSA private key to write
323
  @type rsapub: str
324
  @param rsapub: the RSA public key to write
325
  @type sshkey: str
326
  @param sshkey: the SSH private key to write
327
  @type sshpub: str
328
  @param sshpub: the SSH public key to write
329
  @rtype: boolean
330
  @return: the success of the operation
331

332
  """
333
  sshd_keys =  [(constants.SSH_HOST_RSA_PRIV, rsa, 0600),
334
                (constants.SSH_HOST_RSA_PUB, rsapub, 0644),
335
                (constants.SSH_HOST_DSA_PRIV, dsa, 0600),
336
                (constants.SSH_HOST_DSA_PUB, dsapub, 0644)]
337
  for name, content, mode in sshd_keys:
338
    utils.WriteFile(name, data=content, mode=mode)
339

    
340
  try:
341
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS,
342
                                                    mkdir=True)
343
  except errors.OpExecError, err:
344
    _Fail("Error while processing user ssh files: %s", err, exc=True)
345

    
346
  for name, content in [(priv_key, sshkey), (pub_key, sshpub)]:
347
    utils.WriteFile(name, data=content, mode=0600)
348

    
349
  utils.AddAuthorizedKey(auth_keys, sshpub)
350

    
351
  utils.RunCmd([constants.SSH_INITD_SCRIPT, "restart"])
352

    
353

    
354
def LeaveCluster():
355
  """Cleans up and remove the current node.
356

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

360
  If processing is successful, then it raises an
361
  L{errors.QuitGanetiException} which is used as a special case to
362
  shutdown the node daemon.
363

364
  """
365
  _CleanDirectory(constants.DATA_DIR)
366
  JobQueuePurge()
367

    
368
  try:
369
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
370

    
371
    utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
372

    
373
    utils.RemoveFile(priv_key)
374
    utils.RemoveFile(pub_key)
375
  except errors.OpExecError:
376
    logging.exception("Error while processing ssh files")
377

    
378
  try:
379
    utils.RemoveFile(constants.HMAC_CLUSTER_KEY)
380
    utils.RemoveFile(constants.RAPI_CERT_FILE)
381
    utils.RemoveFile(constants.SSL_CERT_FILE)
382
  except:
383
    logging.exception("Error while removing cluster secrets")
384

    
385
  confd_pid = utils.ReadPidFile(utils.DaemonPidFileName(constants.CONFD))
386

    
387
  if confd_pid:
388
    utils.KillProcess(confd_pid, timeout=2)
389

    
390
  # Raise a custom exception (handled in ganeti-noded)
391
  raise errors.QuitGanetiException(True, 'Shutdown scheduled')
392

    
393

    
394
def GetNodeInfo(vgname, hypervisor_type):
395
  """Gives back a hash with different information about the node.
396

397
  @type vgname: C{string}
398
  @param vgname: the name of the volume group to ask for disk space information
399
  @type hypervisor_type: C{str}
400
  @param hypervisor_type: the name of the hypervisor to ask for
401
      memory information
402
  @rtype: C{dict}
403
  @return: dictionary with the following keys:
404
      - vg_size is the size of the configured volume group in MiB
405
      - vg_free is the free size of the volume group in MiB
406
      - memory_dom0 is the memory allocated for domain0 in MiB
407
      - memory_free is the currently available (free) ram in MiB
408
      - memory_total is the total number of ram in MiB
409

410
  """
411
  outputarray = {}
412
  vginfo = _GetVGInfo(vgname)
413
  outputarray['vg_size'] = vginfo['vg_size']
414
  outputarray['vg_free'] = vginfo['vg_free']
415

    
416
  hyper = hypervisor.GetHypervisor(hypervisor_type)
417
  hyp_info = hyper.GetNodeInfo()
418
  if hyp_info is not None:
419
    outputarray.update(hyp_info)
420

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

    
423
  return outputarray
424

    
425

    
426
def VerifyNode(what, cluster_name):
427
  """Verify the status of the local node.
428

429
  Based on the input L{what} parameter, various checks are done on the
430
  local node.
431

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

435
  If the I{nodelist} key is present, we check that we have
436
  connectivity via ssh with the target nodes (and check the hostname
437
  report).
438

439
  If the I{node-net-test} key is present, we check that we have
440
  connectivity to the given nodes via both primary IP and, if
441
  applicable, secondary IPs.
442

443
  @type what: C{dict}
444
  @param what: a dictionary of things to check:
445
      - filelist: list of files for which to compute checksums
446
      - nodelist: list of nodes we should check ssh communication with
447
      - node-net-test: list of nodes we should check node daemon port
448
        connectivity with
449
      - hypervisor: list with hypervisors to run the verify for
450
  @rtype: dict
451
  @return: a dictionary with the same keys as the input dict, and
452
      values representing the result of the checks
453

454
  """
455
  result = {}
456

    
457
  if constants.NV_HYPERVISOR in what:
458
    result[constants.NV_HYPERVISOR] = tmp = {}
459
    for hv_name in what[constants.NV_HYPERVISOR]:
460
      tmp[hv_name] = hypervisor.GetHypervisor(hv_name).Verify()
461

    
462
  if constants.NV_FILELIST in what:
463
    result[constants.NV_FILELIST] = utils.FingerprintFiles(
464
      what[constants.NV_FILELIST])
465

    
466
  if constants.NV_NODELIST in what:
467
    result[constants.NV_NODELIST] = tmp = {}
468
    random.shuffle(what[constants.NV_NODELIST])
469
    for node in what[constants.NV_NODELIST]:
470
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
471
      if not success:
472
        tmp[node] = message
473

    
474
  if constants.NV_NODENETTEST in what:
475
    result[constants.NV_NODENETTEST] = tmp = {}
476
    my_name = utils.HostInfo().name
477
    my_pip = my_sip = None
478
    for name, pip, sip in what[constants.NV_NODENETTEST]:
479
      if name == my_name:
480
        my_pip = pip
481
        my_sip = sip
482
        break
483
    if not my_pip:
484
      tmp[my_name] = ("Can't find my own primary/secondary IP"
485
                      " in the node list")
486
    else:
487
      port = utils.GetDaemonPort(constants.NODED)
488
      for name, pip, sip in what[constants.NV_NODENETTEST]:
489
        fail = []
490
        if not utils.TcpPing(pip, port, source=my_pip):
491
          fail.append("primary")
492
        if sip != pip:
493
          if not utils.TcpPing(sip, port, source=my_sip):
494
            fail.append("secondary")
495
        if fail:
496
          tmp[name] = ("failure using the %s interface(s)" %
497
                       " and ".join(fail))
498

    
499
  if constants.NV_LVLIST in what:
500
    result[constants.NV_LVLIST] = GetVolumeList(what[constants.NV_LVLIST])
501

    
502
  if constants.NV_INSTANCELIST in what:
503
    result[constants.NV_INSTANCELIST] = GetInstanceList(
504
      what[constants.NV_INSTANCELIST])
505

    
506
  if constants.NV_VGLIST in what:
507
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
508

    
509
  if constants.NV_VERSION in what:
510
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
511
                                    constants.RELEASE_VERSION)
512

    
513
  if constants.NV_HVINFO in what:
514
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
515
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
516

    
517
  if constants.NV_DRBDLIST in what:
518
    try:
519
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
520
    except errors.BlockDeviceError, err:
521
      logging.warning("Can't get used minors list", exc_info=True)
522
      used_minors = str(err)
523
    result[constants.NV_DRBDLIST] = used_minors
524

    
525
  return result
526

    
527

    
528
def GetVolumeList(vg_name):
529
  """Compute list of logical volumes and their size.
530

531
  @type vg_name: str
532
  @param vg_name: the volume group whose LVs we should list
533
  @rtype: dict
534
  @return:
535
      dictionary of all partions (key) with value being a tuple of
536
      their size (in MiB), inactive and online status::
537

538
        {'test1': ('20.06', True, True)}
539

540
      in case of errors, a string is returned with the error
541
      details.
542

543
  """
544
  lvs = {}
545
  sep = '|'
546
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
547
                         "--separator=%s" % sep,
548
                         "-olv_name,lv_size,lv_attr", vg_name])
549
  if result.failed:
550
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
551

    
552
  valid_line_re = re.compile("^ *([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
553
  for line in result.stdout.splitlines():
554
    line = line.strip()
555
    match = valid_line_re.match(line)
556
    if not match:
557
      logging.error("Invalid line returned from lvs output: '%s'", line)
558
      continue
559
    name, size, attr = match.groups()
560
    inactive = attr[4] == '-'
561
    online = attr[5] == 'o'
562
    virtual = attr[0] == 'v'
563
    if virtual:
564
      # we don't want to report such volumes as existing, since they
565
      # don't really hold data
566
      continue
567
    lvs[name] = (size, inactive, online)
568

    
569
  return lvs
570

    
571

    
572
def ListVolumeGroups():
573
  """List the volume groups and their size.
574

575
  @rtype: dict
576
  @return: dictionary with keys volume name and values the
577
      size of the volume
578

579
  """
580
  return utils.ListVolumeGroups()
581

    
582

    
583
def NodeVolumes():
584
  """List all volumes on this node.
585

586
  @rtype: list
587
  @return:
588
    A list of dictionaries, each having four keys:
589
      - name: the logical volume name,
590
      - size: the size of the logical volume
591
      - dev: the physical device on which the LV lives
592
      - vg: the volume group to which it belongs
593

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

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

601
  """
602
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
603
                         "--separator=|",
604
                         "--options=lv_name,lv_size,devices,vg_name"])
605
  if result.failed:
606
    _Fail("Failed to list logical volumes, lvs output: %s",
607
          result.output)
608

    
609
  def parse_dev(dev):
610
    if '(' in dev:
611
      return dev.split('(')[0]
612
    else:
613
      return dev
614

    
615
  def map_line(line):
616
    return {
617
      'name': line[0].strip(),
618
      'size': line[1].strip(),
619
      'dev': parse_dev(line[2].strip()),
620
      'vg': line[3].strip(),
621
    }
622

    
623
  return [map_line(line.split('|')) for line in result.stdout.splitlines()
624
          if line.count('|') >= 3]
625

    
626

    
627
def BridgesExist(bridges_list):
628
  """Check if a list of bridges exist on the current node.
629

630
  @rtype: boolean
631
  @return: C{True} if all of them exist, C{False} otherwise
632

633
  """
634
  missing = []
635
  for bridge in bridges_list:
636
    if not utils.BridgeExists(bridge):
637
      missing.append(bridge)
638

    
639
  if missing:
640
    _Fail("Missing bridges %s", ", ".join(missing))
641

    
642

    
643
def GetInstanceList(hypervisor_list):
644
  """Provides a list of instances.
645

646
  @type hypervisor_list: list
647
  @param hypervisor_list: the list of hypervisors to query information
648

649
  @rtype: list
650
  @return: a list of all running instances on the current node
651
    - instance1.example.com
652
    - instance2.example.com
653

654
  """
655
  results = []
656
  for hname in hypervisor_list:
657
    try:
658
      names = hypervisor.GetHypervisor(hname).ListInstances()
659
      results.extend(names)
660
    except errors.HypervisorError, err:
661
      _Fail("Error enumerating instances (hypervisor %s): %s",
662
            hname, err, exc=True)
663

    
664
  return results
665

    
666

    
667
def GetInstanceInfo(instance, hname):
668
  """Gives back the information about an instance as a dictionary.
669

670
  @type instance: string
671
  @param instance: the instance name
672
  @type hname: string
673
  @param hname: the hypervisor type of the instance
674

675
  @rtype: dict
676
  @return: dictionary with the following keys:
677
      - memory: memory size of instance (int)
678
      - state: xen state of instance (string)
679
      - time: cpu time of instance (float)
680

681
  """
682
  output = {}
683

    
684
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
685
  if iinfo is not None:
686
    output['memory'] = iinfo[2]
687
    output['state'] = iinfo[4]
688
    output['time'] = iinfo[5]
689

    
690
  return output
691

    
692

    
693
def GetInstanceMigratable(instance):
694
  """Gives whether an instance can be migrated.
695

696
  @type instance: L{objects.Instance}
697
  @param instance: object representing the instance to be checked.
698

699
  @rtype: tuple
700
  @return: tuple of (result, description) where:
701
      - result: whether the instance can be migrated or not
702
      - description: a description of the issue, if relevant
703

704
  """
705
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
706
  iname = instance.name
707
  if iname not in hyper.ListInstances():
708
    _Fail("Instance %s is not running", iname)
709

    
710
  for idx in range(len(instance.disks)):
711
    link_name = _GetBlockDevSymlinkPath(iname, idx)
712
    if not os.path.islink(link_name):
713
      _Fail("Instance %s was not restarted since ganeti 1.2.5", iname)
714

    
715

    
716
def GetAllInstancesInfo(hypervisor_list):
717
  """Gather data about all instances.
718

719
  This is the equivalent of L{GetInstanceInfo}, except that it
720
  computes data for all instances at once, thus being faster if one
721
  needs data about more than one instance.
722

723
  @type hypervisor_list: list
724
  @param hypervisor_list: list of hypervisors to query for instance data
725

726
  @rtype: dict
727
  @return: dictionary of instance: data, with data having the following keys:
728
      - memory: memory size of instance (int)
729
      - state: xen state of instance (string)
730
      - time: cpu time of instance (float)
731
      - vcpus: the number of vcpus
732

733
  """
734
  output = {}
735

    
736
  for hname in hypervisor_list:
737
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
738
    if iinfo:
739
      for name, _, memory, vcpus, state, times in iinfo:
740
        value = {
741
          'memory': memory,
742
          'vcpus': vcpus,
743
          'state': state,
744
          'time': times,
745
          }
746
        if name in output:
747
          # we only check static parameters, like memory and vcpus,
748
          # and not state and time which can change between the
749
          # invocations of the different hypervisors
750
          for key in 'memory', 'vcpus':
751
            if value[key] != output[name][key]:
752
              _Fail("Instance %s is running twice"
753
                    " with different parameters", name)
754
        output[name] = value
755

    
756
  return output
757

    
758

    
759
def InstanceOsAdd(instance, reinstall):
760
  """Add an OS to an instance.
761

762
  @type instance: L{objects.Instance}
763
  @param instance: Instance whose OS is to be installed
764
  @type reinstall: boolean
765
  @param reinstall: whether this is an instance reinstall
766
  @rtype: None
767

768
  """
769
  inst_os = OSFromDisk(instance.os)
770

    
771
  create_env = OSEnvironment(instance, inst_os)
772
  if reinstall:
773
    create_env['INSTANCE_REINSTALL'] = "1"
774

    
775
  logfile = "%s/add-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
776
                                     instance.name, int(time.time()))
777

    
778
  result = utils.RunCmd([inst_os.create_script], env=create_env,
779
                        cwd=inst_os.path, output=logfile,)
780
  if result.failed:
781
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
782
                  " output: %s", result.cmd, result.fail_reason, logfile,
783
                  result.output)
784
    lines = [utils.SafeEncode(val)
785
             for val in utils.TailFile(logfile, lines=20)]
786
    _Fail("OS create script failed (%s), last lines in the"
787
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
788

    
789

    
790
def RunRenameInstance(instance, old_name):
791
  """Run the OS rename script for an instance.
792

793
  @type instance: L{objects.Instance}
794
  @param instance: Instance whose OS is to be installed
795
  @type old_name: string
796
  @param old_name: previous instance name
797
  @rtype: boolean
798
  @return: the success of the operation
799

800
  """
801
  inst_os = OSFromDisk(instance.os)
802

    
803
  rename_env = OSEnvironment(instance, inst_os)
804
  rename_env['OLD_INSTANCE_NAME'] = old_name
805

    
806
  logfile = "%s/rename-%s-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
807
                                           old_name,
808
                                           instance.name, int(time.time()))
809

    
810
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
811
                        cwd=inst_os.path, output=logfile)
812

    
813
  if result.failed:
814
    logging.error("os create command '%s' returned error: %s output: %s",
815
                  result.cmd, result.fail_reason, result.output)
816
    lines = [utils.SafeEncode(val)
817
             for val in utils.TailFile(logfile, lines=20)]
818
    _Fail("OS rename script failed (%s), last lines in the"
819
          " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
820

    
821

    
822
def _GetVGInfo(vg_name):
823
  """Get information about the volume group.
824

825
  @type vg_name: str
826
  @param vg_name: the volume group which we query
827
  @rtype: dict
828
  @return:
829
    A dictionary with the following keys:
830
      - C{vg_size} is the total size of the volume group in MiB
831
      - C{vg_free} is the free size of the volume group in MiB
832
      - C{pv_count} are the number of physical disks in that VG
833

834
    If an error occurs during gathering of data, we return the same dict
835
    with keys all set to None.
836

837
  """
838
  retdic = dict.fromkeys(["vg_size", "vg_free", "pv_count"])
839

    
840
  retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings",
841
                         "--nosuffix", "--units=m", "--separator=:", vg_name])
842

    
843
  if retval.failed:
844
    logging.error("volume group %s not present", vg_name)
845
    return retdic
846
  valarr = retval.stdout.strip().rstrip(':').split(':')
847
  if len(valarr) == 3:
848
    try:
849
      retdic = {
850
        "vg_size": int(round(float(valarr[0]), 0)),
851
        "vg_free": int(round(float(valarr[1]), 0)),
852
        "pv_count": int(valarr[2]),
853
        }
854
    except ValueError, err:
855
      logging.exception("Fail to parse vgs output: %s", err)
856
  else:
857
    logging.error("vgs output has the wrong number of fields (expected"
858
                  " three): %s", str(valarr))
859
  return retdic
860

    
861

    
862
def _GetBlockDevSymlinkPath(instance_name, idx):
863
  return os.path.join(constants.DISK_LINKS_DIR,
864
                      "%s:%d" % (instance_name, idx))
865

    
866

    
867
def _SymlinkBlockDev(instance_name, device_path, idx):
868
  """Set up symlinks to a instance's block device.
869

870
  This is an auxiliary function run when an instance is start (on the primary
871
  node) or when an instance is migrated (on the target node).
872

873

874
  @param instance_name: the name of the target instance
875
  @param device_path: path of the physical block device, on the node
876
  @param idx: the disk index
877
  @return: absolute path to the disk's symlink
878

879
  """
880
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
881
  try:
882
    os.symlink(device_path, link_name)
883
  except OSError, err:
884
    if err.errno == errno.EEXIST:
885
      if (not os.path.islink(link_name) or
886
          os.readlink(link_name) != device_path):
887
        os.remove(link_name)
888
        os.symlink(device_path, link_name)
889
    else:
890
      raise
891

    
892
  return link_name
893

    
894

    
895
def _RemoveBlockDevLinks(instance_name, disks):
896
  """Remove the block device symlinks belonging to the given instance.
897

898
  """
899
  for idx, _ in enumerate(disks):
900
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
901
    if os.path.islink(link_name):
902
      try:
903
        os.remove(link_name)
904
      except OSError:
905
        logging.exception("Can't remove symlink '%s'", link_name)
906

    
907

    
908
def _GatherAndLinkBlockDevs(instance):
909
  """Set up an instance's block device(s).
910

911
  This is run on the primary node at instance startup. The block
912
  devices must be already assembled.
913

914
  @type instance: L{objects.Instance}
915
  @param instance: the instance whose disks we shoul assemble
916
  @rtype: list
917
  @return: list of (disk_object, device_path)
918

919
  """
920
  block_devices = []
921
  for idx, disk in enumerate(instance.disks):
922
    device = _RecursiveFindBD(disk)
923
    if device is None:
924
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
925
                                    str(disk))
926
    device.Open()
927
    try:
928
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
929
    except OSError, e:
930
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
931
                                    e.strerror)
932

    
933
    block_devices.append((disk, link_name))
934

    
935
  return block_devices
936

    
937

    
938
def StartInstance(instance):
939
  """Start an instance.
940

941
  @type instance: L{objects.Instance}
942
  @param instance: the instance object
943
  @rtype: None
944

945
  """
946
  running_instances = GetInstanceList([instance.hypervisor])
947

    
948
  if instance.name in running_instances:
949
    logging.info("Instance %s already running, not starting", instance.name)
950
    return
951

    
952
  try:
953
    block_devices = _GatherAndLinkBlockDevs(instance)
954
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
955
    hyper.StartInstance(instance, block_devices)
956
  except errors.BlockDeviceError, err:
957
    _Fail("Block device error: %s", err, exc=True)
958
  except errors.HypervisorError, err:
959
    _RemoveBlockDevLinks(instance.name, instance.disks)
960
    _Fail("Hypervisor error: %s", err, exc=True)
961

    
962

    
963
def InstanceShutdown(instance, timeout):
964
  """Shut an instance down.
965

966
  @note: this functions uses polling with a hardcoded timeout.
967

968
  @type instance: L{objects.Instance}
969
  @param instance: the instance object
970
  @type timeout: integer
971
  @param timeout: maximum timeout for soft shutdown
972
  @rtype: None
973

974
  """
975
  hv_name = instance.hypervisor
976
  hyper = hypervisor.GetHypervisor(hv_name)
977
  running_instances = hyper.ListInstances()
978
  iname = instance.name
979

    
980
  if iname not in running_instances:
981
    logging.info("Instance %s not running, doing nothing", iname)
982
    return
983

    
984
  start = time.time()
985
  end = start + timeout
986
  sleep_time = 1
987

    
988
  tried_once = False
989
  while not tried_once and time.time() < end:
990
    try:
991
      hyper.StopInstance(instance, retry=tried_once)
992
    except errors.HypervisorError, err:
993
      _Fail("Failed to stop instance %s: %s", iname, err)
994
    tried_once = True
995
    time.sleep(sleep_time)
996
    if instance.name not in hyper.ListInstances():
997
      break
998
    if sleep_time < 5:
999
      # 1.2 behaves particularly good for our case:
1000
      # it gives us 10 increasing steps and caps just slightly above 5 seconds
1001
      sleep_time *= 1.2
1002
  else:
1003
    # the shutdown did not succeed
1004
    logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1005

    
1006
    try:
1007
      hyper.StopInstance(instance, force=True)
1008
    except errors.HypervisorError, err:
1009
      _Fail("Failed to force stop instance %s: %s", iname, err)
1010

    
1011
    time.sleep(1)
1012
    if instance.name in GetInstanceList([hv_name]):
1013
      _Fail("Could not shutdown instance %s even by destroy", iname)
1014

    
1015
  _RemoveBlockDevLinks(iname, instance.disks)
1016

    
1017

    
1018
def InstanceReboot(instance, reboot_type):
1019
  """Reboot an instance.
1020

1021
  @type instance: L{objects.Instance}
1022
  @param instance: the instance object to reboot
1023
  @type reboot_type: str
1024
  @param reboot_type: the type of reboot, one the following
1025
    constants:
1026
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1027
        instance OS, do not recreate the VM
1028
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1029
        restart the VM (at the hypervisor level)
1030
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1031
        not accepted here, since that mode is handled differently, in
1032
        cmdlib, and translates into full stop and start of the
1033
        instance (instead of a call_instance_reboot RPC)
1034
  @rtype: None
1035

1036
  """
1037
  running_instances = GetInstanceList([instance.hypervisor])
1038

    
1039
  if instance.name not in running_instances:
1040
    _Fail("Cannot reboot instance %s that is not running", instance.name)
1041

    
1042
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1043
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1044
    try:
1045
      hyper.RebootInstance(instance)
1046
    except errors.HypervisorError, err:
1047
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1048
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1049
    try:
1050
      InstanceShutdown(instance)
1051
      return StartInstance(instance)
1052
    except errors.HypervisorError, err:
1053
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1054
  else:
1055
    _Fail("Invalid reboot_type received: %s", reboot_type)
1056

    
1057

    
1058
def MigrationInfo(instance):
1059
  """Gather information about an instance to be migrated.
1060

1061
  @type instance: L{objects.Instance}
1062
  @param instance: the instance definition
1063

1064
  """
1065
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1066
  try:
1067
    info = hyper.MigrationInfo(instance)
1068
  except errors.HypervisorError, err:
1069
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1070
  return info
1071

    
1072

    
1073
def AcceptInstance(instance, info, target):
1074
  """Prepare the node to accept an instance.
1075

1076
  @type instance: L{objects.Instance}
1077
  @param instance: the instance definition
1078
  @type info: string/data (opaque)
1079
  @param info: migration information, from the source node
1080
  @type target: string
1081
  @param target: target host (usually ip), on this node
1082

1083
  """
1084
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1085
  try:
1086
    hyper.AcceptInstance(instance, info, target)
1087
  except errors.HypervisorError, err:
1088
    _Fail("Failed to accept instance: %s", err, exc=True)
1089

    
1090

    
1091
def FinalizeMigration(instance, info, success):
1092
  """Finalize any preparation to accept an instance.
1093

1094
  @type instance: L{objects.Instance}
1095
  @param instance: the instance definition
1096
  @type info: string/data (opaque)
1097
  @param info: migration information, from the source node
1098
  @type success: boolean
1099
  @param success: whether the migration was a success or a failure
1100

1101
  """
1102
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1103
  try:
1104
    hyper.FinalizeMigration(instance, info, success)
1105
  except errors.HypervisorError, err:
1106
    _Fail("Failed to finalize migration: %s", err, exc=True)
1107

    
1108

    
1109
def MigrateInstance(instance, target, live):
1110
  """Migrates an instance to another node.
1111

1112
  @type instance: L{objects.Instance}
1113
  @param instance: the instance definition
1114
  @type target: string
1115
  @param target: the target node name
1116
  @type live: boolean
1117
  @param live: whether the migration should be done live or not (the
1118
      interpretation of this parameter is left to the hypervisor)
1119
  @rtype: tuple
1120
  @return: a tuple of (success, msg) where:
1121
      - succes is a boolean denoting the success/failure of the operation
1122
      - msg is a string with details in case of failure
1123

1124
  """
1125
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1126

    
1127
  try:
1128
    hyper.MigrateInstance(instance.name, target, live)
1129
  except errors.HypervisorError, err:
1130
    _Fail("Failed to migrate instance: %s", err, exc=True)
1131

    
1132

    
1133
def BlockdevCreate(disk, size, owner, on_primary, info):
1134
  """Creates a block device for an instance.
1135

1136
  @type disk: L{objects.Disk}
1137
  @param disk: the object describing the disk we should create
1138
  @type size: int
1139
  @param size: the size of the physical underlying device, in MiB
1140
  @type owner: str
1141
  @param owner: the name of the instance for which disk is created,
1142
      used for device cache data
1143
  @type on_primary: boolean
1144
  @param on_primary:  indicates if it is the primary node or not
1145
  @type info: string
1146
  @param info: string that will be sent to the physical device
1147
      creation, used for example to set (LVM) tags on LVs
1148

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

1153
  """
1154
  clist = []
1155
  if disk.children:
1156
    for child in disk.children:
1157
      try:
1158
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1159
      except errors.BlockDeviceError, err:
1160
        _Fail("Can't assemble device %s: %s", child, err)
1161
      if on_primary or disk.AssembleOnSecondary():
1162
        # we need the children open in case the device itself has to
1163
        # be assembled
1164
        try:
1165
          crdev.Open()
1166
        except errors.BlockDeviceError, err:
1167
          _Fail("Can't make child '%s' read-write: %s", child, err)
1168
      clist.append(crdev)
1169

    
1170
  try:
1171
    device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
1172
  except errors.BlockDeviceError, err:
1173
    _Fail("Can't create block device: %s", err)
1174

    
1175
  if on_primary or disk.AssembleOnSecondary():
1176
    try:
1177
      device.Assemble()
1178
    except errors.BlockDeviceError, err:
1179
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1180
    device.SetSyncSpeed(constants.SYNC_SPEED)
1181
    if on_primary or disk.OpenOnSecondary():
1182
      try:
1183
        device.Open(force=True)
1184
      except errors.BlockDeviceError, err:
1185
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1186
    DevCacheManager.UpdateCache(device.dev_path, owner,
1187
                                on_primary, disk.iv_name)
1188

    
1189
  device.SetInfo(info)
1190

    
1191
  return device.unique_id
1192

    
1193

    
1194
def BlockdevRemove(disk):
1195
  """Remove a block device.
1196

1197
  @note: This is intended to be called recursively.
1198

1199
  @type disk: L{objects.Disk}
1200
  @param disk: the disk object we should remove
1201
  @rtype: boolean
1202
  @return: the success of the operation
1203

1204
  """
1205
  msgs = []
1206
  try:
1207
    rdev = _RecursiveFindBD(disk)
1208
  except errors.BlockDeviceError, err:
1209
    # probably can't attach
1210
    logging.info("Can't attach to device %s in remove", disk)
1211
    rdev = None
1212
  if rdev is not None:
1213
    r_path = rdev.dev_path
1214
    try:
1215
      rdev.Remove()
1216
    except errors.BlockDeviceError, err:
1217
      msgs.append(str(err))
1218
    if not msgs:
1219
      DevCacheManager.RemoveCache(r_path)
1220

    
1221
  if disk.children:
1222
    for child in disk.children:
1223
      try:
1224
        BlockdevRemove(child)
1225
      except RPCFail, err:
1226
        msgs.append(str(err))
1227

    
1228
  if msgs:
1229
    _Fail("; ".join(msgs))
1230

    
1231

    
1232
def _RecursiveAssembleBD(disk, owner, as_primary):
1233
  """Activate a block device for an instance.
1234

1235
  This is run on the primary and secondary nodes for an instance.
1236

1237
  @note: this function is called recursively.
1238

1239
  @type disk: L{objects.Disk}
1240
  @param disk: the disk we try to assemble
1241
  @type owner: str
1242
  @param owner: the name of the instance which owns the disk
1243
  @type as_primary: boolean
1244
  @param as_primary: if we should make the block device
1245
      read/write
1246

1247
  @return: the assembled device or None (in case no device
1248
      was assembled)
1249
  @raise errors.BlockDeviceError: in case there is an error
1250
      during the activation of the children or the device
1251
      itself
1252

1253
  """
1254
  children = []
1255
  if disk.children:
1256
    mcn = disk.ChildrenNeeded()
1257
    if mcn == -1:
1258
      mcn = 0 # max number of Nones allowed
1259
    else:
1260
      mcn = len(disk.children) - mcn # max number of Nones
1261
    for chld_disk in disk.children:
1262
      try:
1263
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1264
      except errors.BlockDeviceError, err:
1265
        if children.count(None) >= mcn:
1266
          raise
1267
        cdev = None
1268
        logging.error("Error in child activation (but continuing): %s",
1269
                      str(err))
1270
      children.append(cdev)
1271

    
1272
  if as_primary or disk.AssembleOnSecondary():
1273
    r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
1274
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1275
    result = r_dev
1276
    if as_primary or disk.OpenOnSecondary():
1277
      r_dev.Open()
1278
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1279
                                as_primary, disk.iv_name)
1280

    
1281
  else:
1282
    result = True
1283
  return result
1284

    
1285

    
1286
def BlockdevAssemble(disk, owner, as_primary):
1287
  """Activate a block device for an instance.
1288

1289
  This is a wrapper over _RecursiveAssembleBD.
1290

1291
  @rtype: str or boolean
1292
  @return: a C{/dev/...} path for primary nodes, and
1293
      C{True} for secondary nodes
1294

1295
  """
1296
  try:
1297
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1298
    if isinstance(result, bdev.BlockDev):
1299
      result = result.dev_path
1300
  except errors.BlockDeviceError, err:
1301
    _Fail("Error while assembling disk: %s", err, exc=True)
1302

    
1303
  return result
1304

    
1305

    
1306
def BlockdevShutdown(disk):
1307
  """Shut down a block device.
1308

1309
  First, if the device is assembled (Attach() is successful), then
1310
  the device is shutdown. Then the children of the device are
1311
  shutdown.
1312

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

1317
  @type disk: L{objects.Disk}
1318
  @param disk: the description of the disk we should
1319
      shutdown
1320
  @rtype: None
1321

1322
  """
1323
  msgs = []
1324
  r_dev = _RecursiveFindBD(disk)
1325
  if r_dev is not None:
1326
    r_path = r_dev.dev_path
1327
    try:
1328
      r_dev.Shutdown()
1329
      DevCacheManager.RemoveCache(r_path)
1330
    except errors.BlockDeviceError, err:
1331
      msgs.append(str(err))
1332

    
1333
  if disk.children:
1334
    for child in disk.children:
1335
      try:
1336
        BlockdevShutdown(child)
1337
      except RPCFail, err:
1338
        msgs.append(str(err))
1339

    
1340
  if msgs:
1341
    _Fail("; ".join(msgs))
1342

    
1343

    
1344
def BlockdevAddchildren(parent_cdev, new_cdevs):
1345
  """Extend a mirrored block device.
1346

1347
  @type parent_cdev: L{objects.Disk}
1348
  @param parent_cdev: the disk to which we should add children
1349
  @type new_cdevs: list of L{objects.Disk}
1350
  @param new_cdevs: the list of children which we should add
1351
  @rtype: None
1352

1353
  """
1354
  parent_bdev = _RecursiveFindBD(parent_cdev)
1355
  if parent_bdev is None:
1356
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1357
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1358
  if new_bdevs.count(None) > 0:
1359
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1360
  parent_bdev.AddChildren(new_bdevs)
1361

    
1362

    
1363
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1364
  """Shrink a mirrored block device.
1365

1366
  @type parent_cdev: L{objects.Disk}
1367
  @param parent_cdev: the disk from which we should remove children
1368
  @type new_cdevs: list of L{objects.Disk}
1369
  @param new_cdevs: the list of children which we should remove
1370
  @rtype: None
1371

1372
  """
1373
  parent_bdev = _RecursiveFindBD(parent_cdev)
1374
  if parent_bdev is None:
1375
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1376
  devs = []
1377
  for disk in new_cdevs:
1378
    rpath = disk.StaticDevPath()
1379
    if rpath is None:
1380
      bd = _RecursiveFindBD(disk)
1381
      if bd is None:
1382
        _Fail("Can't find device %s while removing children", disk)
1383
      else:
1384
        devs.append(bd.dev_path)
1385
    else:
1386
      devs.append(rpath)
1387
  parent_bdev.RemoveChildren(devs)
1388

    
1389

    
1390
def BlockdevGetmirrorstatus(disks):
1391
  """Get the mirroring status of a list of devices.
1392

1393
  @type disks: list of L{objects.Disk}
1394
  @param disks: the list of disks which we should query
1395
  @rtype: disk
1396
  @return:
1397
      a list of (mirror_done, estimated_time) tuples, which
1398
      are the result of L{bdev.BlockDev.CombinedSyncStatus}
1399
  @raise errors.BlockDeviceError: if any of the disks cannot be
1400
      found
1401

1402
  """
1403
  stats = []
1404
  for dsk in disks:
1405
    rbd = _RecursiveFindBD(dsk)
1406
    if rbd is None:
1407
      _Fail("Can't find device %s", dsk)
1408

    
1409
    stats.append(rbd.CombinedSyncStatus())
1410

    
1411
  return stats
1412

    
1413

    
1414
def _RecursiveFindBD(disk):
1415
  """Check if a device is activated.
1416

1417
  If so, return information about the real device.
1418

1419
  @type disk: L{objects.Disk}
1420
  @param disk: the disk object we need to find
1421

1422
  @return: None if the device can't be found,
1423
      otherwise the device instance
1424

1425
  """
1426
  children = []
1427
  if disk.children:
1428
    for chdisk in disk.children:
1429
      children.append(_RecursiveFindBD(chdisk))
1430

    
1431
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1432

    
1433

    
1434
def BlockdevFind(disk):
1435
  """Check if a device is activated.
1436

1437
  If it is, return information about the real device.
1438

1439
  @type disk: L{objects.Disk}
1440
  @param disk: the disk to find
1441
  @rtype: None or objects.BlockDevStatus
1442
  @return: None if the disk cannot be found, otherwise a the current
1443
           information
1444

1445
  """
1446
  try:
1447
    rbd = _RecursiveFindBD(disk)
1448
  except errors.BlockDeviceError, err:
1449
    _Fail("Failed to find device: %s", err, exc=True)
1450

    
1451
  if rbd is None:
1452
    return None
1453

    
1454
  return rbd.GetSyncStatus()
1455

    
1456

    
1457
def BlockdevGetsize(disks):
1458
  """Computes the size of the given disks.
1459

1460
  If a disk is not found, returns None instead.
1461

1462
  @type disks: list of L{objects.Disk}
1463
  @param disks: the list of disk to compute the size for
1464
  @rtype: list
1465
  @return: list with elements None if the disk cannot be found,
1466
      otherwise the size
1467

1468
  """
1469
  result = []
1470
  for cf in disks:
1471
    try:
1472
      rbd = _RecursiveFindBD(cf)
1473
    except errors.BlockDeviceError, err:
1474
      result.append(None)
1475
      continue
1476
    if rbd is None:
1477
      result.append(None)
1478
    else:
1479
      result.append(rbd.GetActualSize())
1480
  return result
1481

    
1482

    
1483
def BlockdevExport(disk, dest_node, dest_path, cluster_name):
1484
  """Export a block device to a remote node.
1485

1486
  @type disk: L{objects.Disk}
1487
  @param disk: the description of the disk to export
1488
  @type dest_node: str
1489
  @param dest_node: the destination node to export to
1490
  @type dest_path: str
1491
  @param dest_path: the destination path on the target node
1492
  @type cluster_name: str
1493
  @param cluster_name: the cluster name, needed for SSH hostalias
1494
  @rtype: None
1495

1496
  """
1497
  real_disk = _RecursiveFindBD(disk)
1498
  if real_disk is None:
1499
    _Fail("Block device '%s' is not set up", disk)
1500

    
1501
  real_disk.Open()
1502

    
1503
  # the block size on the read dd is 1MiB to match our units
1504
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
1505
                               "dd if=%s bs=1048576 count=%s",
1506
                               real_disk.dev_path, str(disk.size))
1507

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

    
1517
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1518
                                                   constants.GANETI_RUNAS,
1519
                                                   destcmd)
1520

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

    
1524
  result = utils.RunCmd(["bash", "-c", command])
1525

    
1526
  if result.failed:
1527
    _Fail("Disk copy command '%s' returned error: %s"
1528
          " output: %s", command, result.fail_reason, result.output)
1529

    
1530

    
1531
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1532
  """Write a file to the filesystem.
1533

1534
  This allows the master to overwrite(!) a file. It will only perform
1535
  the operation if the file belongs to a list of configuration files.
1536

1537
  @type file_name: str
1538
  @param file_name: the target file name
1539
  @type data: str
1540
  @param data: the new contents of the file
1541
  @type mode: int
1542
  @param mode: the mode to give the file (can be None)
1543
  @type uid: int
1544
  @param uid: the owner of the file (can be -1 for default)
1545
  @type gid: int
1546
  @param gid: the group of the file (can be -1 for default)
1547
  @type atime: float
1548
  @param atime: the atime to set on the file (can be None)
1549
  @type mtime: float
1550
  @param mtime: the mtime to set on the file (can be None)
1551
  @rtype: None
1552

1553
  """
1554
  if not os.path.isabs(file_name):
1555
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
1556

    
1557
  if file_name not in _ALLOWED_UPLOAD_FILES:
1558
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
1559
          file_name)
1560

    
1561
  raw_data = _Decompress(data)
1562

    
1563
  utils.WriteFile(file_name, data=raw_data, mode=mode, uid=uid, gid=gid,
1564
                  atime=atime, mtime=mtime)
1565

    
1566

    
1567
def WriteSsconfFiles(values):
1568
  """Update all ssconf files.
1569

1570
  Wrapper around the SimpleStore.WriteFiles.
1571

1572
  """
1573
  ssconf.SimpleStore().WriteFiles(values)
1574

    
1575

    
1576
def _ErrnoOrStr(err):
1577
  """Format an EnvironmentError exception.
1578

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

1583
  @type err: L{EnvironmentError}
1584
  @param err: the exception to format
1585

1586
  """
1587
  if hasattr(err, 'errno'):
1588
    detail = errno.errorcode[err.errno]
1589
  else:
1590
    detail = str(err)
1591
  return detail
1592

    
1593

    
1594
def _OSOndiskAPIVersion(name, os_dir):
1595
  """Compute and return the API version of a given OS.
1596

1597
  This function will try to read the API version of the OS given by
1598
  the 'name' parameter and residing in the 'os_dir' directory.
1599

1600
  @type name: str
1601
  @param name: the OS name we should look for
1602
  @type os_dir: str
1603
  @param os_dir: the directory inwhich we should look for the OS
1604
  @rtype: tuple
1605
  @return: tuple (status, data) with status denoting the validity and
1606
      data holding either the vaid versions or an error message
1607

1608
  """
1609
  api_file = os.path.sep.join([os_dir, constants.OS_API_FILE])
1610

    
1611
  try:
1612
    st = os.stat(api_file)
1613
  except EnvironmentError, err:
1614
    return False, ("Required file '%s' not found under path %s: %s" %
1615
                   (constants.OS_API_FILE, os_dir, _ErrnoOrStr(err)))
1616

    
1617
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1618
    return False, ("File '%s' in %s is not a regular file" %
1619
                   (constants.OS_API_FILE, os_dir))
1620

    
1621
  try:
1622
    api_versions = utils.ReadFile(api_file).splitlines()
1623
  except EnvironmentError, err:
1624
    return False, ("Error while reading the API version file at %s: %s" %
1625
                   (api_file, _ErrnoOrStr(err)))
1626

    
1627
  try:
1628
    api_versions = [int(version.strip()) for version in api_versions]
1629
  except (TypeError, ValueError), err:
1630
    return False, ("API version(s) can't be converted to integer: %s" %
1631
                   str(err))
1632

    
1633
  return True, api_versions
1634

    
1635

    
1636
def DiagnoseOS(top_dirs=None):
1637
  """Compute the validity for all OSes.
1638

1639
  @type top_dirs: list
1640
  @param top_dirs: the list of directories in which to
1641
      search (if not given defaults to
1642
      L{constants.OS_SEARCH_PATH})
1643
  @rtype: list of L{objects.OS}
1644
  @return: a list of tuples (name, path, status, diagnose, variants)
1645
      for all (potential) OSes under all search paths, where:
1646
          - name is the (potential) OS name
1647
          - path is the full path to the OS
1648
          - status True/False is the validity of the OS
1649
          - diagnose is the error message for an invalid OS, otherwise empty
1650
          - variants is a list of supported OS variants, if any
1651

1652
  """
1653
  if top_dirs is None:
1654
    top_dirs = constants.OS_SEARCH_PATH
1655

    
1656
  result = []
1657
  for dir_name in top_dirs:
1658
    if os.path.isdir(dir_name):
1659
      try:
1660
        f_names = utils.ListVisibleFiles(dir_name)
1661
      except EnvironmentError, err:
1662
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
1663
        break
1664
      for name in f_names:
1665
        os_path = os.path.sep.join([dir_name, name])
1666
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
1667
        if status:
1668
          diagnose = ""
1669
          variants = os_inst.supported_variants
1670
        else:
1671
          diagnose = os_inst
1672
          variants = []
1673
        result.append((name, os_path, status, diagnose, variants))
1674

    
1675
  return result
1676

    
1677

    
1678
def _TryOSFromDisk(name, base_dir=None):
1679
  """Create an OS instance from disk.
1680

1681
  This function will return an OS instance if the given name is a
1682
  valid OS name.
1683

1684
  @type base_dir: string
1685
  @keyword base_dir: Base directory containing OS installations.
1686
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1687
  @rtype: tuple
1688
  @return: success and either the OS instance if we find a valid one,
1689
      or error message
1690

1691
  """
1692
  if base_dir is None:
1693
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1694
    if os_dir is None:
1695
      return False, "Directory for OS %s not found in search path" % name
1696
  else:
1697
    os_dir = os.path.sep.join([base_dir, name])
1698

    
1699
  status, api_versions = _OSOndiskAPIVersion(name, os_dir)
1700
  if not status:
1701
    # push the error up
1702
    return status, api_versions
1703

    
1704
  if not constants.OS_API_VERSIONS.intersection(api_versions):
1705
    return False, ("API version mismatch for path '%s': found %s, want %s." %
1706
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
1707

    
1708
  # OS Files dictionary, we will populate it with the absolute path names
1709
  os_files = dict.fromkeys(constants.OS_SCRIPTS)
1710

    
1711
  if max(api_versions) >= constants.OS_API_V15:
1712
    os_files[constants.OS_VARIANTS_FILE] = ''
1713

    
1714
  for name in os_files:
1715
    os_files[name] = os.path.sep.join([os_dir, name])
1716

    
1717
    try:
1718
      st = os.stat(os_files[name])
1719
    except EnvironmentError, err:
1720
      return False, ("File '%s' under path '%s' is missing (%s)" %
1721
                     (name, os_dir, _ErrnoOrStr(err)))
1722

    
1723
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1724
      return False, ("File '%s' under path '%s' is not a regular file" %
1725
                     (name, os_dir))
1726

    
1727
    if name in constants.OS_SCRIPTS:
1728
      if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1729
        return False, ("File '%s' under path '%s' is not executable" %
1730
                       (name, os_dir))
1731

    
1732
  variants = None
1733
  if constants.OS_VARIANTS_FILE in os_files:
1734
    variants_file = os_files[constants.OS_VARIANTS_FILE]
1735
    try:
1736
      variants = utils.ReadFile(variants_file).splitlines()
1737
    except EnvironmentError, err:
1738
      return False, ("Error while reading the OS variants file at %s: %s" %
1739
                     (variants_file, _ErrnoOrStr(err)))
1740
    if not variants:
1741
      return False, ("No supported os variant found")
1742

    
1743
  os_obj = objects.OS(name=name, path=os_dir,
1744
                      create_script=os_files[constants.OS_SCRIPT_CREATE],
1745
                      export_script=os_files[constants.OS_SCRIPT_EXPORT],
1746
                      import_script=os_files[constants.OS_SCRIPT_IMPORT],
1747
                      rename_script=os_files[constants.OS_SCRIPT_RENAME],
1748
                      supported_variants=variants,
1749
                      api_versions=api_versions)
1750
  return True, os_obj
1751

    
1752

    
1753
def OSFromDisk(name, base_dir=None):
1754
  """Create an OS instance from disk.
1755

1756
  This function will return an OS instance if the given name is a
1757
  valid OS name. Otherwise, it will raise an appropriate
1758
  L{RPCFail} exception, detailing why this is not a valid OS.
1759

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

1763
  @type base_dir: string
1764
  @keyword base_dir: Base directory containing OS installations.
1765
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1766
  @rtype: L{objects.OS}
1767
  @return: the OS instance if we find a valid one
1768
  @raise RPCFail: if we don't find a valid OS
1769

1770
  """
1771
  name_only = name.split('+',1)[0]
1772
  status, payload = _TryOSFromDisk(name_only, base_dir)
1773

    
1774
  if not status:
1775
    _Fail(payload)
1776

    
1777
  return payload
1778

    
1779

    
1780
def OSEnvironment(instance, os, debug=0):
1781
  """Calculate the environment for an os script.
1782

1783
  @type instance: L{objects.Instance}
1784
  @param instance: target instance for the os script run
1785
  @type os: L{objects.OS}
1786
  @param os: operating system for which the environment is being built
1787
  @type debug: integer
1788
  @param debug: debug level (0 or 1, for OS Api 10)
1789
  @rtype: dict
1790
  @return: dict of environment variables
1791
  @raise errors.BlockDeviceError: if the block device
1792
      cannot be found
1793

1794
  """
1795
  result = {}
1796
  api_version = max(constants.OS_API_VERSIONS.intersection(os.api_versions))
1797
  result['OS_API_VERSION'] = '%d' % api_version
1798
  result['INSTANCE_NAME'] = instance.name
1799
  result['INSTANCE_OS'] = instance.os
1800
  result['HYPERVISOR'] = instance.hypervisor
1801
  result['DISK_COUNT'] = '%d' % len(instance.disks)
1802
  result['NIC_COUNT'] = '%d' % len(instance.nics)
1803
  result['DEBUG_LEVEL'] = '%d' % debug
1804
  if api_version >= constants.OS_API_V15:
1805
    try:
1806
      variant = instance.os.split('+', 1)[1]
1807
    except IndexError:
1808
      variant = os.supported_variants[0]
1809
    result['OS_VARIANT'] = variant
1810
  for idx, disk in enumerate(instance.disks):
1811
    real_disk = _RecursiveFindBD(disk)
1812
    if real_disk is None:
1813
      raise errors.BlockDeviceError("Block device '%s' is not set up" %
1814
                                    str(disk))
1815
    real_disk.Open()
1816
    result['DISK_%d_PATH' % idx] = real_disk.dev_path
1817
    result['DISK_%d_ACCESS' % idx] = disk.mode
1818
    if constants.HV_DISK_TYPE in instance.hvparams:
1819
      result['DISK_%d_FRONTEND_TYPE' % idx] = \
1820
        instance.hvparams[constants.HV_DISK_TYPE]
1821
    if disk.dev_type in constants.LDS_BLOCK:
1822
      result['DISK_%d_BACKEND_TYPE' % idx] = 'block'
1823
    elif disk.dev_type == constants.LD_FILE:
1824
      result['DISK_%d_BACKEND_TYPE' % idx] = \
1825
        'file:%s' % disk.physical_id[0]
1826
  for idx, nic in enumerate(instance.nics):
1827
    result['NIC_%d_MAC' % idx] = nic.mac
1828
    if nic.ip:
1829
      result['NIC_%d_IP' % idx] = nic.ip
1830
    result['NIC_%d_MODE' % idx] = nic.nicparams[constants.NIC_MODE]
1831
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
1832
      result['NIC_%d_BRIDGE' % idx] = nic.nicparams[constants.NIC_LINK]
1833
    if nic.nicparams[constants.NIC_LINK]:
1834
      result['NIC_%d_LINK' % idx] = nic.nicparams[constants.NIC_LINK]
1835
    if constants.HV_NIC_TYPE in instance.hvparams:
1836
      result['NIC_%d_FRONTEND_TYPE' % idx] = \
1837
        instance.hvparams[constants.HV_NIC_TYPE]
1838

    
1839
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
1840
    for key, value in source.items():
1841
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
1842

    
1843
  return result
1844

    
1845
def BlockdevGrow(disk, amount):
1846
  """Grow a stack of block devices.
1847

1848
  This function is called recursively, with the childrens being the
1849
  first ones to resize.
1850

1851
  @type disk: L{objects.Disk}
1852
  @param disk: the disk to be grown
1853
  @rtype: (status, result)
1854
  @return: a tuple with the status of the operation
1855
      (True/False), and the errors message if status
1856
      is False
1857

1858
  """
1859
  r_dev = _RecursiveFindBD(disk)
1860
  if r_dev is None:
1861
    _Fail("Cannot find block device %s", disk)
1862

    
1863
  try:
1864
    r_dev.Grow(amount)
1865
  except errors.BlockDeviceError, err:
1866
    _Fail("Failed to grow block device: %s", err, exc=True)
1867

    
1868

    
1869
def BlockdevSnapshot(disk):
1870
  """Create a snapshot copy of a block device.
1871

1872
  This function is called recursively, and the snapshot is actually created
1873
  just for the leaf lvm backend device.
1874

1875
  @type disk: L{objects.Disk}
1876
  @param disk: the disk to be snapshotted
1877
  @rtype: string
1878
  @return: snapshot disk path
1879

1880
  """
1881
  if disk.children:
1882
    if len(disk.children) == 1:
1883
      # only one child, let's recurse on it
1884
      return BlockdevSnapshot(disk.children[0])
1885
    else:
1886
      # more than one child, choose one that matches
1887
      for child in disk.children:
1888
        if child.size == disk.size:
1889
          # return implies breaking the loop
1890
          return BlockdevSnapshot(child)
1891
  elif disk.dev_type == constants.LD_LV:
1892
    r_dev = _RecursiveFindBD(disk)
1893
    if r_dev is not None:
1894
      # let's stay on the safe side and ask for the full size, for now
1895
      return r_dev.Snapshot(disk.size)
1896
    else:
1897
      _Fail("Cannot find block device %s", disk)
1898
  else:
1899
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
1900
          disk.unique_id, disk.dev_type)
1901

    
1902

    
1903
def ExportSnapshot(disk, dest_node, instance, cluster_name, idx):
1904
  """Export a block device snapshot to a remote node.
1905

1906
  @type disk: L{objects.Disk}
1907
  @param disk: the description of the disk to export
1908
  @type dest_node: str
1909
  @param dest_node: the destination node to export to
1910
  @type instance: L{objects.Instance}
1911
  @param instance: the instance object to whom the disk belongs
1912
  @type cluster_name: str
1913
  @param cluster_name: the cluster name, needed for SSH hostalias
1914
  @type idx: int
1915
  @param idx: the index of the disk in the instance's disk list,
1916
      used to export to the OS scripts environment
1917
  @rtype: None
1918

1919
  """
1920
  inst_os = OSFromDisk(instance.os)
1921
  export_env = OSEnvironment(instance, inst_os)
1922

    
1923
  export_script = inst_os.export_script
1924

    
1925
  logfile = "%s/exp-%s-%s-%s.log" % (constants.LOG_OS_DIR, inst_os.name,
1926
                                     instance.name, int(time.time()))
1927
  if not os.path.exists(constants.LOG_OS_DIR):
1928
    os.mkdir(constants.LOG_OS_DIR, 0750)
1929
  real_disk = _RecursiveFindBD(disk)
1930
  if real_disk is None:
1931
    _Fail("Block device '%s' is not set up", disk)
1932

    
1933
  real_disk.Open()
1934

    
1935
  export_env['EXPORT_DEVICE'] = real_disk.dev_path
1936
  export_env['EXPORT_INDEX'] = str(idx)
1937

    
1938
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1939
  destfile = disk.physical_id[1]
1940

    
1941
  # the target command is built out of three individual commands,
1942
  # which are joined by pipes; we check each individual command for
1943
  # valid parameters
1944
  expcmd = utils.BuildShellCmd("set -e; set -o pipefail; cd %s; %s 2>%s",
1945
                               inst_os.path, export_script, logfile)
1946

    
1947
  comprcmd = "gzip"
1948

    
1949
  destcmd = utils.BuildShellCmd("mkdir -p %s && cat > %s/%s",
1950
                                destdir, destdir, destfile)
1951
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1952
                                                   constants.GANETI_RUNAS,
1953
                                                   destcmd)
1954

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

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

    
1960
  if result.failed:
1961
    _Fail("OS snapshot export command '%s' returned error: %s"
1962
          " output: %s", command, result.fail_reason, result.output)
1963

    
1964

    
1965
def FinalizeExport(instance, snap_disks):
1966
  """Write out the export configuration information.
1967

1968
  @type instance: L{objects.Instance}
1969
  @param instance: the instance which we export, used for
1970
      saving configuration
1971
  @type snap_disks: list of L{objects.Disk}
1972
  @param snap_disks: list of snapshot block devices, which
1973
      will be used to get the actual name of the dump file
1974

1975
  @rtype: None
1976

1977
  """
1978
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1979
  finaldestdir = os.path.join(constants.EXPORT_DIR, instance.name)
1980

    
1981
  config = objects.SerializableConfigParser()
1982

    
1983
  config.add_section(constants.INISECT_EXP)
1984
  config.set(constants.INISECT_EXP, 'version', '0')
1985
  config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
1986
  config.set(constants.INISECT_EXP, 'source', instance.primary_node)
1987
  config.set(constants.INISECT_EXP, 'os', instance.os)
1988
  config.set(constants.INISECT_EXP, 'compression', 'gzip')
1989

    
1990
  config.add_section(constants.INISECT_INS)
1991
  config.set(constants.INISECT_INS, 'name', instance.name)
1992
  config.set(constants.INISECT_INS, 'memory', '%d' %
1993
             instance.beparams[constants.BE_MEMORY])
1994
  config.set(constants.INISECT_INS, 'vcpus', '%d' %
1995
             instance.beparams[constants.BE_VCPUS])
1996
  config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
1997

    
1998
  nic_total = 0
1999
  for nic_count, nic in enumerate(instance.nics):
2000
    nic_total += 1
2001
    config.set(constants.INISECT_INS, 'nic%d_mac' %
2002
               nic_count, '%s' % nic.mac)
2003
    config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
2004
    config.set(constants.INISECT_INS, 'nic%d_bridge' % nic_count,
2005
               '%s' % nic.bridge)
2006
  # TODO: redundant: on load can read nics until it doesn't exist
2007
  config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_total)
2008

    
2009
  disk_total = 0
2010
  for disk_count, disk in enumerate(snap_disks):
2011
    if disk:
2012
      disk_total += 1
2013
      config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
2014
                 ('%s' % disk.iv_name))
2015
      config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
2016
                 ('%s' % disk.physical_id[1]))
2017
      config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
2018
                 ('%d' % disk.size))
2019

    
2020
  config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_total)
2021

    
2022
  utils.WriteFile(os.path.join(destdir, constants.EXPORT_CONF_FILE),
2023
                  data=config.Dumps())
2024
  shutil.rmtree(finaldestdir, True)
2025
  shutil.move(destdir, finaldestdir)
2026

    
2027

    
2028
def ExportInfo(dest):
2029
  """Get export configuration information.
2030

2031
  @type dest: str
2032
  @param dest: directory containing the export
2033

2034
  @rtype: L{objects.SerializableConfigParser}
2035
  @return: a serializable config file containing the
2036
      export info
2037

2038
  """
2039
  cff = os.path.join(dest, constants.EXPORT_CONF_FILE)
2040

    
2041
  config = objects.SerializableConfigParser()
2042
  config.read(cff)
2043

    
2044
  if (not config.has_section(constants.INISECT_EXP) or
2045
      not config.has_section(constants.INISECT_INS)):
2046
    _Fail("Export info file doesn't have the required fields")
2047

    
2048
  return config.Dumps()
2049

    
2050

    
2051
def ImportOSIntoInstance(instance, src_node, src_images, cluster_name):
2052
  """Import an os image into an instance.
2053

2054
  @type instance: L{objects.Instance}
2055
  @param instance: instance to import the disks into
2056
  @type src_node: string
2057
  @param src_node: source node for the disk images
2058
  @type src_images: list of string
2059
  @param src_images: absolute paths of the disk images
2060
  @rtype: list of boolean
2061
  @return: each boolean represent the success of importing the n-th disk
2062

2063
  """
2064
  inst_os = OSFromDisk(instance.os)
2065
  import_env = OSEnvironment(instance, inst_os)
2066
  import_script = inst_os.import_script
2067

    
2068
  logfile = "%s/import-%s-%s-%s.log" % (constants.LOG_OS_DIR, instance.os,
2069
                                        instance.name, int(time.time()))
2070
  if not os.path.exists(constants.LOG_OS_DIR):
2071
    os.mkdir(constants.LOG_OS_DIR, 0750)
2072

    
2073
  comprcmd = "gunzip"
2074
  impcmd = utils.BuildShellCmd("(cd %s; %s >%s 2>&1)", inst_os.path,
2075
                               import_script, logfile)
2076

    
2077
  final_result = []
2078
  for idx, image in enumerate(src_images):
2079
    if image:
2080
      destcmd = utils.BuildShellCmd('cat %s', image)
2081
      remotecmd = _GetSshRunner(cluster_name).BuildCmd(src_node,
2082
                                                       constants.GANETI_RUNAS,
2083
                                                       destcmd)
2084
      command = '|'.join([utils.ShellQuoteArgs(remotecmd), comprcmd, impcmd])
2085
      import_env['IMPORT_DEVICE'] = import_env['DISK_%d_PATH' % idx]
2086
      import_env['IMPORT_INDEX'] = str(idx)
2087
      result = utils.RunCmd(command, env=import_env)
2088
      if result.failed:
2089
        logging.error("Disk import command '%s' returned error: %s"
2090
                      " output: %s", command, result.fail_reason,
2091
                      result.output)
2092
        final_result.append("error importing disk %d: %s, %s" %
2093
                            (idx, result.fail_reason, result.output[-100]))
2094

    
2095
  if final_result:
2096
    _Fail("; ".join(final_result), log=False)
2097

    
2098

    
2099
def ListExports():
2100
  """Return a list of exports currently available on this machine.
2101

2102
  @rtype: list
2103
  @return: list of the exports
2104

2105
  """
2106
  if os.path.isdir(constants.EXPORT_DIR):
2107
    return utils.ListVisibleFiles(constants.EXPORT_DIR)
2108
  else:
2109
    _Fail("No exports directory")
2110

    
2111

    
2112
def RemoveExport(export):
2113
  """Remove an existing export from the node.
2114

2115
  @type export: str
2116
  @param export: the name of the export to remove
2117
  @rtype: None
2118

2119
  """
2120
  target = os.path.join(constants.EXPORT_DIR, export)
2121

    
2122
  try:
2123
    shutil.rmtree(target)
2124
  except EnvironmentError, err:
2125
    _Fail("Error while removing the export: %s", err, exc=True)
2126

    
2127

    
2128
def BlockdevRename(devlist):
2129
  """Rename a list of block devices.
2130

2131
  @type devlist: list of tuples
2132
  @param devlist: list of tuples of the form  (disk,
2133
      new_logical_id, new_physical_id); disk is an
2134
      L{objects.Disk} object describing the current disk,
2135
      and new logical_id/physical_id is the name we
2136
      rename it to
2137
  @rtype: boolean
2138
  @return: True if all renames succeeded, False otherwise
2139

2140
  """
2141
  msgs = []
2142
  result = True
2143
  for disk, unique_id in devlist:
2144
    dev = _RecursiveFindBD(disk)
2145
    if dev is None:
2146
      msgs.append("Can't find device %s in rename" % str(disk))
2147
      result = False
2148
      continue
2149
    try:
2150
      old_rpath = dev.dev_path
2151
      dev.Rename(unique_id)
2152
      new_rpath = dev.dev_path
2153
      if old_rpath != new_rpath:
2154
        DevCacheManager.RemoveCache(old_rpath)
2155
        # FIXME: we should add the new cache information here, like:
2156
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2157
        # but we don't have the owner here - maybe parse from existing
2158
        # cache? for now, we only lose lvm data when we rename, which
2159
        # is less critical than DRBD or MD
2160
    except errors.BlockDeviceError, err:
2161
      msgs.append("Can't rename device '%s' to '%s': %s" %
2162
                  (dev, unique_id, err))
2163
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2164
      result = False
2165
  if not result:
2166
    _Fail("; ".join(msgs))
2167

    
2168

    
2169
def _TransformFileStorageDir(file_storage_dir):
2170
  """Checks whether given file_storage_dir is valid.
2171

2172
  Checks wheter the given file_storage_dir is within the cluster-wide
2173
  default file_storage_dir stored in SimpleStore. Only paths under that
2174
  directory are allowed.
2175

2176
  @type file_storage_dir: str
2177
  @param file_storage_dir: the path to check
2178

2179
  @return: the normalized path if valid, None otherwise
2180

2181
  """
2182
  cfg = _GetConfig()
2183
  file_storage_dir = os.path.normpath(file_storage_dir)
2184
  base_file_storage_dir = cfg.GetFileStorageDir()
2185
  if (not os.path.commonprefix([file_storage_dir, base_file_storage_dir]) ==
2186
      base_file_storage_dir):
2187
    _Fail("File storage directory '%s' is not under base file"
2188
          " storage directory '%s'", file_storage_dir, base_file_storage_dir)
2189
  return file_storage_dir
2190

    
2191

    
2192
def CreateFileStorageDir(file_storage_dir):
2193
  """Create file storage directory.
2194

2195
  @type file_storage_dir: str
2196
  @param file_storage_dir: directory to create
2197

2198
  @rtype: tuple
2199
  @return: tuple with first element a boolean indicating wheter dir
2200
      creation was successful or not
2201

2202
  """
2203
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2204
  if os.path.exists(file_storage_dir):
2205
    if not os.path.isdir(file_storage_dir):
2206
      _Fail("Specified storage dir '%s' is not a directory",
2207
            file_storage_dir)
2208
  else:
2209
    try:
2210
      os.makedirs(file_storage_dir, 0750)
2211
    except OSError, err:
2212
      _Fail("Cannot create file storage directory '%s': %s",
2213
            file_storage_dir, err, exc=True)
2214

    
2215

    
2216
def RemoveFileStorageDir(file_storage_dir):
2217
  """Remove file storage directory.
2218

2219
  Remove it only if it's empty. If not log an error and return.
2220

2221
  @type file_storage_dir: str
2222
  @param file_storage_dir: the directory we should cleanup
2223
  @rtype: tuple (success,)
2224
  @return: tuple of one element, C{success}, denoting
2225
      whether the operation was successful
2226

2227
  """
2228
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2229
  if os.path.exists(file_storage_dir):
2230
    if not os.path.isdir(file_storage_dir):
2231
      _Fail("Specified Storage directory '%s' is not a directory",
2232
            file_storage_dir)
2233
    # deletes dir only if empty, otherwise we want to fail the rpc call
2234
    try:
2235
      os.rmdir(file_storage_dir)
2236
    except OSError, err:
2237
      _Fail("Cannot remove file storage directory '%s': %s",
2238
            file_storage_dir, err)
2239

    
2240

    
2241
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2242
  """Rename the file storage directory.
2243

2244
  @type old_file_storage_dir: str
2245
  @param old_file_storage_dir: the current path
2246
  @type new_file_storage_dir: str
2247
  @param new_file_storage_dir: the name we should rename to
2248
  @rtype: tuple (success,)
2249
  @return: tuple of one element, C{success}, denoting
2250
      whether the operation was successful
2251

2252
  """
2253
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2254
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2255
  if not os.path.exists(new_file_storage_dir):
2256
    if os.path.isdir(old_file_storage_dir):
2257
      try:
2258
        os.rename(old_file_storage_dir, new_file_storage_dir)
2259
      except OSError, err:
2260
        _Fail("Cannot rename '%s' to '%s': %s",
2261
              old_file_storage_dir, new_file_storage_dir, err)
2262
    else:
2263
      _Fail("Specified storage dir '%s' is not a directory",
2264
            old_file_storage_dir)
2265
  else:
2266
    if os.path.exists(old_file_storage_dir):
2267
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2268
            old_file_storage_dir, new_file_storage_dir)
2269

    
2270

    
2271
def _EnsureJobQueueFile(file_name):
2272
  """Checks whether the given filename is in the queue directory.
2273

2274
  @type file_name: str
2275
  @param file_name: the file name we should check
2276
  @rtype: None
2277
  @raises RPCFail: if the file is not valid
2278

2279
  """
2280
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2281
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2282

    
2283
  if not result:
2284
    _Fail("Passed job queue file '%s' does not belong to"
2285
          " the queue directory '%s'", file_name, queue_dir)
2286

    
2287

    
2288
def JobQueueUpdate(file_name, content):
2289
  """Updates a file in the queue directory.
2290

2291
  This is just a wrapper over L{utils.WriteFile}, with proper
2292
  checking.
2293

2294
  @type file_name: str
2295
  @param file_name: the job file name
2296
  @type content: str
2297
  @param content: the new job contents
2298
  @rtype: boolean
2299
  @return: the success of the operation
2300

2301
  """
2302
  _EnsureJobQueueFile(file_name)
2303

    
2304
  # Write and replace the file atomically
2305
  utils.WriteFile(file_name, data=_Decompress(content))
2306

    
2307

    
2308
def JobQueueRename(old, new):
2309
  """Renames a job queue file.
2310

2311
  This is just a wrapper over os.rename with proper checking.
2312

2313
  @type old: str
2314
  @param old: the old (actual) file name
2315
  @type new: str
2316
  @param new: the desired file name
2317
  @rtype: tuple
2318
  @return: the success of the operation and payload
2319

2320
  """
2321
  _EnsureJobQueueFile(old)
2322
  _EnsureJobQueueFile(new)
2323

    
2324
  utils.RenameFile(old, new, mkdir=True)
2325

    
2326

    
2327
def JobQueueSetDrainFlag(drain_flag):
2328
  """Set the drain flag for the queue.
2329

2330
  This will set or unset the queue drain flag.
2331

2332
  @type drain_flag: boolean
2333
  @param drain_flag: if True, will set the drain flag, otherwise reset it.
2334
  @rtype: truple
2335
  @return: always True, None
2336
  @warning: the function always returns True
2337

2338
  """
2339
  if drain_flag:
2340
    utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True)
2341
  else:
2342
    utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
2343

    
2344

    
2345
def BlockdevClose(instance_name, disks):
2346
  """Closes the given block devices.
2347

2348
  This means they will be switched to secondary mode (in case of
2349
  DRBD).
2350

2351
  @param instance_name: if the argument is not empty, the symlinks
2352
      of this instance will be removed
2353
  @type disks: list of L{objects.Disk}
2354
  @param disks: the list of disks to be closed
2355
  @rtype: tuple (success, message)
2356
  @return: a tuple of success and message, where success
2357
      indicates the succes of the operation, and message
2358
      which will contain the error details in case we
2359
      failed
2360

2361
  """
2362
  bdevs = []
2363
  for cf in disks:
2364
    rd = _RecursiveFindBD(cf)
2365
    if rd is None:
2366
      _Fail("Can't find device %s", cf)
2367
    bdevs.append(rd)
2368

    
2369
  msg = []
2370
  for rd in bdevs:
2371
    try:
2372
      rd.Close()
2373
    except errors.BlockDeviceError, err:
2374
      msg.append(str(err))
2375
  if msg:
2376
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2377
  else:
2378
    if instance_name:
2379
      _RemoveBlockDevLinks(instance_name, disks)
2380

    
2381

    
2382
def ValidateHVParams(hvname, hvparams):
2383
  """Validates the given hypervisor parameters.
2384

2385
  @type hvname: string
2386
  @param hvname: the hypervisor name
2387
  @type hvparams: dict
2388
  @param hvparams: the hypervisor parameters to be validated
2389
  @rtype: None
2390

2391
  """
2392
  try:
2393
    hv_type = hypervisor.GetHypervisor(hvname)
2394
    hv_type.ValidateParameters(hvparams)
2395
  except errors.HypervisorError, err:
2396
    _Fail(str(err), log=False)
2397

    
2398

    
2399
def DemoteFromMC():
2400
  """Demotes the current node from master candidate role.
2401

2402
  """
2403
  # try to ensure we're not the master by mistake
2404
  master, myself = ssconf.GetMasterAndMyself()
2405
  if master == myself:
2406
    _Fail("ssconf status shows I'm the master node, will not demote")
2407
  pid_file = utils.DaemonPidFileName(constants.MASTERD)
2408
  if utils.IsProcessAlive(utils.ReadPidFile(pid_file)):
2409
    _Fail("The master daemon is running, will not demote")
2410
  try:
2411
    if os.path.isfile(constants.CLUSTER_CONF_FILE):
2412
      utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2413
  except EnvironmentError, err:
2414
    if err.errno != errno.ENOENT:
2415
      _Fail("Error while backing up cluster file: %s", err, exc=True)
2416
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2417

    
2418

    
2419
def _FindDisks(nodes_ip, disks):
2420
  """Sets the physical ID on disks and returns the block devices.
2421

2422
  """
2423
  # set the correct physical ID
2424
  my_name = utils.HostInfo().name
2425
  for cf in disks:
2426
    cf.SetPhysicalID(my_name, nodes_ip)
2427

    
2428
  bdevs = []
2429

    
2430
  for cf in disks:
2431
    rd = _RecursiveFindBD(cf)
2432
    if rd is None:
2433
      _Fail("Can't find device %s", cf)
2434
    bdevs.append(rd)
2435
  return bdevs
2436

    
2437

    
2438
def DrbdDisconnectNet(nodes_ip, disks):
2439
  """Disconnects the network on a list of drbd devices.
2440

2441
  """
2442
  bdevs = _FindDisks(nodes_ip, disks)
2443

    
2444
  # disconnect disks
2445
  for rd in bdevs:
2446
    try:
2447
      rd.DisconnectNet()
2448
    except errors.BlockDeviceError, err:
2449
      _Fail("Can't change network configuration to standalone mode: %s",
2450
            err, exc=True)
2451

    
2452

    
2453
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
2454
  """Attaches the network on a list of drbd devices.
2455

2456
  """
2457
  bdevs = _FindDisks(nodes_ip, disks)
2458

    
2459
  if multimaster:
2460
    for idx, rd in enumerate(bdevs):
2461
      try:
2462
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
2463
      except EnvironmentError, err:
2464
        _Fail("Can't create symlink: %s", err)
2465
  # reconnect disks, switch to new master configuration and if
2466
  # needed primary mode
2467
  for rd in bdevs:
2468
    try:
2469
      rd.AttachNet(multimaster)
2470
    except errors.BlockDeviceError, err:
2471
      _Fail("Can't change network configuration: %s", err)
2472
  # wait until the disks are connected; we need to retry the re-attach
2473
  # if the device becomes standalone, as this might happen if the one
2474
  # node disconnects and reconnects in a different mode before the
2475
  # other node reconnects; in this case, one or both of the nodes will
2476
  # decide it has wrong configuration and switch to standalone
2477
  RECONNECT_TIMEOUT = 2 * 60
2478
  sleep_time = 0.100 # start with 100 miliseconds
2479
  timeout_limit = time.time() + RECONNECT_TIMEOUT
2480
  while time.time() < timeout_limit:
2481
    all_connected = True
2482
    for rd in bdevs:
2483
      stats = rd.GetProcStatus()
2484
      if not (stats.is_connected or stats.is_in_resync):
2485
        all_connected = False
2486
      if stats.is_standalone:
2487
        # peer had different config info and this node became
2488
        # standalone, even though this should not happen with the
2489
        # new staged way of changing disk configs
2490
        try:
2491
          rd.AttachNet(multimaster)
2492
        except errors.BlockDeviceError, err:
2493
          _Fail("Can't change network configuration: %s", err)
2494
    if all_connected:
2495
      break
2496
    time.sleep(sleep_time)
2497
    sleep_time = min(5, sleep_time * 1.5)
2498
  if not all_connected:
2499
    _Fail("Timeout in disk reconnecting")
2500
  if multimaster:
2501
    # change to primary mode
2502
    for rd in bdevs:
2503
      try:
2504
        rd.Open()
2505
      except errors.BlockDeviceError, err:
2506
        _Fail("Can't change to primary mode: %s", err)
2507

    
2508

    
2509
def DrbdWaitSync(nodes_ip, disks):
2510
  """Wait until DRBDs have synchronized.
2511

2512
  """
2513
  bdevs = _FindDisks(nodes_ip, disks)
2514

    
2515
  min_resync = 100
2516
  alldone = True
2517
  for rd in bdevs:
2518
    stats = rd.GetProcStatus()
2519
    if not (stats.is_connected or stats.is_in_resync):
2520
      _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
2521
    alldone = alldone and (not stats.is_in_resync)
2522
    if stats.sync_percent is not None:
2523
      min_resync = min(min_resync, stats.sync_percent)
2524

    
2525
  return (alldone, min_resync)
2526

    
2527

    
2528
def PowercycleNode(hypervisor_type):
2529
  """Hard-powercycle the node.
2530

2531
  Because we need to return first, and schedule the powercycle in the
2532
  background, we won't be able to report failures nicely.
2533

2534
  """
2535
  hyper = hypervisor.GetHypervisor(hypervisor_type)
2536
  try:
2537
    pid = os.fork()
2538
  except OSError:
2539
    # if we can't fork, we'll pretend that we're in the child process
2540
    pid = 0
2541
  if pid > 0:
2542
    return "Reboot scheduled in 5 seconds"
2543
  time.sleep(5)
2544
  hyper.PowercycleNode()
2545

    
2546

    
2547
class HooksRunner(object):
2548
  """Hook runner.
2549

2550
  This class is instantiated on the node side (ganeti-noded) and not
2551
  on the master side.
2552

2553
  """
2554
  RE_MASK = re.compile("^[a-zA-Z0-9_-]+$")
2555

    
2556
  def __init__(self, hooks_base_dir=None):
2557
    """Constructor for hooks runner.
2558

2559
    @type hooks_base_dir: str or None
2560
    @param hooks_base_dir: if not None, this overrides the
2561
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
2562

2563
    """
2564
    if hooks_base_dir is None:
2565
      hooks_base_dir = constants.HOOKS_BASE_DIR
2566
    self._BASE_DIR = hooks_base_dir
2567

    
2568
  @staticmethod
2569
  def ExecHook(script, env):
2570
    """Exec one hook script.
2571

2572
    @type script: str
2573
    @param script: the full path to the script
2574
    @type env: dict
2575
    @param env: the environment with which to exec the script
2576
    @rtype: tuple (success, message)
2577
    @return: a tuple of success and message, where success
2578
        indicates the succes of the operation, and message
2579
        which will contain the error details in case we
2580
        failed
2581

2582
    """
2583
    # exec the process using subprocess and log the output
2584
    fdstdin = None
2585
    try:
2586
      fdstdin = open("/dev/null", "r")
2587
      child = subprocess.Popen([script], stdin=fdstdin, stdout=subprocess.PIPE,
2588
                               stderr=subprocess.STDOUT, close_fds=True,
2589
                               shell=False, cwd="/", env=env)
2590
      output = ""
2591
      try:
2592
        output = child.stdout.read(4096)
2593
        child.stdout.close()
2594
      except EnvironmentError, err:
2595
        output += "Hook script error: %s" % str(err)
2596

    
2597
      while True:
2598
        try:
2599
          result = child.wait()
2600
          break
2601
        except EnvironmentError, err:
2602
          if err.errno == errno.EINTR:
2603
            continue
2604
          raise
2605
    finally:
2606
      # try not to leak fds
2607
      for fd in (fdstdin, ):
2608
        if fd is not None:
2609
          try:
2610
            fd.close()
2611
          except EnvironmentError, err:
2612
            # just log the error
2613
            #logging.exception("Error while closing fd %s", fd)
2614
            pass
2615

    
2616
    return result == 0, utils.SafeEncode(output.strip())
2617

    
2618
  def RunHooks(self, hpath, phase, env):
2619
    """Run the scripts in the hooks directory.
2620

2621
    @type hpath: str
2622
    @param hpath: the path to the hooks directory which
2623
        holds the scripts
2624
    @type phase: str
2625
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
2626
        L{constants.HOOKS_PHASE_POST}
2627
    @type env: dict
2628
    @param env: dictionary with the environment for the hook
2629
    @rtype: list
2630
    @return: list of 3-element tuples:
2631
      - script path
2632
      - script result, either L{constants.HKR_SUCCESS} or
2633
        L{constants.HKR_FAIL}
2634
      - output of the script
2635

2636
    @raise errors.ProgrammerError: for invalid input
2637
        parameters
2638

2639
    """
2640
    if phase == constants.HOOKS_PHASE_PRE:
2641
      suffix = "pre"
2642
    elif phase == constants.HOOKS_PHASE_POST:
2643
      suffix = "post"
2644
    else:
2645
      _Fail("Unknown hooks phase '%s'", phase)
2646

    
2647
    rr = []
2648

    
2649
    subdir = "%s-%s.d" % (hpath, suffix)
2650
    dir_name = "%s/%s" % (self._BASE_DIR, subdir)
2651
    try:
2652
      dir_contents = utils.ListVisibleFiles(dir_name)
2653
    except OSError:
2654
      # FIXME: must log output in case of failures
2655
      return rr
2656

    
2657
    # we use the standard python sort order,
2658
    # so 00name is the recommended naming scheme
2659
    dir_contents.sort()
2660
    for relname in dir_contents:
2661
      fname = os.path.join(dir_name, relname)
2662
      if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and
2663
          self.RE_MASK.match(relname) is not None):
2664
        rrval = constants.HKR_SKIP
2665
        output = ""
2666
      else:
2667
        result, output = self.ExecHook(fname, env)
2668
        if not result:
2669
          rrval = constants.HKR_FAIL
2670
        else:
2671
          rrval = constants.HKR_SUCCESS
2672
      rr.append(("%s/%s" % (subdir, relname), rrval, output))
2673

    
2674
    return rr
2675

    
2676

    
2677
class IAllocatorRunner(object):
2678
  """IAllocator runner.
2679

2680
  This class is instantiated on the node side (ganeti-noded) and not on
2681
  the master side.
2682

2683
  """
2684
  def Run(self, name, idata):
2685
    """Run an iallocator script.
2686

2687
    @type name: str
2688
    @param name: the iallocator script name
2689
    @type idata: str
2690
    @param idata: the allocator input data
2691

2692
    @rtype: tuple
2693
    @return: two element tuple of:
2694
       - status
2695
       - either error message or stdout of allocator (for success)
2696

2697
    """
2698
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
2699
                                  os.path.isfile)
2700
    if alloc_script is None:
2701
      _Fail("iallocator module '%s' not found in the search path", name)
2702

    
2703
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
2704
    try:
2705
      os.write(fd, idata)
2706
      os.close(fd)
2707
      result = utils.RunCmd([alloc_script, fin_name])
2708
      if result.failed:
2709
        _Fail("iallocator module '%s' failed: %s, output '%s'",
2710
              name, result.fail_reason, result.output)
2711
    finally:
2712
      os.unlink(fin_name)
2713

    
2714
    return result.stdout
2715

    
2716

    
2717
class DevCacheManager(object):
2718
  """Simple class for managing a cache of block device information.
2719

2720
  """
2721
  _DEV_PREFIX = "/dev/"
2722
  _ROOT_DIR = constants.BDEV_CACHE_DIR
2723

    
2724
  @classmethod
2725
  def _ConvertPath(cls, dev_path):
2726
    """Converts a /dev/name path to the cache file name.
2727

2728
    This replaces slashes with underscores and strips the /dev
2729
    prefix. It then returns the full path to the cache file.
2730

2731
    @type dev_path: str
2732
    @param dev_path: the C{/dev/} path name
2733
    @rtype: str
2734
    @return: the converted path name
2735

2736
    """
2737
    if dev_path.startswith(cls._DEV_PREFIX):
2738
      dev_path = dev_path[len(cls._DEV_PREFIX):]
2739
    dev_path = dev_path.replace("/", "_")
2740
    fpath = "%s/bdev_%s" % (cls._ROOT_DIR, dev_path)
2741
    return fpath
2742

    
2743
  @classmethod
2744
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
2745
    """Updates the cache information for a given device.
2746

2747
    @type dev_path: str
2748
    @param dev_path: the pathname of the device
2749
    @type owner: str
2750
    @param owner: the owner (instance name) of the device
2751
    @type on_primary: bool
2752
    @param on_primary: whether this is the primary
2753
        node nor not
2754
    @type iv_name: str
2755
    @param iv_name: the instance-visible name of the
2756
        device, as in objects.Disk.iv_name
2757

2758
    @rtype: None
2759

2760
    """
2761
    if dev_path is None:
2762
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
2763
      return
2764
    fpath = cls._ConvertPath(dev_path)
2765
    if on_primary:
2766
      state = "primary"
2767
    else:
2768
      state = "secondary"
2769
    if iv_name is None:
2770
      iv_name = "not_visible"
2771
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
2772
    try:
2773
      utils.WriteFile(fpath, data=fdata)
2774
    except EnvironmentError, err:
2775
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
2776

    
2777
  @classmethod
2778
  def RemoveCache(cls, dev_path):
2779
    """Remove data for a dev_path.
2780

2781
    This is just a wrapper over L{utils.RemoveFile} with a converted
2782
    path name and logging.
2783

2784
    @type dev_path: str
2785
    @param dev_path: the pathname of the device
2786

2787
    @rtype: None
2788

2789
    """
2790
    if dev_path is None:
2791
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
2792
      return
2793
    fpath = cls._ConvertPath(dev_path)
2794
    try:
2795
      utils.RemoveFile(fpath)
2796
    except EnvironmentError, err:
2797
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)