Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 5a533f8a

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

    
25
import os
26
import os.path
27
import shutil
28
import time
29
import stat
30
import errno
31
import re
32
import subprocess
33
import random
34
import logging
35
import tempfile
36
import zlib
37
import base64
38

    
39
from ganeti import errors
40
from ganeti import utils
41
from ganeti import ssh
42
from ganeti import hypervisor
43
from ganeti import constants
44
from ganeti import bdev
45
from ganeti import objects
46
from ganeti import ssconf
47

    
48

    
49
class RPCFail(Exception):
50
  """Class denoting RPC failure.
51

52
  Its argument is the error message.
53

54
  """
55

    
56
def _Fail(msg, *args, **kwargs):
57
  """Log an error and the raise an RPCFail exception.
58

59
  This exception is then handled specially in the ganeti daemon and
60
  turned into a 'failed' return type. As such, this function is a
61
  useful shortcut for logging the error and returning it to the master
62
  daemon.
63

64
  @type msg: string
65
  @param msg: the text of the exception
66
  @raise RPCFail
67

68
  """
69
  if args:
70
    msg = msg % args
71
  if "exc" in kwargs and kwargs["exc"]:
72
    logging.exception(msg)
73
  else:
74
    logging.error(msg)
75
  raise RPCFail(msg)
76

    
77

    
78
def _GetConfig():
79
  """Simple wrapper to return a SimpleStore.
80

81
  @rtype: L{ssconf.SimpleStore}
82
  @return: a SimpleStore instance
83

84
  """
85
  return ssconf.SimpleStore()
86

    
87

    
88
def _GetSshRunner(cluster_name):
89
  """Simple wrapper to return an SshRunner.
90

91
  @type cluster_name: str
92
  @param cluster_name: the cluster name, which is needed
93
      by the SshRunner constructor
94
  @rtype: L{ssh.SshRunner}
95
  @return: an SshRunner instance
96

97
  """
98
  return ssh.SshRunner(cluster_name)
99

    
100

    
101
def _Decompress(data):
102
  """Unpacks data compressed by the RPC client.
103

104
  @type data: list or tuple
105
  @param data: Data sent by RPC client
106
  @rtype: str
107
  @return: Decompressed data
108

109
  """
110
  assert isinstance(data, (list, tuple))
111
  assert len(data) == 2
112
  (encoding, content) = data
113
  if encoding == constants.RPC_ENCODING_NONE:
114
    return content
115
  elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
116
    return zlib.decompress(base64.b64decode(content))
117
  else:
118
    raise AssertionError("Unknown data encoding")
119

    
120

    
121
def _CleanDirectory(path, exclude=None):
122
  """Removes all regular files in a directory.
123

124
  @type path: str
125
  @param path: the directory to clean
126
  @type exclude: list
127
  @param exclude: list of files to be excluded, defaults
128
      to the empty list
129

130
  """
131
  if not os.path.isdir(path):
132
    return
133
  if exclude is None:
134
    exclude = []
135
  else:
136
    # Normalize excluded paths
137
    exclude = [os.path.normpath(i) for i in exclude]
138

    
139
  for rel_name in utils.ListVisibleFiles(path):
140
    full_name = os.path.normpath(os.path.join(path, rel_name))
141
    if full_name in exclude:
142
      continue
143
    if os.path.isfile(full_name) and not os.path.islink(full_name):
144
      utils.RemoveFile(full_name)
145

    
146

    
147
def JobQueuePurge():
148
  """Removes job queue files and archived jobs.
149

150
  @rtype: tuple
151
  @return: True, None
152

153
  """
154
  _CleanDirectory(constants.QUEUE_DIR, exclude=[constants.JOB_QUEUE_LOCK_FILE])
155
  _CleanDirectory(constants.JOB_QUEUE_ARCHIVE_DIR)
156
  return True, None
157

    
158

    
159
def GetMasterInfo():
160
  """Returns master information.
161

162
  This is an utility function to compute master information, either
163
  for consumption here or from the node daemon.
164

165
  @rtype: tuple
166
  @return: True, (master_netdev, master_ip, master_name) in case of success
167
  @raise RPCFail: in case of errors
168

169
  """
170
  try:
171
    cfg = _GetConfig()
172
    master_netdev = cfg.GetMasterNetdev()
173
    master_ip = cfg.GetMasterIP()
174
    master_node = cfg.GetMasterNode()
175
  except errors.ConfigurationError, err:
176
    _Fail("Cluster configuration incomplete", exc=True)
177
  return True, (master_netdev, master_ip, master_node)
178

    
179

    
180
def StartMaster(start_daemons):
181
  """Activate local node as master node.
182

183
  The function will always try activate the IP address of the master
184
  (unless someone else has it). It will also start the master daemons,
185
  based on the start_daemons parameter.
186

187
  @type start_daemons: boolean
188
  @param start_daemons: whther to also start the master
189
      daemons (ganeti-masterd and ganeti-rapi)
190
  @rtype: None
191

192
  """
193
  # GetMasterInfo will raise an exception if not able to return data
194
  master_netdev, master_ip, _ = GetMasterInfo()[1]
195

    
196
  payload = []
197
  if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
198
    if utils.OwnIpAddress(master_ip):
199
      # we already have the ip:
200
      logging.debug("Master IP already configured, doing nothing")
201
    else:
202
      msg = "Someone else has the master ip, not activating"
203
      logging.error(msg)
204
      payload.append(msg)
205
  else:
206
    result = utils.RunCmd(["ip", "address", "add", "%s/32" % master_ip,
207
                           "dev", master_netdev, "label",
208
                           "%s:0" % master_netdev])
209
    if result.failed:
210
      msg = "Can't activate master IP: %s" % result.output
211
      logging.error(msg)
212
      payload.append(msg)
213

    
214
    result = utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev,
215
                           "-s", master_ip, master_ip])
216
    # we'll ignore the exit code of arping
217

    
218
  # and now start the master and rapi daemons
219
  if start_daemons:
220
    for daemon in 'ganeti-masterd', 'ganeti-rapi':
221
      result = utils.RunCmd([daemon])
222
      if result.failed:
223
        msg = "Can't start daemon %s: %s" % (daemon, result.output)
224
        logging.error(msg)
225
        payload.append(msg)
226

    
227
  return not payload, "; ".join(payload)
228

    
229

    
230
def StopMaster(stop_daemons):
231
  """Deactivate this node as master.
232

233
  The function will always try to deactivate the IP address of the
234
  master. It will also stop the master daemons depending on the
235
  stop_daemons parameter.
236

237
  @type stop_daemons: boolean
238
  @param stop_daemons: whether to also stop the master daemons
239
      (ganeti-masterd and ganeti-rapi)
240
  @rtype: None
241

242
  """
243
  # TODO: log and report back to the caller the error failures; we
244
  # need to decide in which case we fail the RPC for this
245

    
246
  # GetMasterInfo will raise an exception if not able to return data
247
  master_netdev, master_ip, _ = GetMasterInfo()[1]
248

    
249
  result = utils.RunCmd(["ip", "address", "del", "%s/32" % master_ip,
250
                         "dev", master_netdev])
251
  if result.failed:
252
    logging.error("Can't remove the master IP, error: %s", result.output)
253
    # but otherwise ignore the failure
254

    
255
  if stop_daemons:
256
    # stop/kill the rapi and the master daemon
257
    for daemon in constants.RAPI_PID, constants.MASTERD_PID:
258
      utils.KillProcess(utils.ReadPidFile(utils.DaemonPidFileName(daemon)))
259

    
260
  return True, None
261

    
262

    
263
def AddNode(dsa, dsapub, rsa, rsapub, sshkey, sshpub):
264
  """Joins this node to the cluster.
265

266
  This does the following:
267
      - updates the hostkeys of the machine (rsa and dsa)
268
      - adds the ssh private key to the user
269
      - adds the ssh public key to the users' authorized_keys file
270

271
  @type dsa: str
272
  @param dsa: the DSA private key to write
273
  @type dsapub: str
274
  @param dsapub: the DSA public key to write
275
  @type rsa: str
276
  @param rsa: the RSA private key to write
277
  @type rsapub: str
278
  @param rsapub: the RSA public key to write
279
  @type sshkey: str
280
  @param sshkey: the SSH private key to write
281
  @type sshpub: str
282
  @param sshpub: the SSH public key to write
283
  @rtype: boolean
284
  @return: the success of the operation
285

286
  """
287
  sshd_keys =  [(constants.SSH_HOST_RSA_PRIV, rsa, 0600),
288
                (constants.SSH_HOST_RSA_PUB, rsapub, 0644),
289
                (constants.SSH_HOST_DSA_PRIV, dsa, 0600),
290
                (constants.SSH_HOST_DSA_PUB, dsapub, 0644)]
291
  for name, content, mode in sshd_keys:
292
    utils.WriteFile(name, data=content, mode=mode)
293

    
294
  try:
295
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS,
296
                                                    mkdir=True)
297
  except errors.OpExecError, err:
298
    _Fail("Error while processing user ssh files: %s", err, exc=True)
299

    
300
  for name, content in [(priv_key, sshkey), (pub_key, sshpub)]:
301
    utils.WriteFile(name, data=content, mode=0600)
302

    
303
  utils.AddAuthorizedKey(auth_keys, sshpub)
304

    
305
  utils.RunCmd([constants.SSH_INITD_SCRIPT, "restart"])
306

    
307
  return (True, "Node added successfully")
308

    
309

    
310
def LeaveCluster():
311
  """Cleans up and remove the current node.
312

313
  This function cleans up and prepares the current node to be removed
314
  from the cluster.
315

316
  If processing is successful, then it raises an
317
  L{errors.QuitGanetiException} which is used as a special case to
318
  shutdown the node daemon.
319

320
  """
321
  _CleanDirectory(constants.DATA_DIR)
322
  JobQueuePurge()
323

    
324
  try:
325
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
326

    
327
    f = open(pub_key, 'r')
328
    try:
329
      utils.RemoveAuthorizedKey(auth_keys, f.read(8192))
330
    finally:
331
      f.close()
332

    
333
    utils.RemoveFile(priv_key)
334
    utils.RemoveFile(pub_key)
335
  except errors.OpExecError:
336
    logging.exception("Error while processing ssh files")
337

    
338
  # Raise a custom exception (handled in ganeti-noded)
339
  raise errors.QuitGanetiException(True, 'Shutdown scheduled')
340

    
341

    
342
def GetNodeInfo(vgname, hypervisor_type):
343
  """Gives back a hash with different informations about the node.
344

345
  @type vgname: C{string}
346
  @param vgname: the name of the volume group to ask for disk space information
347
  @type hypervisor_type: C{str}
348
  @param hypervisor_type: the name of the hypervisor to ask for
349
      memory information
350
  @rtype: C{dict}
351
  @return: dictionary with the following keys:
352
      - vg_size is the size of the configured volume group in MiB
353
      - vg_free is the free size of the volume group in MiB
354
      - memory_dom0 is the memory allocated for domain0 in MiB
355
      - memory_free is the currently available (free) ram in MiB
356
      - memory_total is the total number of ram in MiB
357

358
  """
359
  outputarray = {}
360
  vginfo = _GetVGInfo(vgname)
361
  outputarray['vg_size'] = vginfo['vg_size']
362
  outputarray['vg_free'] = vginfo['vg_free']
363

    
364
  hyper = hypervisor.GetHypervisor(hypervisor_type)
365
  hyp_info = hyper.GetNodeInfo()
366
  if hyp_info is not None:
367
    outputarray.update(hyp_info)
368

    
369
  f = open("/proc/sys/kernel/random/boot_id", 'r')
370
  try:
371
    outputarray["bootid"] = f.read(128).rstrip("\n")
372
  finally:
373
    f.close()
374

    
375
  return True, outputarray
376

    
377

    
378
def VerifyNode(what, cluster_name):
379
  """Verify the status of the local node.
380

381
  Based on the input L{what} parameter, various checks are done on the
382
  local node.
383

384
  If the I{filelist} key is present, this list of
385
  files is checksummed and the file/checksum pairs are returned.
386

387
  If the I{nodelist} key is present, we check that we have
388
  connectivity via ssh with the target nodes (and check the hostname
389
  report).
390

391
  If the I{node-net-test} key is present, we check that we have
392
  connectivity to the given nodes via both primary IP and, if
393
  applicable, secondary IPs.
394

395
  @type what: C{dict}
396
  @param what: a dictionary of things to check:
397
      - filelist: list of files for which to compute checksums
398
      - nodelist: list of nodes we should check ssh communication with
399
      - node-net-test: list of nodes we should check node daemon port
400
        connectivity with
401
      - hypervisor: list with hypervisors to run the verify for
402
  @rtype: dict
403
  @return: a dictionary with the same keys as the input dict, and
404
      values representing the result of the checks
405

406
  """
407
  result = {}
408

    
409
  if constants.NV_HYPERVISOR in what:
410
    result[constants.NV_HYPERVISOR] = tmp = {}
411
    for hv_name in what[constants.NV_HYPERVISOR]:
412
      tmp[hv_name] = hypervisor.GetHypervisor(hv_name).Verify()
413

    
414
  if constants.NV_FILELIST in what:
415
    result[constants.NV_FILELIST] = utils.FingerprintFiles(
416
      what[constants.NV_FILELIST])
417

    
418
  if constants.NV_NODELIST in what:
419
    result[constants.NV_NODELIST] = tmp = {}
420
    random.shuffle(what[constants.NV_NODELIST])
421
    for node in what[constants.NV_NODELIST]:
422
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
423
      if not success:
424
        tmp[node] = message
425

    
426
  if constants.NV_NODENETTEST in what:
427
    result[constants.NV_NODENETTEST] = tmp = {}
428
    my_name = utils.HostInfo().name
429
    my_pip = my_sip = None
430
    for name, pip, sip in what[constants.NV_NODENETTEST]:
431
      if name == my_name:
432
        my_pip = pip
433
        my_sip = sip
434
        break
435
    if not my_pip:
436
      tmp[my_name] = ("Can't find my own primary/secondary IP"
437
                      " in the node list")
438
    else:
439
      port = utils.GetNodeDaemonPort()
440
      for name, pip, sip in what[constants.NV_NODENETTEST]:
441
        fail = []
442
        if not utils.TcpPing(pip, port, source=my_pip):
443
          fail.append("primary")
444
        if sip != pip:
445
          if not utils.TcpPing(sip, port, source=my_sip):
446
            fail.append("secondary")
447
        if fail:
448
          tmp[name] = ("failure using the %s interface(s)" %
449
                       " and ".join(fail))
450

    
451
  if constants.NV_LVLIST in what:
452
    result[constants.NV_LVLIST] = GetVolumeList(what[constants.NV_LVLIST])
453

    
454
  if constants.NV_INSTANCELIST in what:
455
    result[constants.NV_INSTANCELIST] = GetInstanceList(
456
      what[constants.NV_INSTANCELIST])
457

    
458
  if constants.NV_VGLIST in what:
459
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
460

    
461
  if constants.NV_VERSION in what:
462
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
463
                                    constants.RELEASE_VERSION)
464

    
465
  if constants.NV_HVINFO in what:
466
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
467
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
468

    
469
  if constants.NV_DRBDLIST in what:
470
    try:
471
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
472
    except errors.BlockDeviceError, err:
473
      logging.warning("Can't get used minors list", exc_info=True)
474
      used_minors = str(err)
475
    result[constants.NV_DRBDLIST] = used_minors
476

    
477
  return True, result
478

    
479

    
480
def GetVolumeList(vg_name):
481
  """Compute list of logical volumes and their size.
482

483
  @type vg_name: str
484
  @param vg_name: the volume group whose LVs we should list
485
  @rtype: dict
486
  @return:
487
      dictionary of all partions (key) with value being a tuple of
488
      their size (in MiB), inactive and online status::
489

490
        {'test1': ('20.06', True, True)}
491

492
      in case of errors, a string is returned with the error
493
      details.
494

495
  """
496
  lvs = {}
497
  sep = '|'
498
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
499
                         "--separator=%s" % sep,
500
                         "-olv_name,lv_size,lv_attr", vg_name])
501
  if result.failed:
502
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
503

    
504
  valid_line_re = re.compile("^ *([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
505
  for line in result.stdout.splitlines():
506
    line = line.strip()
507
    match = valid_line_re.match(line)
508
    if not match:
509
      logging.error("Invalid line returned from lvs output: '%s'", line)
510
      continue
511
    name, size, attr = match.groups()
512
    inactive = attr[4] == '-'
513
    online = attr[5] == 'o'
514
    lvs[name] = (size, inactive, online)
515

    
516
  return lvs
517

    
518

    
519
def ListVolumeGroups():
520
  """List the volume groups and their size.
521

522
  @rtype: dict
523
  @return: dictionary with keys volume name and values the
524
      size of the volume
525

526
  """
527
  return True, utils.ListVolumeGroups()
528

    
529

    
530
def NodeVolumes():
531
  """List all volumes on this node.
532

533
  @rtype: list
534
  @return:
535
    A list of dictionaries, each having four keys:
536
      - name: the logical volume name,
537
      - size: the size of the logical volume
538
      - dev: the physical device on which the LV lives
539
      - vg: the volume group to which it belongs
540

541
    In case of errors, we return an empty list and log the
542
    error.
543

544
    Note that since a logical volume can live on multiple physical
545
    volumes, the resulting list might include a logical volume
546
    multiple times.
547

548
  """
549
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
550
                         "--separator=|",
551
                         "--options=lv_name,lv_size,devices,vg_name"])
552
  if result.failed:
553
    _Fail("Failed to list logical volumes, lvs output: %s",
554
          result.output)
555

    
556
  def parse_dev(dev):
557
    if '(' in dev:
558
      return dev.split('(')[0]
559
    else:
560
      return dev
561

    
562
  def map_line(line):
563
    return {
564
      'name': line[0].strip(),
565
      'size': line[1].strip(),
566
      'dev': parse_dev(line[2].strip()),
567
      'vg': line[3].strip(),
568
    }
569

    
570
  return True, [map_line(line.split('|'))
571
                for line in result.stdout.splitlines()
572
                if line.count('|') >= 3]
573

    
574

    
575
def BridgesExist(bridges_list):
576
  """Check if a list of bridges exist on the current node.
577

578
  @rtype: boolean
579
  @return: C{True} if all of them exist, C{False} otherwise
580

581
  """
582
  missing = []
583
  for bridge in bridges_list:
584
    if not utils.BridgeExists(bridge):
585
      missing.append(bridge)
586

    
587
  if missing:
588
    return False, "Missing bridges %s" % (", ".join(missing),)
589

    
590
  return True, None
591

    
592

    
593
def GetInstanceList(hypervisor_list):
594
  """Provides a list of instances.
595

596
  @type hypervisor_list: list
597
  @param hypervisor_list: the list of hypervisors to query information
598

599
  @rtype: list
600
  @return: a list of all running instances on the current node
601
    - instance1.example.com
602
    - instance2.example.com
603

604
  """
605
  results = []
606
  for hname in hypervisor_list:
607
    try:
608
      names = hypervisor.GetHypervisor(hname).ListInstances()
609
      results.extend(names)
610
    except errors.HypervisorError, err:
611
      _Fail("Error enumerating instances (hypervisor %s): %s",
612
            hname, err, exc=True)
613

    
614
  return results
615

    
616

    
617
def GetInstanceInfo(instance, hname):
618
  """Gives back the informations about an instance as a dictionary.
619

620
  @type instance: string
621
  @param instance: the instance name
622
  @type hname: string
623
  @param hname: the hypervisor type of the instance
624

625
  @rtype: dict
626
  @return: dictionary with the following keys:
627
      - memory: memory size of instance (int)
628
      - state: xen state of instance (string)
629
      - time: cpu time of instance (float)
630

631
  """
632
  output = {}
633

    
634
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
635
  if iinfo is not None:
636
    output['memory'] = iinfo[2]
637
    output['state'] = iinfo[4]
638
    output['time'] = iinfo[5]
639

    
640
  return True, output
641

    
642

    
643
def GetInstanceMigratable(instance):
644
  """Gives whether an instance can be migrated.
645

646
  @type instance: L{objects.Instance}
647
  @param instance: object representing the instance to be checked.
648

649
  @rtype: tuple
650
  @return: tuple of (result, description) where:
651
      - result: whether the instance can be migrated or not
652
      - description: a description of the issue, if relevant
653

654
  """
655
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
656
  if instance.name not in hyper.ListInstances():
657
    return (False, 'not running')
658

    
659
  for idx in range(len(instance.disks)):
660
    link_name = _GetBlockDevSymlinkPath(instance.name, idx)
661
    if not os.path.islink(link_name):
662
      return (False, 'not restarted since ganeti 1.2.5')
663

    
664
  return (True, '')
665

    
666

    
667
def GetAllInstancesInfo(hypervisor_list):
668
  """Gather data about all instances.
669

670
  This is the equivalent of L{GetInstanceInfo}, except that it
671
  computes data for all instances at once, thus being faster if one
672
  needs data about more than one instance.
673

674
  @type hypervisor_list: list
675
  @param hypervisor_list: list of hypervisors to query for instance data
676

677
  @rtype: dict
678
  @return: dictionary of instance: data, with data having the following keys:
679
      - memory: memory size of instance (int)
680
      - state: xen state of instance (string)
681
      - time: cpu time of instance (float)
682
      - vcpus: the number of vcpus
683

684
  """
685
  output = {}
686

    
687
  for hname in hypervisor_list:
688
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
689
    if iinfo:
690
      for name, inst_id, memory, vcpus, state, times in iinfo:
691
        value = {
692
          'memory': memory,
693
          'vcpus': vcpus,
694
          'state': state,
695
          'time': times,
696
          }
697
        if name in output:
698
          # we only check static parameters, like memory and vcpus,
699
          # and not state and time which can change between the
700
          # invocations of the different hypervisors
701
          for key in 'memory', 'vcpus':
702
            if value[key] != output[name][key]:
703
              _Fail("Instance %s is running twice"
704
                    " with different parameters", name)
705
        output[name] = value
706

    
707
  return True, output
708

    
709

    
710
def InstanceOsAdd(instance, reinstall):
711
  """Add an OS to an instance.
712

713
  @type instance: L{objects.Instance}
714
  @param instance: Instance whose OS is to be installed
715
  @type reinstall: boolean
716
  @param reinstall: whether this is an instance reinstall
717
  @rtype: boolean
718
  @return: the success of the operation
719

720
  """
721
  inst_os = OSFromDisk(instance.os)
722

    
723

    
724
  create_env = OSEnvironment(instance)
725
  if reinstall:
726
    create_env['INSTANCE_REINSTALL'] = "1"
727

    
728
  logfile = "%s/add-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
729
                                     instance.name, int(time.time()))
730

    
731
  result = utils.RunCmd([inst_os.create_script], env=create_env,
732
                        cwd=inst_os.path, output=logfile,)
733
  if result.failed:
734
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
735
                  " output: %s", result.cmd, result.fail_reason, logfile,
736
                  result.output)
737
    lines = [utils.SafeEncode(val)
738
             for val in utils.TailFile(logfile, lines=20)]
739
    return (False, "OS create script failed (%s), last lines in the"
740
            " log file:\n%s" % (result.fail_reason, "\n".join(lines)))
741

    
742
  return (True, "Successfully installed")
743

    
744

    
745
def RunRenameInstance(instance, old_name):
746
  """Run the OS rename script for an instance.
747

748
  @type instance: L{objects.Instance}
749
  @param instance: Instance whose OS is to be installed
750
  @type old_name: string
751
  @param old_name: previous instance name
752
  @rtype: boolean
753
  @return: the success of the operation
754

755
  """
756
  inst_os = OSFromDisk(instance.os)
757

    
758
  rename_env = OSEnvironment(instance)
759
  rename_env['OLD_INSTANCE_NAME'] = old_name
760

    
761
  logfile = "%s/rename-%s-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
762
                                           old_name,
763
                                           instance.name, int(time.time()))
764

    
765
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
766
                        cwd=inst_os.path, output=logfile)
767

    
768
  if result.failed:
769
    logging.error("os create command '%s' returned error: %s output: %s",
770
                  result.cmd, result.fail_reason, result.output)
771
    lines = [utils.SafeEncode(val)
772
             for val in utils.TailFile(logfile, lines=20)]
773
    return (False, "OS rename script failed (%s), last lines in the"
774
            " log file:\n%s" % (result.fail_reason, "\n".join(lines)))
775

    
776
  return (True, "Rename successful")
777

    
778

    
779
def _GetVGInfo(vg_name):
780
  """Get informations about the volume group.
781

782
  @type vg_name: str
783
  @param vg_name: the volume group which we query
784
  @rtype: dict
785
  @return:
786
    A dictionary with the following keys:
787
      - C{vg_size} is the total size of the volume group in MiB
788
      - C{vg_free} is the free size of the volume group in MiB
789
      - C{pv_count} are the number of physical disks in that VG
790

791
    If an error occurs during gathering of data, we return the same dict
792
    with keys all set to None.
793

794
  """
795
  retdic = dict.fromkeys(["vg_size", "vg_free", "pv_count"])
796

    
797
  retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings",
798
                         "--nosuffix", "--units=m", "--separator=:", vg_name])
799

    
800
  if retval.failed:
801
    logging.error("volume group %s not present", vg_name)
802
    return retdic
803
  valarr = retval.stdout.strip().rstrip(':').split(':')
804
  if len(valarr) == 3:
805
    try:
806
      retdic = {
807
        "vg_size": int(round(float(valarr[0]), 0)),
808
        "vg_free": int(round(float(valarr[1]), 0)),
809
        "pv_count": int(valarr[2]),
810
        }
811
    except ValueError, err:
812
      logging.exception("Fail to parse vgs output")
813
  else:
814
    logging.error("vgs output has the wrong number of fields (expected"
815
                  " three): %s", str(valarr))
816
  return retdic
817

    
818

    
819
def _GetBlockDevSymlinkPath(instance_name, idx):
820
  return os.path.join(constants.DISK_LINKS_DIR,
821
                      "%s:%d" % (instance_name, idx))
822

    
823

    
824
def _SymlinkBlockDev(instance_name, device_path, idx):
825
  """Set up symlinks to a instance's block device.
826

827
  This is an auxiliary function run when an instance is start (on the primary
828
  node) or when an instance is migrated (on the target node).
829

830

831
  @param instance_name: the name of the target instance
832
  @param device_path: path of the physical block device, on the node
833
  @param idx: the disk index
834
  @return: absolute path to the disk's symlink
835

836
  """
837
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
838
  try:
839
    os.symlink(device_path, link_name)
840
  except OSError, err:
841
    if err.errno == errno.EEXIST:
842
      if (not os.path.islink(link_name) or
843
          os.readlink(link_name) != device_path):
844
        os.remove(link_name)
845
        os.symlink(device_path, link_name)
846
    else:
847
      raise
848

    
849
  return link_name
850

    
851

    
852
def _RemoveBlockDevLinks(instance_name, disks):
853
  """Remove the block device symlinks belonging to the given instance.
854

855
  """
856
  for idx, disk in enumerate(disks):
857
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
858
    if os.path.islink(link_name):
859
      try:
860
        os.remove(link_name)
861
      except OSError:
862
        logging.exception("Can't remove symlink '%s'", link_name)
863

    
864

    
865
def _GatherAndLinkBlockDevs(instance):
866
  """Set up an instance's block device(s).
867

868
  This is run on the primary node at instance startup. The block
869
  devices must be already assembled.
870

871
  @type instance: L{objects.Instance}
872
  @param instance: the instance whose disks we shoul assemble
873
  @rtype: list
874
  @return: list of (disk_object, device_path)
875

876
  """
877
  block_devices = []
878
  for idx, disk in enumerate(instance.disks):
879
    device = _RecursiveFindBD(disk)
880
    if device is None:
881
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
882
                                    str(disk))
883
    device.Open()
884
    try:
885
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
886
    except OSError, e:
887
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
888
                                    e.strerror)
889

    
890
    block_devices.append((disk, link_name))
891

    
892
  return block_devices
893

    
894

    
895
def StartInstance(instance):
896
  """Start an instance.
897

898
  @type instance: L{objects.Instance}
899
  @param instance: the instance object
900
  @rtype: boolean
901
  @return: whether the startup was successful or not
902

903
  """
904
  running_instances = GetInstanceList([instance.hypervisor])
905

    
906
  if instance.name in running_instances:
907
    return (True, "Already running")
908

    
909
  try:
910
    block_devices = _GatherAndLinkBlockDevs(instance)
911
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
912
    hyper.StartInstance(instance, block_devices)
913
  except errors.BlockDeviceError, err:
914
    _Fail("Block device error: %s", err, exc=True)
915
  except errors.HypervisorError, err:
916
    _RemoveBlockDevLinks(instance.name, instance.disks)
917
    _Fail("Hypervisor error: %s", err, exc=True)
918

    
919
  return (True, "Instance started successfully")
920

    
921

    
922
def InstanceShutdown(instance):
923
  """Shut an instance down.
924

925
  @note: this functions uses polling with a hardcoded timeout.
926

927
  @type instance: L{objects.Instance}
928
  @param instance: the instance object
929
  @rtype: boolean
930
  @return: whether the startup was successful or not
931

932
  """
933
  hv_name = instance.hypervisor
934
  running_instances = GetInstanceList([hv_name])
935

    
936
  if instance.name not in running_instances:
937
    return (True, "Instance already stopped")
938

    
939
  hyper = hypervisor.GetHypervisor(hv_name)
940
  try:
941
    hyper.StopInstance(instance)
942
  except errors.HypervisorError, err:
943
    _Fail("Failed to stop instance %s: %s", instance.name, err)
944

    
945
  # test every 10secs for 2min
946

    
947
  time.sleep(1)
948
  for dummy in range(11):
949
    if instance.name not in GetInstanceList([hv_name]):
950
      break
951
    time.sleep(10)
952
  else:
953
    # the shutdown did not succeed
954
    logging.error("Shutdown of '%s' unsuccessful, using destroy",
955
                  instance.name)
956

    
957
    try:
958
      hyper.StopInstance(instance, force=True)
959
    except errors.HypervisorError, err:
960
      _Fail("Failed to force stop instance %s: %s", instance.name, err)
961

    
962
    time.sleep(1)
963
    if instance.name in GetInstanceList([hv_name]):
964
      _Fail("Could not shutdown instance %s even by destroy", instance.name)
965

    
966
  _RemoveBlockDevLinks(instance.name, instance.disks)
967

    
968
  return (True, "Instance has been shutdown successfully")
969

    
970

    
971
def InstanceReboot(instance, reboot_type):
972
  """Reboot an instance.
973

974
  @type instance: L{objects.Instance}
975
  @param instance: the instance object to reboot
976
  @type reboot_type: str
977
  @param reboot_type: the type of reboot, one the following
978
    constants:
979
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
980
        instance OS, do not recreate the VM
981
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
982
        restart the VM (at the hypervisor level)
983
      - the other reboot type (L{constants.INSTANCE_REBOOT_HARD})
984
        is not accepted here, since that mode is handled
985
        differently
986
  @rtype: boolean
987
  @return: the success of the operation
988

989
  """
990
  running_instances = GetInstanceList([instance.hypervisor])
991

    
992
  if instance.name not in running_instances:
993
    _Fail("Cannot reboot instance %s that is not running", instance.name)
994

    
995
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
996
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
997
    try:
998
      hyper.RebootInstance(instance)
999
    except errors.HypervisorError, err:
1000
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1001
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1002
    try:
1003
      stop_result = InstanceShutdown(instance)
1004
      if not stop_result[0]:
1005
        return stop_result
1006
      return StartInstance(instance)
1007
    except errors.HypervisorError, err:
1008
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1009
  else:
1010
    _Fail("Invalid reboot_type received: %s", reboot_type)
1011

    
1012
  return (True, "Reboot successful")
1013

    
1014

    
1015
def MigrationInfo(instance):
1016
  """Gather information about an instance to be migrated.
1017

1018
  @type instance: L{objects.Instance}
1019
  @param instance: the instance definition
1020

1021
  """
1022
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1023
  try:
1024
    info = hyper.MigrationInfo(instance)
1025
  except errors.HypervisorError, err:
1026
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1027
  return (True, info)
1028

    
1029

    
1030
def AcceptInstance(instance, info, target):
1031
  """Prepare the node to accept an instance.
1032

1033
  @type instance: L{objects.Instance}
1034
  @param instance: the instance definition
1035
  @type info: string/data (opaque)
1036
  @param info: migration information, from the source node
1037
  @type target: string
1038
  @param target: target host (usually ip), on this node
1039

1040
  """
1041
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1042
  try:
1043
    hyper.AcceptInstance(instance, info, target)
1044
  except errors.HypervisorError, err:
1045
    _Fail("Failed to accept instance: %s", err, exc=True)
1046
  return (True, "Accept successfull")
1047

    
1048

    
1049
def FinalizeMigration(instance, info, success):
1050
  """Finalize any preparation to accept an instance.
1051

1052
  @type instance: L{objects.Instance}
1053
  @param instance: the instance definition
1054
  @type info: string/data (opaque)
1055
  @param info: migration information, from the source node
1056
  @type success: boolean
1057
  @param success: whether the migration was a success or a failure
1058

1059
  """
1060
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1061
  try:
1062
    hyper.FinalizeMigration(instance, info, success)
1063
  except errors.HypervisorError, err:
1064
    _Fail("Failed to finalize migration: %s", err, exc=True)
1065
  return (True, "Migration Finalized")
1066

    
1067

    
1068
def MigrateInstance(instance, target, live):
1069
  """Migrates an instance to another node.
1070

1071
  @type instance: L{objects.Instance}
1072
  @param instance: the instance definition
1073
  @type target: string
1074
  @param target: the target node name
1075
  @type live: boolean
1076
  @param live: whether the migration should be done live or not (the
1077
      interpretation of this parameter is left to the hypervisor)
1078
  @rtype: tuple
1079
  @return: a tuple of (success, msg) where:
1080
      - succes is a boolean denoting the success/failure of the operation
1081
      - msg is a string with details in case of failure
1082

1083
  """
1084
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1085

    
1086
  try:
1087
    hyper.MigrateInstance(instance.name, target, live)
1088
  except errors.HypervisorError, err:
1089
    _Fail("Failed to migrate instance: %s", err, exc=True)
1090
  return (True, "Migration successfull")
1091

    
1092

    
1093
def BlockdevCreate(disk, size, owner, on_primary, info):
1094
  """Creates a block device for an instance.
1095

1096
  @type disk: L{objects.Disk}
1097
  @param disk: the object describing the disk we should create
1098
  @type size: int
1099
  @param size: the size of the physical underlying device, in MiB
1100
  @type owner: str
1101
  @param owner: the name of the instance for which disk is created,
1102
      used for device cache data
1103
  @type on_primary: boolean
1104
  @param on_primary:  indicates if it is the primary node or not
1105
  @type info: string
1106
  @param info: string that will be sent to the physical device
1107
      creation, used for example to set (LVM) tags on LVs
1108

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

1113
  """
1114
  clist = []
1115
  if disk.children:
1116
    for child in disk.children:
1117
      try:
1118
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1119
      except errors.BlockDeviceError, err:
1120
        _Fail("Can't assemble device %s: %s", child, err)
1121
      if on_primary or disk.AssembleOnSecondary():
1122
        # we need the children open in case the device itself has to
1123
        # be assembled
1124
        try:
1125
          crdev.Open()
1126
        except errors.BlockDeviceError, err:
1127
          _Fail("Can't make child '%s' read-write: %s", child, err)
1128
      clist.append(crdev)
1129

    
1130
  try:
1131
    device = bdev.Create(disk.dev_type, disk.physical_id, clist, size)
1132
  except errors.BlockDeviceError, err:
1133
    _Fail("Can't create block device: %s", err)
1134

    
1135
  if on_primary or disk.AssembleOnSecondary():
1136
    try:
1137
      device.Assemble()
1138
    except errors.BlockDeviceError, err:
1139
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1140
    device.SetSyncSpeed(constants.SYNC_SPEED)
1141
    if on_primary or disk.OpenOnSecondary():
1142
      try:
1143
        device.Open(force=True)
1144
      except errors.BlockDeviceError, err:
1145
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1146
    DevCacheManager.UpdateCache(device.dev_path, owner,
1147
                                on_primary, disk.iv_name)
1148

    
1149
  device.SetInfo(info)
1150

    
1151
  physical_id = device.unique_id
1152
  return True, physical_id
1153

    
1154

    
1155
def BlockdevRemove(disk):
1156
  """Remove a block device.
1157

1158
  @note: This is intended to be called recursively.
1159

1160
  @type disk: L{objects.Disk}
1161
  @param disk: the disk object we should remove
1162
  @rtype: boolean
1163
  @return: the success of the operation
1164

1165
  """
1166
  msgs = []
1167
  result = True
1168
  try:
1169
    rdev = _RecursiveFindBD(disk)
1170
  except errors.BlockDeviceError, err:
1171
    # probably can't attach
1172
    logging.info("Can't attach to device %s in remove", disk)
1173
    rdev = None
1174
  if rdev is not None:
1175
    r_path = rdev.dev_path
1176
    try:
1177
      rdev.Remove()
1178
    except errors.BlockDeviceError, err:
1179
      msgs.append(str(err))
1180
      result = False
1181
    if result:
1182
      DevCacheManager.RemoveCache(r_path)
1183

    
1184
  if disk.children:
1185
    for child in disk.children:
1186
      c_status, c_msg = BlockdevRemove(child)
1187
      result = result and c_status
1188
      if c_msg: # not an empty message
1189
        msgs.append(c_msg)
1190

    
1191
  return (result, "; ".join(msgs))
1192

    
1193

    
1194
def _RecursiveAssembleBD(disk, owner, as_primary):
1195
  """Activate a block device for an instance.
1196

1197
  This is run on the primary and secondary nodes for an instance.
1198

1199
  @note: this function is called recursively.
1200

1201
  @type disk: L{objects.Disk}
1202
  @param disk: the disk we try to assemble
1203
  @type owner: str
1204
  @param owner: the name of the instance which owns the disk
1205
  @type as_primary: boolean
1206
  @param as_primary: if we should make the block device
1207
      read/write
1208

1209
  @return: the assembled device or None (in case no device
1210
      was assembled)
1211
  @raise errors.BlockDeviceError: in case there is an error
1212
      during the activation of the children or the device
1213
      itself
1214

1215
  """
1216
  children = []
1217
  if disk.children:
1218
    mcn = disk.ChildrenNeeded()
1219
    if mcn == -1:
1220
      mcn = 0 # max number of Nones allowed
1221
    else:
1222
      mcn = len(disk.children) - mcn # max number of Nones
1223
    for chld_disk in disk.children:
1224
      try:
1225
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1226
      except errors.BlockDeviceError, err:
1227
        if children.count(None) >= mcn:
1228
          raise
1229
        cdev = None
1230
        logging.error("Error in child activation (but continuing): %s",
1231
                      str(err))
1232
      children.append(cdev)
1233

    
1234
  if as_primary or disk.AssembleOnSecondary():
1235
    r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children)
1236
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1237
    result = r_dev
1238
    if as_primary or disk.OpenOnSecondary():
1239
      r_dev.Open()
1240
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1241
                                as_primary, disk.iv_name)
1242

    
1243
  else:
1244
    result = True
1245
  return result
1246

    
1247

    
1248
def BlockdevAssemble(disk, owner, as_primary):
1249
  """Activate a block device for an instance.
1250

1251
  This is a wrapper over _RecursiveAssembleBD.
1252

1253
  @rtype: str or boolean
1254
  @return: a C{/dev/...} path for primary nodes, and
1255
      C{True} for secondary nodes
1256

1257
  """
1258
  status = True
1259
  result = "no error information"
1260
  try:
1261
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1262
    if isinstance(result, bdev.BlockDev):
1263
      result = result.dev_path
1264
  except errors.BlockDeviceError, err:
1265
    result = "Error while assembling disk: %s" % str(err)
1266
    status = False
1267
  return (status, result)
1268

    
1269

    
1270
def BlockdevShutdown(disk):
1271
  """Shut down a block device.
1272

1273
  First, if the device is assembled (Attach() is successfull), then
1274
  the device is shutdown. Then the children of the device are
1275
  shutdown.
1276

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

1281
  @type disk: L{objects.Disk}
1282
  @param disk: the description of the disk we should
1283
      shutdown
1284
  @rtype: boolean
1285
  @return: the success of the operation
1286

1287
  """
1288
  msgs = []
1289
  result = True
1290
  r_dev = _RecursiveFindBD(disk)
1291
  if r_dev is not None:
1292
    r_path = r_dev.dev_path
1293
    try:
1294
      r_dev.Shutdown()
1295
      DevCacheManager.RemoveCache(r_path)
1296
    except errors.BlockDeviceError, err:
1297
      msgs.append(str(err))
1298
      result = False
1299

    
1300
  if disk.children:
1301
    for child in disk.children:
1302
      c_status, c_msg = BlockdevShutdown(child)
1303
      result = result and c_status
1304
      if c_msg: # not an empty message
1305
        msgs.append(c_msg)
1306

    
1307
  return (result, "; ".join(msgs))
1308

    
1309

    
1310
def BlockdevAddchildren(parent_cdev, new_cdevs):
1311
  """Extend a mirrored block device.
1312

1313
  @type parent_cdev: L{objects.Disk}
1314
  @param parent_cdev: the disk to which we should add children
1315
  @type new_cdevs: list of L{objects.Disk}
1316
  @param new_cdevs: the list of children which we should add
1317
  @rtype: boolean
1318
  @return: the success of the operation
1319

1320
  """
1321
  parent_bdev = _RecursiveFindBD(parent_cdev)
1322
  if parent_bdev is None:
1323
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1324
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1325
  if new_bdevs.count(None) > 0:
1326
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1327
  parent_bdev.AddChildren(new_bdevs)
1328
  return (True, None)
1329

    
1330

    
1331
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1332
  """Shrink a mirrored block device.
1333

1334
  @type parent_cdev: L{objects.Disk}
1335
  @param parent_cdev: the disk from which we should remove children
1336
  @type new_cdevs: list of L{objects.Disk}
1337
  @param new_cdevs: the list of children which we should remove
1338
  @rtype: boolean
1339
  @return: the success of the operation
1340

1341
  """
1342
  parent_bdev = _RecursiveFindBD(parent_cdev)
1343
  if parent_bdev is None:
1344
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1345
  devs = []
1346
  for disk in new_cdevs:
1347
    rpath = disk.StaticDevPath()
1348
    if rpath is None:
1349
      bd = _RecursiveFindBD(disk)
1350
      if bd is None:
1351
        _Fail("Can't find device %s while removing children", disk)
1352
      else:
1353
        devs.append(bd.dev_path)
1354
    else:
1355
      devs.append(rpath)
1356
  parent_bdev.RemoveChildren(devs)
1357
  return (True, None)
1358

    
1359

    
1360
def BlockdevGetmirrorstatus(disks):
1361
  """Get the mirroring status of a list of devices.
1362

1363
  @type disks: list of L{objects.Disk}
1364
  @param disks: the list of disks which we should query
1365
  @rtype: disk
1366
  @return:
1367
      a list of (mirror_done, estimated_time) tuples, which
1368
      are the result of L{bdev.BlockDev.CombinedSyncStatus}
1369
  @raise errors.BlockDeviceError: if any of the disks cannot be
1370
      found
1371

1372
  """
1373
  stats = []
1374
  for dsk in disks:
1375
    rbd = _RecursiveFindBD(dsk)
1376
    if rbd is None:
1377
      _Fail("Can't find device %s", dsk)
1378
    stats.append(rbd.CombinedSyncStatus())
1379
  return True, stats
1380

    
1381

    
1382
def _RecursiveFindBD(disk):
1383
  """Check if a device is activated.
1384

1385
  If so, return informations about the real device.
1386

1387
  @type disk: L{objects.Disk}
1388
  @param disk: the disk object we need to find
1389

1390
  @return: None if the device can't be found,
1391
      otherwise the device instance
1392

1393
  """
1394
  children = []
1395
  if disk.children:
1396
    for chdisk in disk.children:
1397
      children.append(_RecursiveFindBD(chdisk))
1398

    
1399
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children)
1400

    
1401

    
1402
def BlockdevFind(disk):
1403
  """Check if a device is activated.
1404

1405
  If it is, return informations about the real device.
1406

1407
  @type disk: L{objects.Disk}
1408
  @param disk: the disk to find
1409
  @rtype: None or tuple
1410
  @return: None if the disk cannot be found, otherwise a
1411
      tuple (device_path, major, minor, sync_percent,
1412
      estimated_time, is_degraded)
1413

1414
  """
1415
  try:
1416
    rbd = _RecursiveFindBD(disk)
1417
  except errors.BlockDeviceError, err:
1418
    _Fail("Failed to find device: %s", err, exc=True)
1419
  if rbd is None:
1420
    return (True, None)
1421
  return (True, (rbd.dev_path, rbd.major, rbd.minor) + rbd.GetSyncStatus())
1422

    
1423

    
1424
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1425
  """Write a file to the filesystem.
1426

1427
  This allows the master to overwrite(!) a file. It will only perform
1428
  the operation if the file belongs to a list of configuration files.
1429

1430
  @type file_name: str
1431
  @param file_name: the target file name
1432
  @type data: str
1433
  @param data: the new contents of the file
1434
  @type mode: int
1435
  @param mode: the mode to give the file (can be None)
1436
  @type uid: int
1437
  @param uid: the owner of the file (can be -1 for default)
1438
  @type gid: int
1439
  @param gid: the group of the file (can be -1 for default)
1440
  @type atime: float
1441
  @param atime: the atime to set on the file (can be None)
1442
  @type mtime: float
1443
  @param mtime: the mtime to set on the file (can be None)
1444
  @rtype: boolean
1445
  @return: the success of the operation; errors are logged
1446
      in the node daemon log
1447

1448
  """
1449
  if not os.path.isabs(file_name):
1450
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
1451

    
1452
  allowed_files = set([
1453
    constants.CLUSTER_CONF_FILE,
1454
    constants.ETC_HOSTS,
1455
    constants.SSH_KNOWN_HOSTS_FILE,
1456
    constants.VNC_PASSWORD_FILE,
1457
    constants.RAPI_CERT_FILE,
1458
    constants.RAPI_USERS_FILE,
1459
    ])
1460

    
1461
  for hv_name in constants.HYPER_TYPES:
1462
    hv_class = hypervisor.GetHypervisor(hv_name)
1463
    allowed_files.update(hv_class.GetAncillaryFiles())
1464

    
1465
  if file_name not in allowed_files:
1466
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
1467
          file_name)
1468

    
1469
  raw_data = _Decompress(data)
1470

    
1471
  utils.WriteFile(file_name, data=raw_data, mode=mode, uid=uid, gid=gid,
1472
                  atime=atime, mtime=mtime)
1473
  return (True, "success")
1474

    
1475

    
1476
def WriteSsconfFiles(values):
1477
  """Update all ssconf files.
1478

1479
  Wrapper around the SimpleStore.WriteFiles.
1480

1481
  """
1482
  ssconf.SimpleStore().WriteFiles(values)
1483
  return True, None
1484

    
1485

    
1486
def _ErrnoOrStr(err):
1487
  """Format an EnvironmentError exception.
1488

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

1493
  @type err: L{EnvironmentError}
1494
  @param err: the exception to format
1495

1496
  """
1497
  if hasattr(err, 'errno'):
1498
    detail = errno.errorcode[err.errno]
1499
  else:
1500
    detail = str(err)
1501
  return detail
1502

    
1503

    
1504
def _OSOndiskVersion(name, os_dir):
1505
  """Compute and return the API version of a given OS.
1506

1507
  This function will try to read the API version of the OS given by
1508
  the 'name' parameter and residing in the 'os_dir' directory.
1509

1510
  @type name: str
1511
  @param name: the OS name we should look for
1512
  @type os_dir: str
1513
  @param os_dir: the directory inwhich we should look for the OS
1514
  @rtype: tuple
1515
  @return: tuple (status, data) with status denoting the validity and
1516
      data holding either the vaid versions or an error message
1517

1518
  """
1519
  api_file = os.path.sep.join([os_dir, "ganeti_api_version"])
1520

    
1521
  try:
1522
    st = os.stat(api_file)
1523
  except EnvironmentError, err:
1524
    return False, ("Required file 'ganeti_api_version' file not"
1525
                   " found under path %s: %s" % (os_dir, _ErrnoOrStr(err)))
1526

    
1527
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1528
    return False, ("File 'ganeti_api_version' file at %s is not"
1529
                   " a regular file" % os_dir)
1530

    
1531
  try:
1532
    f = open(api_file)
1533
    try:
1534
      api_versions = f.readlines()
1535
    finally:
1536
      f.close()
1537
  except EnvironmentError, err:
1538
    return False, ("Error while reading the API version file at %s: %s" %
1539
                   (api_file, _ErrnoOrStr(err)))
1540

    
1541
  api_versions = [version.strip() for version in api_versions]
1542
  try:
1543
    api_versions = [int(version) for version in api_versions]
1544
  except (TypeError, ValueError), err:
1545
    return False, ("API version(s) can't be converted to integer: %s" %
1546
                   str(err))
1547

    
1548
  return True, api_versions
1549

    
1550

    
1551
def DiagnoseOS(top_dirs=None):
1552
  """Compute the validity for all OSes.
1553

1554
  @type top_dirs: list
1555
  @param top_dirs: the list of directories in which to
1556
      search (if not given defaults to
1557
      L{constants.OS_SEARCH_PATH})
1558
  @rtype: list of L{objects.OS}
1559
  @return: a list of tuples (name, path, status, diagnose)
1560
      for all (potential) OSes under all search paths, where:
1561
          - name is the (potential) OS name
1562
          - path is the full path to the OS
1563
          - status True/False is the validity of the OS
1564
          - diagnose is the error message for an invalid OS, otherwise empty
1565

1566
  """
1567
  if top_dirs is None:
1568
    top_dirs = constants.OS_SEARCH_PATH
1569

    
1570
  result = []
1571
  for dir_name in top_dirs:
1572
    if os.path.isdir(dir_name):
1573
      try:
1574
        f_names = utils.ListVisibleFiles(dir_name)
1575
      except EnvironmentError, err:
1576
        logging.exception("Can't list the OS directory %s", dir_name)
1577
        break
1578
      for name in f_names:
1579
        os_path = os.path.sep.join([dir_name, name])
1580
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
1581
        if status:
1582
          diagnose = ""
1583
        else:
1584
          diagnose = os_inst
1585
        result.append((name, os_path, status, diagnose))
1586

    
1587
  return True, result
1588

    
1589

    
1590
def _TryOSFromDisk(name, base_dir=None):
1591
  """Create an OS instance from disk.
1592

1593
  This function will return an OS instance if the given name is a
1594
  valid OS name.
1595

1596
  @type base_dir: string
1597
  @keyword base_dir: Base directory containing OS installations.
1598
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1599
  @rtype: tuple
1600
  @return: success and either the OS instance if we find a valid one,
1601
      or error message
1602

1603
  """
1604
  if base_dir is None:
1605
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1606
    if os_dir is None:
1607
      return False, "Directory for OS %s not found in search path" % name
1608
  else:
1609
    os_dir = os.path.sep.join([base_dir, name])
1610

    
1611
  status, api_versions = _OSOndiskVersion(name, os_dir)
1612
  if not status:
1613
    # push the error up
1614
    return status, api_versions
1615

    
1616
  if constants.OS_API_VERSION not in api_versions:
1617
    return False, ("API version mismatch for path '%s': found %s, want %s." %
1618
                   (os_dir, api_versions, constants.OS_API_VERSION))
1619

    
1620
  # OS Scripts dictionary, we will populate it with the actual script names
1621
  os_scripts = dict.fromkeys(constants.OS_SCRIPTS)
1622

    
1623
  for script in os_scripts:
1624
    os_scripts[script] = os.path.sep.join([os_dir, script])
1625

    
1626
    try:
1627
      st = os.stat(os_scripts[script])
1628
    except EnvironmentError, err:
1629
      return False, ("Script '%s' under path '%s' is missing (%s)" %
1630
                     (script, os_dir, _ErrnoOrStr(err)))
1631

    
1632
    if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1633
      return False, ("Script '%s' under path '%s' is not executable" %
1634
                     (script, os_dir))
1635

    
1636
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1637
      return False, ("Script '%s' under path '%s' is not a regular file" %
1638
                     (script, os_dir))
1639

    
1640
  os_obj = objects.OS(name=name, path=os_dir,
1641
                      create_script=os_scripts[constants.OS_SCRIPT_CREATE],
1642
                      export_script=os_scripts[constants.OS_SCRIPT_EXPORT],
1643
                      import_script=os_scripts[constants.OS_SCRIPT_IMPORT],
1644
                      rename_script=os_scripts[constants.OS_SCRIPT_RENAME],
1645
                      api_versions=api_versions)
1646
  return True, os_obj
1647

    
1648

    
1649
def OSFromDisk(name, base_dir=None):
1650
  """Create an OS instance from disk.
1651

1652
  This function will return an OS instance if the given name is a
1653
  valid OS name. Otherwise, it will raise an appropriate
1654
  L{RPCFail} exception, detailing why this is not a valid OS.
1655

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

1659
  @type base_dir: string
1660
  @keyword base_dir: Base directory containing OS installations.
1661
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1662
  @rtype: L{objects.OS}
1663
  @return: the OS instance if we find a valid one
1664
  @raise RPCFail: if we don't find a valid OS
1665

1666
  """
1667
  status, payload = _TryOSFromDisk(name, base_dir)
1668

    
1669
  if not status:
1670
    _Fail(payload)
1671

    
1672
  return payload
1673

    
1674

    
1675
def OSEnvironment(instance, debug=0):
1676
  """Calculate the environment for an os script.
1677

1678
  @type instance: L{objects.Instance}
1679
  @param instance: target instance for the os script run
1680
  @type debug: integer
1681
  @param debug: debug level (0 or 1, for OS Api 10)
1682
  @rtype: dict
1683
  @return: dict of environment variables
1684
  @raise errors.BlockDeviceError: if the block device
1685
      cannot be found
1686

1687
  """
1688
  result = {}
1689
  result['OS_API_VERSION'] = '%d' % constants.OS_API_VERSION
1690
  result['INSTANCE_NAME'] = instance.name
1691
  result['INSTANCE_OS'] = instance.os
1692
  result['HYPERVISOR'] = instance.hypervisor
1693
  result['DISK_COUNT'] = '%d' % len(instance.disks)
1694
  result['NIC_COUNT'] = '%d' % len(instance.nics)
1695
  result['DEBUG_LEVEL'] = '%d' % debug
1696
  for idx, disk in enumerate(instance.disks):
1697
    real_disk = _RecursiveFindBD(disk)
1698
    if real_disk is None:
1699
      raise errors.BlockDeviceError("Block device '%s' is not set up" %
1700
                                    str(disk))
1701
    real_disk.Open()
1702
    result['DISK_%d_PATH' % idx] = real_disk.dev_path
1703
    result['DISK_%d_ACCESS' % idx] = disk.mode
1704
    if constants.HV_DISK_TYPE in instance.hvparams:
1705
      result['DISK_%d_FRONTEND_TYPE' % idx] = \
1706
        instance.hvparams[constants.HV_DISK_TYPE]
1707
    if disk.dev_type in constants.LDS_BLOCK:
1708
      result['DISK_%d_BACKEND_TYPE' % idx] = 'block'
1709
    elif disk.dev_type == constants.LD_FILE:
1710
      result['DISK_%d_BACKEND_TYPE' % idx] = \
1711
        'file:%s' % disk.physical_id[0]
1712
  for idx, nic in enumerate(instance.nics):
1713
    result['NIC_%d_MAC' % idx] = nic.mac
1714
    if nic.ip:
1715
      result['NIC_%d_IP' % idx] = nic.ip
1716
    result['NIC_%d_MODE' % idx] = nic.nicparams[constants.NIC_MODE]
1717
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
1718
      result['NIC_%d_BRIDGE' % idx] = nic.nicparams[constants.NIC_LINK]
1719
    if nic.nicparams[constants.NIC_LINK]:
1720
      result['NIC_%d_LINK' % idx] = nic.nicparams[constants.NIC_LINK]
1721
    if constants.HV_NIC_TYPE in instance.hvparams:
1722
      result['NIC_%d_FRONTEND_TYPE' % idx] = \
1723
        instance.hvparams[constants.HV_NIC_TYPE]
1724

    
1725
  return result
1726

    
1727
def BlockdevGrow(disk, amount):
1728
  """Grow a stack of block devices.
1729

1730
  This function is called recursively, with the childrens being the
1731
  first ones to resize.
1732

1733
  @type disk: L{objects.Disk}
1734
  @param disk: the disk to be grown
1735
  @rtype: (status, result)
1736
  @return: a tuple with the status of the operation
1737
      (True/False), and the errors message if status
1738
      is False
1739

1740
  """
1741
  r_dev = _RecursiveFindBD(disk)
1742
  if r_dev is None:
1743
    return False, "Cannot find block device %s" % (disk,)
1744

    
1745
  try:
1746
    r_dev.Grow(amount)
1747
  except errors.BlockDeviceError, err:
1748
    _Fail("Failed to grow block device: %s", err, exc=True)
1749

    
1750
  return True, None
1751

    
1752

    
1753
def BlockdevSnapshot(disk):
1754
  """Create a snapshot copy of a block device.
1755

1756
  This function is called recursively, and the snapshot is actually created
1757
  just for the leaf lvm backend device.
1758

1759
  @type disk: L{objects.Disk}
1760
  @param disk: the disk to be snapshotted
1761
  @rtype: string
1762
  @return: snapshot disk path
1763

1764
  """
1765
  if disk.children:
1766
    if len(disk.children) == 1:
1767
      # only one child, let's recurse on it
1768
      return BlockdevSnapshot(disk.children[0])
1769
    else:
1770
      # more than one child, choose one that matches
1771
      for child in disk.children:
1772
        if child.size == disk.size:
1773
          # return implies breaking the loop
1774
          return BlockdevSnapshot(child)
1775
  elif disk.dev_type == constants.LD_LV:
1776
    r_dev = _RecursiveFindBD(disk)
1777
    if r_dev is not None:
1778
      # let's stay on the safe side and ask for the full size, for now
1779
      return True, r_dev.Snapshot(disk.size)
1780
    else:
1781
      _Fail("Cannot find block device %s", disk)
1782
  else:
1783
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
1784
          disk.unique_id, disk.dev_type)
1785

    
1786

    
1787
def ExportSnapshot(disk, dest_node, instance, cluster_name, idx):
1788
  """Export a block device snapshot to a remote node.
1789

1790
  @type disk: L{objects.Disk}
1791
  @param disk: the description of the disk to export
1792
  @type dest_node: str
1793
  @param dest_node: the destination node to export to
1794
  @type instance: L{objects.Instance}
1795
  @param instance: the instance object to whom the disk belongs
1796
  @type cluster_name: str
1797
  @param cluster_name: the cluster name, needed for SSH hostalias
1798
  @type idx: int
1799
  @param idx: the index of the disk in the instance's disk list,
1800
      used to export to the OS scripts environment
1801
  @rtype: boolean
1802
  @return: the success of the operation
1803

1804
  """
1805
  export_env = OSEnvironment(instance)
1806

    
1807
  inst_os = OSFromDisk(instance.os)
1808
  export_script = inst_os.export_script
1809

    
1810
  logfile = "%s/exp-%s-%s-%s.log" % (constants.LOG_OS_DIR, inst_os.name,
1811
                                     instance.name, int(time.time()))
1812
  if not os.path.exists(constants.LOG_OS_DIR):
1813
    os.mkdir(constants.LOG_OS_DIR, 0750)
1814
  real_disk = _RecursiveFindBD(disk)
1815
  if real_disk is None:
1816
    _Fail("Block device '%s' is not set up", disk)
1817

    
1818
  real_disk.Open()
1819

    
1820
  export_env['EXPORT_DEVICE'] = real_disk.dev_path
1821
  export_env['EXPORT_INDEX'] = str(idx)
1822

    
1823
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1824
  destfile = disk.physical_id[1]
1825

    
1826
  # the target command is built out of three individual commands,
1827
  # which are joined by pipes; we check each individual command for
1828
  # valid parameters
1829
  expcmd = utils.BuildShellCmd("cd %s; %s 2>%s", inst_os.path,
1830
                               export_script, logfile)
1831

    
1832
  comprcmd = "gzip"
1833

    
1834
  destcmd = utils.BuildShellCmd("mkdir -p %s && cat > %s/%s",
1835
                                destdir, destdir, destfile)
1836
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1837
                                                   constants.GANETI_RUNAS,
1838
                                                   destcmd)
1839

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

    
1843
  result = utils.RunCmd(command, env=export_env)
1844

    
1845
  if result.failed:
1846
    _Fail("OS snapshot export command '%s' returned error: %s"
1847
          " output: %s", command, result.fail_reason, result.output)
1848

    
1849
  return (True, None)
1850

    
1851

    
1852
def FinalizeExport(instance, snap_disks):
1853
  """Write out the export configuration information.
1854

1855
  @type instance: L{objects.Instance}
1856
  @param instance: the instance which we export, used for
1857
      saving configuration
1858
  @type snap_disks: list of L{objects.Disk}
1859
  @param snap_disks: list of snapshot block devices, which
1860
      will be used to get the actual name of the dump file
1861

1862
  @rtype: boolean
1863
  @return: the success of the operation
1864

1865
  """
1866
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1867
  finaldestdir = os.path.join(constants.EXPORT_DIR, instance.name)
1868

    
1869
  config = objects.SerializableConfigParser()
1870

    
1871
  config.add_section(constants.INISECT_EXP)
1872
  config.set(constants.INISECT_EXP, 'version', '0')
1873
  config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
1874
  config.set(constants.INISECT_EXP, 'source', instance.primary_node)
1875
  config.set(constants.INISECT_EXP, 'os', instance.os)
1876
  config.set(constants.INISECT_EXP, 'compression', 'gzip')
1877

    
1878
  config.add_section(constants.INISECT_INS)
1879
  config.set(constants.INISECT_INS, 'name', instance.name)
1880
  config.set(constants.INISECT_INS, 'memory', '%d' %
1881
             instance.beparams[constants.BE_MEMORY])
1882
  config.set(constants.INISECT_INS, 'vcpus', '%d' %
1883
             instance.beparams[constants.BE_VCPUS])
1884
  config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
1885

    
1886
  nic_total = 0
1887
  for nic_count, nic in enumerate(instance.nics):
1888
    nic_total += 1
1889
    config.set(constants.INISECT_INS, 'nic%d_mac' %
1890
               nic_count, '%s' % nic.mac)
1891
    config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
1892
    config.set(constants.INISECT_INS, 'nic%d_bridge' % nic_count,
1893
               '%s' % nic.bridge)
1894
  # TODO: redundant: on load can read nics until it doesn't exist
1895
  config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_total)
1896

    
1897
  disk_total = 0
1898
  for disk_count, disk in enumerate(snap_disks):
1899
    if disk:
1900
      disk_total += 1
1901
      config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
1902
                 ('%s' % disk.iv_name))
1903
      config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
1904
                 ('%s' % disk.physical_id[1]))
1905
      config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
1906
                 ('%d' % disk.size))
1907

    
1908
  config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_total)
1909

    
1910
  utils.WriteFile(os.path.join(destdir, constants.EXPORT_CONF_FILE),
1911
                  data=config.Dumps())
1912
  shutil.rmtree(finaldestdir, True)
1913
  shutil.move(destdir, finaldestdir)
1914

    
1915
  return True, None
1916

    
1917

    
1918
def ExportInfo(dest):
1919
  """Get export configuration information.
1920

1921
  @type dest: str
1922
  @param dest: directory containing the export
1923

1924
  @rtype: L{objects.SerializableConfigParser}
1925
  @return: a serializable config file containing the
1926
      export info
1927

1928
  """
1929
  cff = os.path.join(dest, constants.EXPORT_CONF_FILE)
1930

    
1931
  config = objects.SerializableConfigParser()
1932
  config.read(cff)
1933

    
1934
  if (not config.has_section(constants.INISECT_EXP) or
1935
      not config.has_section(constants.INISECT_INS)):
1936
    _Fail("Export info file doesn't have the required fields")
1937

    
1938
  return True, config.Dumps()
1939

    
1940

    
1941
def ImportOSIntoInstance(instance, src_node, src_images, cluster_name):
1942
  """Import an os image into an instance.
1943

1944
  @type instance: L{objects.Instance}
1945
  @param instance: instance to import the disks into
1946
  @type src_node: string
1947
  @param src_node: source node for the disk images
1948
  @type src_images: list of string
1949
  @param src_images: absolute paths of the disk images
1950
  @rtype: list of boolean
1951
  @return: each boolean represent the success of importing the n-th disk
1952

1953
  """
1954
  import_env = OSEnvironment(instance)
1955
  inst_os = OSFromDisk(instance.os)
1956
  import_script = inst_os.import_script
1957

    
1958
  logfile = "%s/import-%s-%s-%s.log" % (constants.LOG_OS_DIR, instance.os,
1959
                                        instance.name, int(time.time()))
1960
  if not os.path.exists(constants.LOG_OS_DIR):
1961
    os.mkdir(constants.LOG_OS_DIR, 0750)
1962

    
1963
  comprcmd = "gunzip"
1964
  impcmd = utils.BuildShellCmd("(cd %s; %s >%s 2>&1)", inst_os.path,
1965
                               import_script, logfile)
1966

    
1967
  final_result = []
1968
  for idx, image in enumerate(src_images):
1969
    if image:
1970
      destcmd = utils.BuildShellCmd('cat %s', image)
1971
      remotecmd = _GetSshRunner(cluster_name).BuildCmd(src_node,
1972
                                                       constants.GANETI_RUNAS,
1973
                                                       destcmd)
1974
      command = '|'.join([utils.ShellQuoteArgs(remotecmd), comprcmd, impcmd])
1975
      import_env['IMPORT_DEVICE'] = import_env['DISK_%d_PATH' % idx]
1976
      import_env['IMPORT_INDEX'] = str(idx)
1977
      result = utils.RunCmd(command, env=import_env)
1978
      if result.failed:
1979
        logging.error("Disk import command '%s' returned error: %s"
1980
                      " output: %s", command, result.fail_reason,
1981
                      result.output)
1982
        final_result.append("error importing disk %d: %s, %s" %
1983
                            (idx, result.fail_reason, result.output[-100]))
1984

    
1985
  if final_result:
1986
    return False, "; ".join(final_result)
1987
  return True, None
1988

    
1989

    
1990
def ListExports():
1991
  """Return a list of exports currently available on this machine.
1992

1993
  @rtype: list
1994
  @return: list of the exports
1995

1996
  """
1997
  if os.path.isdir(constants.EXPORT_DIR):
1998
    return True, utils.ListVisibleFiles(constants.EXPORT_DIR)
1999
  else:
2000
    return False, "No exports directory"
2001

    
2002

    
2003
def RemoveExport(export):
2004
  """Remove an existing export from the node.
2005

2006
  @type export: str
2007
  @param export: the name of the export to remove
2008
  @rtype: boolean
2009
  @return: the success of the operation
2010

2011
  """
2012
  target = os.path.join(constants.EXPORT_DIR, export)
2013

    
2014
  try:
2015
    shutil.rmtree(target)
2016
  except EnvironmentError, err:
2017
    _Fail("Error while removing the export: %s", err, exc=True)
2018

    
2019
  return True, None
2020

    
2021

    
2022
def BlockdevRename(devlist):
2023
  """Rename a list of block devices.
2024

2025
  @type devlist: list of tuples
2026
  @param devlist: list of tuples of the form  (disk,
2027
      new_logical_id, new_physical_id); disk is an
2028
      L{objects.Disk} object describing the current disk,
2029
      and new logical_id/physical_id is the name we
2030
      rename it to
2031
  @rtype: boolean
2032
  @return: True if all renames succeeded, False otherwise
2033

2034
  """
2035
  msgs = []
2036
  result = True
2037
  for disk, unique_id in devlist:
2038
    dev = _RecursiveFindBD(disk)
2039
    if dev is None:
2040
      msgs.append("Can't find device %s in rename" % str(disk))
2041
      result = False
2042
      continue
2043
    try:
2044
      old_rpath = dev.dev_path
2045
      dev.Rename(unique_id)
2046
      new_rpath = dev.dev_path
2047
      if old_rpath != new_rpath:
2048
        DevCacheManager.RemoveCache(old_rpath)
2049
        # FIXME: we should add the new cache information here, like:
2050
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2051
        # but we don't have the owner here - maybe parse from existing
2052
        # cache? for now, we only lose lvm data when we rename, which
2053
        # is less critical than DRBD or MD
2054
    except errors.BlockDeviceError, err:
2055
      msgs.append("Can't rename device '%s' to '%s': %s" %
2056
                  (dev, unique_id, err))
2057
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2058
      result = False
2059
  return (result, "; ".join(msgs))
2060

    
2061

    
2062
def _TransformFileStorageDir(file_storage_dir):
2063
  """Checks whether given file_storage_dir is valid.
2064

2065
  Checks wheter the given file_storage_dir is within the cluster-wide
2066
  default file_storage_dir stored in SimpleStore. Only paths under that
2067
  directory are allowed.
2068

2069
  @type file_storage_dir: str
2070
  @param file_storage_dir: the path to check
2071

2072
  @return: the normalized path if valid, None otherwise
2073

2074
  """
2075
  cfg = _GetConfig()
2076
  file_storage_dir = os.path.normpath(file_storage_dir)
2077
  base_file_storage_dir = cfg.GetFileStorageDir()
2078
  if (not os.path.commonprefix([file_storage_dir, base_file_storage_dir]) ==
2079
      base_file_storage_dir):
2080
    _Fail("File storage directory '%s' is not under base file"
2081
          " storage directory '%s'", file_storage_dir, base_file_storage_dir)
2082
  return file_storage_dir
2083

    
2084

    
2085
def CreateFileStorageDir(file_storage_dir):
2086
  """Create file storage directory.
2087

2088
  @type file_storage_dir: str
2089
  @param file_storage_dir: directory to create
2090

2091
  @rtype: tuple
2092
  @return: tuple with first element a boolean indicating wheter dir
2093
      creation was successful or not
2094

2095
  """
2096
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2097
  if os.path.exists(file_storage_dir):
2098
    if not os.path.isdir(file_storage_dir):
2099
      _Fail("Specified storage dir '%s' is not a directory",
2100
            file_storage_dir)
2101
  else:
2102
    try:
2103
      os.makedirs(file_storage_dir, 0750)
2104
    except OSError, err:
2105
      _Fail("Cannot create file storage directory '%s': %s",
2106
            file_storage_dir, err, exc=True)
2107
  return True, None
2108

    
2109

    
2110
def RemoveFileStorageDir(file_storage_dir):
2111
  """Remove file storage directory.
2112

2113
  Remove it only if it's empty. If not log an error and return.
2114

2115
  @type file_storage_dir: str
2116
  @param file_storage_dir: the directory we should cleanup
2117
  @rtype: tuple (success,)
2118
  @return: tuple of one element, C{success}, denoting
2119
      whether the operation was successfull
2120

2121
  """
2122
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2123
  if os.path.exists(file_storage_dir):
2124
    if not os.path.isdir(file_storage_dir):
2125
      _Fail("Specified Storage directory '%s' is not a directory",
2126
            file_storage_dir)
2127
    # deletes dir only if empty, otherwise we want to return False
2128
    try:
2129
      os.rmdir(file_storage_dir)
2130
    except OSError, err:
2131
      _Fail("Cannot remove file storage directory '%s': %s",
2132
            file_storage_dir, err)
2133

    
2134
  return True, None
2135

    
2136

    
2137
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2138
  """Rename the file storage directory.
2139

2140
  @type old_file_storage_dir: str
2141
  @param old_file_storage_dir: the current path
2142
  @type new_file_storage_dir: str
2143
  @param new_file_storage_dir: the name we should rename to
2144
  @rtype: tuple (success,)
2145
  @return: tuple of one element, C{success}, denoting
2146
      whether the operation was successful
2147

2148
  """
2149
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2150
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2151
  if not os.path.exists(new_file_storage_dir):
2152
    if os.path.isdir(old_file_storage_dir):
2153
      try:
2154
        os.rename(old_file_storage_dir, new_file_storage_dir)
2155
      except OSError, err:
2156
        _Fail("Cannot rename '%s' to '%s': %s",
2157
              old_file_storage_dir, new_file_storage_dir, err)
2158
    else:
2159
      _Fail("Specified storage dir '%s' is not a directory",
2160
            old_file_storage_dir)
2161
  else:
2162
    if os.path.exists(old_file_storage_dir):
2163
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2164
            old_file_storage_dir, new_file_storage_dir)
2165
  return True, None
2166

    
2167

    
2168
def _EnsureJobQueueFile(file_name):
2169
  """Checks whether the given filename is in the queue directory.
2170

2171
  @type file_name: str
2172
  @param file_name: the file name we should check
2173
  @rtype: None
2174
  @raises RPCFail: if the file is not valid
2175

2176
  """
2177
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2178
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2179

    
2180
  if not result:
2181
    _Fail("Passed job queue file '%s' does not belong to"
2182
          " the queue directory '%s'", file_name, queue_dir)
2183

    
2184

    
2185
def JobQueueUpdate(file_name, content):
2186
  """Updates a file in the queue directory.
2187

2188
  This is just a wrapper over L{utils.WriteFile}, with proper
2189
  checking.
2190

2191
  @type file_name: str
2192
  @param file_name: the job file name
2193
  @type content: str
2194
  @param content: the new job contents
2195
  @rtype: boolean
2196
  @return: the success of the operation
2197

2198
  """
2199
  _EnsureJobQueueFile(file_name)
2200

    
2201
  # Write and replace the file atomically
2202
  utils.WriteFile(file_name, data=_Decompress(content))
2203

    
2204
  return True, None
2205

    
2206

    
2207
def JobQueueRename(old, new):
2208
  """Renames a job queue file.
2209

2210
  This is just a wrapper over os.rename with proper checking.
2211

2212
  @type old: str
2213
  @param old: the old (actual) file name
2214
  @type new: str
2215
  @param new: the desired file name
2216
  @rtype: tuple
2217
  @return: the success of the operation and payload
2218

2219
  """
2220
  _EnsureJobQueueFile(old)
2221
  _EnsureJobQueueFile(new)
2222

    
2223
  utils.RenameFile(old, new, mkdir=True)
2224

    
2225
  return True, None
2226

    
2227

    
2228
def JobQueueSetDrainFlag(drain_flag):
2229
  """Set the drain flag for the queue.
2230

2231
  This will set or unset the queue drain flag.
2232

2233
  @type drain_flag: boolean
2234
  @param drain_flag: if True, will set the drain flag, otherwise reset it.
2235
  @rtype: truple
2236
  @return: always True, None
2237
  @warning: the function always returns True
2238

2239
  """
2240
  if drain_flag:
2241
    utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True)
2242
  else:
2243
    utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
2244

    
2245
  return True, None
2246

    
2247

    
2248
def BlockdevClose(instance_name, disks):
2249
  """Closes the given block devices.
2250

2251
  This means they will be switched to secondary mode (in case of
2252
  DRBD).
2253

2254
  @param instance_name: if the argument is not empty, the symlinks
2255
      of this instance will be removed
2256
  @type disks: list of L{objects.Disk}
2257
  @param disks: the list of disks to be closed
2258
  @rtype: tuple (success, message)
2259
  @return: a tuple of success and message, where success
2260
      indicates the succes of the operation, and message
2261
      which will contain the error details in case we
2262
      failed
2263

2264
  """
2265
  bdevs = []
2266
  for cf in disks:
2267
    rd = _RecursiveFindBD(cf)
2268
    if rd is None:
2269
      _Fail("Can't find device %s", cf)
2270
    bdevs.append(rd)
2271

    
2272
  msg = []
2273
  for rd in bdevs:
2274
    try:
2275
      rd.Close()
2276
    except errors.BlockDeviceError, err:
2277
      msg.append(str(err))
2278
  if msg:
2279
    return (False, "Can't make devices secondary: %s" % ",".join(msg))
2280
  else:
2281
    if instance_name:
2282
      _RemoveBlockDevLinks(instance_name, disks)
2283
    return (True, "All devices secondary")
2284

    
2285

    
2286
def ValidateHVParams(hvname, hvparams):
2287
  """Validates the given hypervisor parameters.
2288

2289
  @type hvname: string
2290
  @param hvname: the hypervisor name
2291
  @type hvparams: dict
2292
  @param hvparams: the hypervisor parameters to be validated
2293
  @rtype: tuple (success, message)
2294
  @return: a tuple of success and message, where success
2295
      indicates the succes of the operation, and message
2296
      which will contain the error details in case we
2297
      failed
2298

2299
  """
2300
  try:
2301
    hv_type = hypervisor.GetHypervisor(hvname)
2302
    hv_type.ValidateParameters(hvparams)
2303
    return (True, "Validation passed")
2304
  except errors.HypervisorError, err:
2305
    return (False, str(err))
2306

    
2307

    
2308
def DemoteFromMC():
2309
  """Demotes the current node from master candidate role.
2310

2311
  """
2312
  # try to ensure we're not the master by mistake
2313
  master, myself = ssconf.GetMasterAndMyself()
2314
  if master == myself:
2315
    return (False, "ssconf status shows I'm the master node, will not demote")
2316
  pid_file = utils.DaemonPidFileName(constants.MASTERD_PID)
2317
  if utils.IsProcessAlive(utils.ReadPidFile(pid_file)):
2318
    return (False, "The master daemon is running, will not demote")
2319
  try:
2320
    utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2321
  except EnvironmentError, err:
2322
    if err.errno != errno.ENOENT:
2323
      return (False, "Error while backing up cluster file: %s" % str(err))
2324
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2325
  return (True, "Done")
2326

    
2327

    
2328
def _FindDisks(nodes_ip, disks):
2329
  """Sets the physical ID on disks and returns the block devices.
2330

2331
  """
2332
  # set the correct physical ID
2333
  my_name = utils.HostInfo().name
2334
  for cf in disks:
2335
    cf.SetPhysicalID(my_name, nodes_ip)
2336

    
2337
  bdevs = []
2338

    
2339
  for cf in disks:
2340
    rd = _RecursiveFindBD(cf)
2341
    if rd is None:
2342
      _Fail("Can't find device %s", cf)
2343
    bdevs.append(rd)
2344
  return bdevs
2345

    
2346

    
2347
def DrbdDisconnectNet(nodes_ip, disks):
2348
  """Disconnects the network on a list of drbd devices.
2349

2350
  """
2351
  bdevs = _FindDisks(nodes_ip, disks)
2352

    
2353
  # disconnect disks
2354
  for rd in bdevs:
2355
    try:
2356
      rd.DisconnectNet()
2357
    except errors.BlockDeviceError, err:
2358
      _Fail("Can't change network configuration to standalone mode: %s",
2359
            err, exc=True)
2360
  return (True, "All disks are now disconnected")
2361

    
2362

    
2363
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
2364
  """Attaches the network on a list of drbd devices.
2365

2366
  """
2367
  bdevs = _FindDisks(nodes_ip, disks)
2368

    
2369
  if multimaster:
2370
    for idx, rd in enumerate(bdevs):
2371
      try:
2372
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
2373
      except EnvironmentError, err:
2374
        _Fail("Can't create symlink: %s", err)
2375
  # reconnect disks, switch to new master configuration and if
2376
  # needed primary mode
2377
  for rd in bdevs:
2378
    try:
2379
      rd.AttachNet(multimaster)
2380
    except errors.BlockDeviceError, err:
2381
      _Fail("Can't change network configuration: %s", err)
2382
  # wait until the disks are connected; we need to retry the re-attach
2383
  # if the device becomes standalone, as this might happen if the one
2384
  # node disconnects and reconnects in a different mode before the
2385
  # other node reconnects; in this case, one or both of the nodes will
2386
  # decide it has wrong configuration and switch to standalone
2387
  RECONNECT_TIMEOUT = 2 * 60
2388
  sleep_time = 0.100 # start with 100 miliseconds
2389
  timeout_limit = time.time() + RECONNECT_TIMEOUT
2390
  while time.time() < timeout_limit:
2391
    all_connected = True
2392
    for rd in bdevs:
2393
      stats = rd.GetProcStatus()
2394
      if not (stats.is_connected or stats.is_in_resync):
2395
        all_connected = False
2396
      if stats.is_standalone:
2397
        # peer had different config info and this node became
2398
        # standalone, even though this should not happen with the
2399
        # new staged way of changing disk configs
2400
        try:
2401
          rd.ReAttachNet(multimaster)
2402
        except errors.BlockDeviceError, err:
2403
          _Fail("Can't change network configuration: %s", err)
2404
    if all_connected:
2405
      break
2406
    time.sleep(sleep_time)
2407
    sleep_time = min(5, sleep_time * 1.5)
2408
  if not all_connected:
2409
    return (False, "Timeout in disk reconnecting")
2410
  if multimaster:
2411
    # change to primary mode
2412
    for rd in bdevs:
2413
      try:
2414
        rd.Open()
2415
      except errors.BlockDeviceError, err:
2416
        _Fail("Can't change to primary mode: %s", err)
2417
  if multimaster:
2418
    msg = "multi-master and primary"
2419
  else:
2420
    msg = "single-master"
2421
  return (True, "Disks are now configured as %s" % msg)
2422

    
2423

    
2424
def DrbdWaitSync(nodes_ip, disks):
2425
  """Wait until DRBDs have synchronized.
2426

2427
  """
2428
  bdevs = _FindDisks(nodes_ip, disks)
2429

    
2430
  min_resync = 100
2431
  alldone = True
2432
  failure = False
2433
  for rd in bdevs:
2434
    stats = rd.GetProcStatus()
2435
    if not (stats.is_connected or stats.is_in_resync):
2436
      failure = True
2437
      break
2438
    alldone = alldone and (not stats.is_in_resync)
2439
    if stats.sync_percent is not None:
2440
      min_resync = min(min_resync, stats.sync_percent)
2441
  return (not failure, (alldone, min_resync))
2442

    
2443

    
2444
def PowercycleNode(hypervisor_type):
2445
  """Hard-powercycle the node.
2446

2447
  Because we need to return first, and schedule the powercycle in the
2448
  background, we won't be able to report failures nicely.
2449

2450
  """
2451
  hyper = hypervisor.GetHypervisor(hypervisor_type)
2452
  try:
2453
    pid = os.fork()
2454
  except OSError, err:
2455
    # if we can't fork, we'll pretend that we're in the child process
2456
    pid = 0
2457
  if pid > 0:
2458
    return (True, "Reboot scheduled in 5 seconds")
2459
  time.sleep(5)
2460
  hyper.PowercycleNode()
2461

    
2462

    
2463
class HooksRunner(object):
2464
  """Hook runner.
2465

2466
  This class is instantiated on the node side (ganeti-noded) and not
2467
  on the master side.
2468

2469
  """
2470
  RE_MASK = re.compile("^[a-zA-Z0-9_-]+$")
2471

    
2472
  def __init__(self, hooks_base_dir=None):
2473
    """Constructor for hooks runner.
2474

2475
    @type hooks_base_dir: str or None
2476
    @param hooks_base_dir: if not None, this overrides the
2477
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
2478

2479
    """
2480
    if hooks_base_dir is None:
2481
      hooks_base_dir = constants.HOOKS_BASE_DIR
2482
    self._BASE_DIR = hooks_base_dir
2483

    
2484
  @staticmethod
2485
  def ExecHook(script, env):
2486
    """Exec one hook script.
2487

2488
    @type script: str
2489
    @param script: the full path to the script
2490
    @type env: dict
2491
    @param env: the environment with which to exec the script
2492
    @rtype: tuple (success, message)
2493
    @return: a tuple of success and message, where success
2494
        indicates the succes of the operation, and message
2495
        which will contain the error details in case we
2496
        failed
2497

2498
    """
2499
    # exec the process using subprocess and log the output
2500
    fdstdin = None
2501
    try:
2502
      fdstdin = open("/dev/null", "r")
2503
      child = subprocess.Popen([script], stdin=fdstdin, stdout=subprocess.PIPE,
2504
                               stderr=subprocess.STDOUT, close_fds=True,
2505
                               shell=False, cwd="/", env=env)
2506
      output = ""
2507
      try:
2508
        output = child.stdout.read(4096)
2509
        child.stdout.close()
2510
      except EnvironmentError, err:
2511
        output += "Hook script error: %s" % str(err)
2512

    
2513
      while True:
2514
        try:
2515
          result = child.wait()
2516
          break
2517
        except EnvironmentError, err:
2518
          if err.errno == errno.EINTR:
2519
            continue
2520
          raise
2521
    finally:
2522
      # try not to leak fds
2523
      for fd in (fdstdin, ):
2524
        if fd is not None:
2525
          try:
2526
            fd.close()
2527
          except EnvironmentError, err:
2528
            # just log the error
2529
            #logging.exception("Error while closing fd %s", fd)
2530
            pass
2531

    
2532
    return result == 0, utils.SafeEncode(output.strip())
2533

    
2534
  def RunHooks(self, hpath, phase, env):
2535
    """Run the scripts in the hooks directory.
2536

2537
    @type hpath: str
2538
    @param hpath: the path to the hooks directory which
2539
        holds the scripts
2540
    @type phase: str
2541
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
2542
        L{constants.HOOKS_PHASE_POST}
2543
    @type env: dict
2544
    @param env: dictionary with the environment for the hook
2545
    @rtype: list
2546
    @return: list of 3-element tuples:
2547
      - script path
2548
      - script result, either L{constants.HKR_SUCCESS} or
2549
        L{constants.HKR_FAIL}
2550
      - output of the script
2551

2552
    @raise errors.ProgrammerError: for invalid input
2553
        parameters
2554

2555
    """
2556
    if phase == constants.HOOKS_PHASE_PRE:
2557
      suffix = "pre"
2558
    elif phase == constants.HOOKS_PHASE_POST:
2559
      suffix = "post"
2560
    else:
2561
      _Fail("Unknown hooks phase '%s'", phase)
2562

    
2563
    rr = []
2564

    
2565
    subdir = "%s-%s.d" % (hpath, suffix)
2566
    dir_name = "%s/%s" % (self._BASE_DIR, subdir)
2567
    try:
2568
      dir_contents = utils.ListVisibleFiles(dir_name)
2569
    except OSError, err:
2570
      # FIXME: must log output in case of failures
2571
      return True, rr
2572

    
2573
    # we use the standard python sort order,
2574
    # so 00name is the recommended naming scheme
2575
    dir_contents.sort()
2576
    for relname in dir_contents:
2577
      fname = os.path.join(dir_name, relname)
2578
      if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and
2579
          self.RE_MASK.match(relname) is not None):
2580
        rrval = constants.HKR_SKIP
2581
        output = ""
2582
      else:
2583
        result, output = self.ExecHook(fname, env)
2584
        if not result:
2585
          rrval = constants.HKR_FAIL
2586
        else:
2587
          rrval = constants.HKR_SUCCESS
2588
      rr.append(("%s/%s" % (subdir, relname), rrval, output))
2589

    
2590
    return True, rr
2591

    
2592

    
2593
class IAllocatorRunner(object):
2594
  """IAllocator runner.
2595

2596
  This class is instantiated on the node side (ganeti-noded) and not on
2597
  the master side.
2598

2599
  """
2600
  def Run(self, name, idata):
2601
    """Run an iallocator script.
2602

2603
    @type name: str
2604
    @param name: the iallocator script name
2605
    @type idata: str
2606
    @param idata: the allocator input data
2607

2608
    @rtype: tuple
2609
    @return: two element tuple of:
2610
       - status
2611
       - either error message or stdout of allocator (for success)
2612

2613
    """
2614
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
2615
                                  os.path.isfile)
2616
    if alloc_script is None:
2617
      _Fail("iallocator module '%s' not found in the search path", name)
2618

    
2619
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
2620
    try:
2621
      os.write(fd, idata)
2622
      os.close(fd)
2623
      result = utils.RunCmd([alloc_script, fin_name])
2624
      if result.failed:
2625
        _Fail("iallocator module '%s' failed: %s, output '%s'",
2626
              name, result.fail_reason, result.output)
2627
    finally:
2628
      os.unlink(fin_name)
2629

    
2630
    return True, result.stdout
2631

    
2632

    
2633
class DevCacheManager(object):
2634
  """Simple class for managing a cache of block device information.
2635

2636
  """
2637
  _DEV_PREFIX = "/dev/"
2638
  _ROOT_DIR = constants.BDEV_CACHE_DIR
2639

    
2640
  @classmethod
2641
  def _ConvertPath(cls, dev_path):
2642
    """Converts a /dev/name path to the cache file name.
2643

2644
    This replaces slashes with underscores and strips the /dev
2645
    prefix. It then returns the full path to the cache file.
2646

2647
    @type dev_path: str
2648
    @param dev_path: the C{/dev/} path name
2649
    @rtype: str
2650
    @return: the converted path name
2651

2652
    """
2653
    if dev_path.startswith(cls._DEV_PREFIX):
2654
      dev_path = dev_path[len(cls._DEV_PREFIX):]
2655
    dev_path = dev_path.replace("/", "_")
2656
    fpath = "%s/bdev_%s" % (cls._ROOT_DIR, dev_path)
2657
    return fpath
2658

    
2659
  @classmethod
2660
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
2661
    """Updates the cache information for a given device.
2662

2663
    @type dev_path: str
2664
    @param dev_path: the pathname of the device
2665
    @type owner: str
2666
    @param owner: the owner (instance name) of the device
2667
    @type on_primary: bool
2668
    @param on_primary: whether this is the primary
2669
        node nor not
2670
    @type iv_name: str
2671
    @param iv_name: the instance-visible name of the
2672
        device, as in objects.Disk.iv_name
2673

2674
    @rtype: None
2675

2676
    """
2677
    if dev_path is None:
2678
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
2679
      return
2680
    fpath = cls._ConvertPath(dev_path)
2681
    if on_primary:
2682
      state = "primary"
2683
    else:
2684
      state = "secondary"
2685
    if iv_name is None:
2686
      iv_name = "not_visible"
2687
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
2688
    try:
2689
      utils.WriteFile(fpath, data=fdata)
2690
    except EnvironmentError, err:
2691
      logging.exception("Can't update bdev cache for %s", dev_path)
2692

    
2693
  @classmethod
2694
  def RemoveCache(cls, dev_path):
2695
    """Remove data for a dev_path.
2696

2697
    This is just a wrapper over L{utils.RemoveFile} with a converted
2698
    path name and logging.
2699

2700
    @type dev_path: str
2701
    @param dev_path: the pathname of the device
2702

2703
    @rtype: None
2704

2705
    """
2706
    if dev_path is None:
2707
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
2708
      return
2709
    fpath = cls._ConvertPath(dev_path)
2710
    try:
2711
      utils.RemoveFile(fpath)
2712
    except EnvironmentError, err:
2713
      logging.exception("Can't update bdev cache for %s", dev_path)