Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 3583908a

History | View | Annotate | Download (80.2 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 "log" not in kwargs or kwargs["log"]: # if we should log this error
72
    if "exc" in kwargs and kwargs["exc"]:
73
      logging.exception(msg)
74
    else:
75
      logging.error(msg)
76
  raise RPCFail(msg)
77

    
78

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

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

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

    
88

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

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

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

    
101

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

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

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

    
121

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

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

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

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

    
147

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

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

154
  """
155
  _CleanDirectory(constants.QUEUE_DIR, exclude=[constants.JOB_QUEUE_LOCK_FILE])
156
  _CleanDirectory(constants.JOB_QUEUE_ARCHIVE_DIR)
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: master_netdev, master_ip, master_name
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: %s", err, exc=True)
177
  return (master_netdev, master_ip, master_node)
178

    
179

    
180
def StartMaster(start_daemons, no_voting):
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: whether to also start the master
189
      daemons (ganeti-masterd and ganeti-rapi)
190
  @type no_voting: boolean
191
  @param no_voting: whether to start ganeti-masterd without a node vote
192
      (if start_daemons is True), but still non-interactively
193
  @rtype: None
194

195
  """
196
  # GetMasterInfo will raise an exception if not able to return data
197
  master_netdev, master_ip, _ = GetMasterInfo()
198

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

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

    
221
  # and now start the master and rapi daemons
222
  if start_daemons:
223
    daemons_params = {
224
        'ganeti-masterd': [],
225
        'ganeti-rapi': [],
226
        }
227
    if no_voting:
228
      daemons_params['ganeti-masterd'].append('--no-voting')
229
      daemons_params['ganeti-masterd'].append('--yes-do-it')
230
    for daemon in daemons_params:
231
      cmd = [daemon]
232
      cmd.extend(daemons_params[daemon])
233
      result = utils.RunCmd(cmd)
234
      if result.failed:
235
        msg = "Can't start daemon %s: %s" % (daemon, result.output)
236
        logging.error(msg)
237
        err_msgs.append(msg)
238

    
239
  if err_msgs:
240
    _Fail("; ".join(err_msgs))
241

    
242

    
243
def StopMaster(stop_daemons):
244
  """Deactivate this node as master.
245

246
  The function will always try to deactivate the IP address of the
247
  master. It will also stop the master daemons depending on the
248
  stop_daemons parameter.
249

250
  @type stop_daemons: boolean
251
  @param stop_daemons: whether to also stop the master daemons
252
      (ganeti-masterd and ganeti-rapi)
253
  @rtype: None
254

255
  """
256
  # TODO: log and report back to the caller the error failures; we
257
  # need to decide in which case we fail the RPC for this
258

    
259
  # GetMasterInfo will raise an exception if not able to return data
260
  master_netdev, master_ip, _ = GetMasterInfo()
261

    
262
  result = utils.RunCmd(["ip", "address", "del", "%s/32" % master_ip,
263
                         "dev", master_netdev])
264
  if result.failed:
265
    logging.error("Can't remove the master IP, error: %s", result.output)
266
    # but otherwise ignore the failure
267

    
268
  if stop_daemons:
269
    # stop/kill the rapi and the master daemon
270
    for daemon in constants.RAPI_PID, constants.MASTERD_PID:
271
      utils.KillProcess(utils.ReadPidFile(utils.DaemonPidFileName(daemon)))
272

    
273

    
274
def AddNode(dsa, dsapub, rsa, rsapub, sshkey, sshpub):
275
  """Joins this node to the cluster.
276

277
  This does the following:
278
      - updates the hostkeys of the machine (rsa and dsa)
279
      - adds the ssh private key to the user
280
      - adds the ssh public key to the users' authorized_keys file
281

282
  @type dsa: str
283
  @param dsa: the DSA private key to write
284
  @type dsapub: str
285
  @param dsapub: the DSA public key to write
286
  @type rsa: str
287
  @param rsa: the RSA private key to write
288
  @type rsapub: str
289
  @param rsapub: the RSA public key to write
290
  @type sshkey: str
291
  @param sshkey: the SSH private key to write
292
  @type sshpub: str
293
  @param sshpub: the SSH public key to write
294
  @rtype: boolean
295
  @return: the success of the operation
296

297
  """
298
  sshd_keys =  [(constants.SSH_HOST_RSA_PRIV, rsa, 0600),
299
                (constants.SSH_HOST_RSA_PUB, rsapub, 0644),
300
                (constants.SSH_HOST_DSA_PRIV, dsa, 0600),
301
                (constants.SSH_HOST_DSA_PUB, dsapub, 0644)]
302
  for name, content, mode in sshd_keys:
303
    utils.WriteFile(name, data=content, mode=mode)
304

    
305
  try:
306
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS,
307
                                                    mkdir=True)
308
  except errors.OpExecError, err:
309
    _Fail("Error while processing user ssh files: %s", err, exc=True)
310

    
311
  for name, content in [(priv_key, sshkey), (pub_key, sshpub)]:
312
    utils.WriteFile(name, data=content, mode=0600)
313

    
314
  utils.AddAuthorizedKey(auth_keys, sshpub)
315

    
316
  utils.RunCmd([constants.SSH_INITD_SCRIPT, "restart"])
317

    
318

    
319
def LeaveCluster():
320
  """Cleans up and remove the current node.
321

322
  This function cleans up and prepares the current node to be removed
323
  from the cluster.
324

325
  If processing is successful, then it raises an
326
  L{errors.QuitGanetiException} which is used as a special case to
327
  shutdown the node daemon.
328

329
  """
330
  _CleanDirectory(constants.DATA_DIR)
331
  JobQueuePurge()
332

    
333
  try:
334
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
335

    
336
    f = open(pub_key, 'r')
337
    try:
338
      utils.RemoveAuthorizedKey(auth_keys, f.read(8192))
339
    finally:
340
      f.close()
341

    
342
    utils.RemoveFile(priv_key)
343
    utils.RemoveFile(pub_key)
344
  except errors.OpExecError:
345
    logging.exception("Error while processing ssh files")
346

    
347
  # Raise a custom exception (handled in ganeti-noded)
348
  raise errors.QuitGanetiException(True, 'Shutdown scheduled')
349

    
350

    
351
def GetNodeInfo(vgname, hypervisor_type):
352
  """Gives back a hash with different information about the node.
353

354
  @type vgname: C{string}
355
  @param vgname: the name of the volume group to ask for disk space information
356
  @type hypervisor_type: C{str}
357
  @param hypervisor_type: the name of the hypervisor to ask for
358
      memory information
359
  @rtype: C{dict}
360
  @return: dictionary with the following keys:
361
      - vg_size is the size of the configured volume group in MiB
362
      - vg_free is the free size of the volume group in MiB
363
      - memory_dom0 is the memory allocated for domain0 in MiB
364
      - memory_free is the currently available (free) ram in MiB
365
      - memory_total is the total number of ram in MiB
366

367
  """
368
  outputarray = {}
369
  vginfo = _GetVGInfo(vgname)
370
  outputarray['vg_size'] = vginfo['vg_size']
371
  outputarray['vg_free'] = vginfo['vg_free']
372

    
373
  hyper = hypervisor.GetHypervisor(hypervisor_type)
374
  hyp_info = hyper.GetNodeInfo()
375
  if hyp_info is not None:
376
    outputarray.update(hyp_info)
377

    
378
  f = open("/proc/sys/kernel/random/boot_id", 'r')
379
  try:
380
    outputarray["bootid"] = f.read(128).rstrip("\n")
381
  finally:
382
    f.close()
383

    
384
  return outputarray
385

    
386

    
387
def VerifyNode(what, cluster_name):
388
  """Verify the status of the local node.
389

390
  Based on the input L{what} parameter, various checks are done on the
391
  local node.
392

393
  If the I{filelist} key is present, this list of
394
  files is checksummed and the file/checksum pairs are returned.
395

396
  If the I{nodelist} key is present, we check that we have
397
  connectivity via ssh with the target nodes (and check the hostname
398
  report).
399

400
  If the I{node-net-test} key is present, we check that we have
401
  connectivity to the given nodes via both primary IP and, if
402
  applicable, secondary IPs.
403

404
  @type what: C{dict}
405
  @param what: a dictionary of things to check:
406
      - filelist: list of files for which to compute checksums
407
      - nodelist: list of nodes we should check ssh communication with
408
      - node-net-test: list of nodes we should check node daemon port
409
        connectivity with
410
      - hypervisor: list with hypervisors to run the verify for
411
  @rtype: dict
412
  @return: a dictionary with the same keys as the input dict, and
413
      values representing the result of the checks
414

415
  """
416
  result = {}
417

    
418
  if constants.NV_HYPERVISOR in what:
419
    result[constants.NV_HYPERVISOR] = tmp = {}
420
    for hv_name in what[constants.NV_HYPERVISOR]:
421
      tmp[hv_name] = hypervisor.GetHypervisor(hv_name).Verify()
422

    
423
  if constants.NV_FILELIST in what:
424
    result[constants.NV_FILELIST] = utils.FingerprintFiles(
425
      what[constants.NV_FILELIST])
426

    
427
  if constants.NV_NODELIST in what:
428
    result[constants.NV_NODELIST] = tmp = {}
429
    random.shuffle(what[constants.NV_NODELIST])
430
    for node in what[constants.NV_NODELIST]:
431
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
432
      if not success:
433
        tmp[node] = message
434

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

    
460
  if constants.NV_LVLIST in what:
461
    result[constants.NV_LVLIST] = GetVolumeList(what[constants.NV_LVLIST])
462

    
463
  if constants.NV_INSTANCELIST in what:
464
    result[constants.NV_INSTANCELIST] = GetInstanceList(
465
      what[constants.NV_INSTANCELIST])
466

    
467
  if constants.NV_VGLIST in what:
468
    result[constants.NV_VGLIST] = utils.ListVolumeGroups()
469

    
470
  if constants.NV_VERSION in what:
471
    result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
472
                                    constants.RELEASE_VERSION)
473

    
474
  if constants.NV_HVINFO in what:
475
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
476
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
477

    
478
  if constants.NV_DRBDLIST in what:
479
    try:
480
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
481
    except errors.BlockDeviceError, err:
482
      logging.warning("Can't get used minors list", exc_info=True)
483
      used_minors = str(err)
484
    result[constants.NV_DRBDLIST] = used_minors
485

    
486
  return result
487

    
488

    
489
def GetVolumeList(vg_name):
490
  """Compute list of logical volumes and their size.
491

492
  @type vg_name: str
493
  @param vg_name: the volume group whose LVs we should list
494
  @rtype: dict
495
  @return:
496
      dictionary of all partions (key) with value being a tuple of
497
      their size (in MiB), inactive and online status::
498

499
        {'test1': ('20.06', True, True)}
500

501
      in case of errors, a string is returned with the error
502
      details.
503

504
  """
505
  lvs = {}
506
  sep = '|'
507
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
508
                         "--separator=%s" % sep,
509
                         "-olv_name,lv_size,lv_attr", vg_name])
510
  if result.failed:
511
    _Fail("Failed to list logical volumes, lvs output: %s", result.output)
512

    
513
  valid_line_re = re.compile("^ *([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
514
  for line in result.stdout.splitlines():
515
    line = line.strip()
516
    match = valid_line_re.match(line)
517
    if not match:
518
      logging.error("Invalid line returned from lvs output: '%s'", line)
519
      continue
520
    name, size, attr = match.groups()
521
    inactive = attr[4] == '-'
522
    online = attr[5] == 'o'
523
    lvs[name] = (size, inactive, online)
524

    
525
  return lvs
526

    
527

    
528
def ListVolumeGroups():
529
  """List the volume groups and their size.
530

531
  @rtype: dict
532
  @return: dictionary with keys volume name and values the
533
      size of the volume
534

535
  """
536
  return utils.ListVolumeGroups()
537

    
538

    
539
def NodeVolumes():
540
  """List all volumes on this node.
541

542
  @rtype: list
543
  @return:
544
    A list of dictionaries, each having four keys:
545
      - name: the logical volume name,
546
      - size: the size of the logical volume
547
      - dev: the physical device on which the LV lives
548
      - vg: the volume group to which it belongs
549

550
    In case of errors, we return an empty list and log the
551
    error.
552

553
    Note that since a logical volume can live on multiple physical
554
    volumes, the resulting list might include a logical volume
555
    multiple times.
556

557
  """
558
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
559
                         "--separator=|",
560
                         "--options=lv_name,lv_size,devices,vg_name"])
561
  if result.failed:
562
    _Fail("Failed to list logical volumes, lvs output: %s",
563
          result.output)
564

    
565
  def parse_dev(dev):
566
    if '(' in dev:
567
      return dev.split('(')[0]
568
    else:
569
      return dev
570

    
571
  def map_line(line):
572
    return {
573
      'name': line[0].strip(),
574
      'size': line[1].strip(),
575
      'dev': parse_dev(line[2].strip()),
576
      'vg': line[3].strip(),
577
    }
578

    
579
  return [map_line(line.split('|')) for line in result.stdout.splitlines()
580
          if line.count('|') >= 3]
581

    
582

    
583
def BridgesExist(bridges_list):
584
  """Check if a list of bridges exist on the current node.
585

586
  @rtype: boolean
587
  @return: C{True} if all of them exist, C{False} otherwise
588

589
  """
590
  missing = []
591
  for bridge in bridges_list:
592
    if not utils.BridgeExists(bridge):
593
      missing.append(bridge)
594

    
595
  if missing:
596
    _Fail("Missing bridges %s", ", ".join(missing))
597

    
598

    
599
def GetInstanceList(hypervisor_list):
600
  """Provides a list of instances.
601

602
  @type hypervisor_list: list
603
  @param hypervisor_list: the list of hypervisors to query information
604

605
  @rtype: list
606
  @return: a list of all running instances on the current node
607
    - instance1.example.com
608
    - instance2.example.com
609

610
  """
611
  results = []
612
  for hname in hypervisor_list:
613
    try:
614
      names = hypervisor.GetHypervisor(hname).ListInstances()
615
      results.extend(names)
616
    except errors.HypervisorError, err:
617
      _Fail("Error enumerating instances (hypervisor %s): %s",
618
            hname, err, exc=True)
619

    
620
  return results
621

    
622

    
623
def GetInstanceInfo(instance, hname):
624
  """Gives back the information about an instance as a dictionary.
625

626
  @type instance: string
627
  @param instance: the instance name
628
  @type hname: string
629
  @param hname: the hypervisor type of the instance
630

631
  @rtype: dict
632
  @return: dictionary with the following keys:
633
      - memory: memory size of instance (int)
634
      - state: xen state of instance (string)
635
      - time: cpu time of instance (float)
636

637
  """
638
  output = {}
639

    
640
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
641
  if iinfo is not None:
642
    output['memory'] = iinfo[2]
643
    output['state'] = iinfo[4]
644
    output['time'] = iinfo[5]
645

    
646
  return output
647

    
648

    
649
def GetInstanceMigratable(instance):
650
  """Gives whether an instance can be migrated.
651

652
  @type instance: L{objects.Instance}
653
  @param instance: object representing the instance to be checked.
654

655
  @rtype: tuple
656
  @return: tuple of (result, description) where:
657
      - result: whether the instance can be migrated or not
658
      - description: a description of the issue, if relevant
659

660
  """
661
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
662
  iname = instance.name
663
  if iname not in hyper.ListInstances():
664
    _Fail("Instance %s is not running", iname)
665

    
666
  for idx in range(len(instance.disks)):
667
    link_name = _GetBlockDevSymlinkPath(iname, idx)
668
    if not os.path.islink(link_name):
669
      _Fail("Instance %s was not restarted since ganeti 1.2.5", iname)
670

    
671

    
672
def GetAllInstancesInfo(hypervisor_list):
673
  """Gather data about all instances.
674

675
  This is the equivalent of L{GetInstanceInfo}, except that it
676
  computes data for all instances at once, thus being faster if one
677
  needs data about more than one instance.
678

679
  @type hypervisor_list: list
680
  @param hypervisor_list: list of hypervisors to query for instance data
681

682
  @rtype: dict
683
  @return: dictionary of instance: data, with data having the following keys:
684
      - memory: memory size of instance (int)
685
      - state: xen state of instance (string)
686
      - time: cpu time of instance (float)
687
      - vcpus: the number of vcpus
688

689
  """
690
  output = {}
691

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

    
712
  return output
713

    
714

    
715
def InstanceOsAdd(instance, reinstall):
716
  """Add an OS to an instance.
717

718
  @type instance: L{objects.Instance}
719
  @param instance: Instance whose OS is to be installed
720
  @type reinstall: boolean
721
  @param reinstall: whether this is an instance reinstall
722
  @rtype: None
723

724
  """
725
  inst_os = OSFromDisk(instance.os)
726

    
727
  create_env = OSEnvironment(instance, inst_os)
728
  if reinstall:
729
    create_env['INSTANCE_REINSTALL'] = "1"
730

    
731
  logfile = "%s/add-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
732
                                     instance.name, int(time.time()))
733

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

    
745

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

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

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

    
759
  rename_env = OSEnvironment(instance, inst_os)
760
  rename_env['OLD_INSTANCE_NAME'] = old_name
761

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

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

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

    
777

    
778
def _GetVGInfo(vg_name):
779
  """Get information about the volume group.
780

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

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

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

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

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

    
817

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

    
822

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

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

829

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

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

    
848
  return link_name
849

    
850

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

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

    
863

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

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

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

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

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

    
891
  return block_devices
892

    
893

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

897
  @type instance: L{objects.Instance}
898
  @param instance: the instance object
899
  @rtype: None
900

901
  """
902
  running_instances = GetInstanceList([instance.hypervisor])
903

    
904
  if instance.name in running_instances:
905
    logging.info("Instance %s already running, not starting", instance.name)
906
    return
907

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

    
918

    
919
def InstanceShutdown(instance):
920
  """Shut an instance down.
921

922
  @note: this functions uses polling with a hardcoded timeout.
923

924
  @type instance: L{objects.Instance}
925
  @param instance: the instance object
926
  @rtype: None
927

928
  """
929
  hv_name = instance.hypervisor
930
  running_instances = GetInstanceList([hv_name])
931
  iname = instance.name
932

    
933
  if iname not in running_instances:
934
    logging.info("Instance %s not running, doing nothing", iname)
935
    return
936

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

    
943
  # test every 10secs for 2min
944

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

    
954
    try:
955
      hyper.StopInstance(instance, force=True)
956
    except errors.HypervisorError, err:
957
      _Fail("Failed to force stop instance %s: %s", iname, err)
958

    
959
    time.sleep(1)
960
    if instance.name in GetInstanceList([hv_name]):
961
      _Fail("Could not shutdown instance %s even by destroy", iname)
962

    
963
  _RemoveBlockDevLinks(iname, instance.disks)
964

    
965

    
966
def InstanceReboot(instance, reboot_type):
967
  """Reboot an instance.
968

969
  @type instance: L{objects.Instance}
970
  @param instance: the instance object to reboot
971
  @type reboot_type: str
972
  @param reboot_type: the type of reboot, one the following
973
    constants:
974
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
975
        instance OS, do not recreate the VM
976
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
977
        restart the VM (at the hypervisor level)
978
      - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
979
        not accepted here, since that mode is handled differently, in
980
        cmdlib, and translates into full stop and start of the
981
        instance (instead of a call_instance_reboot RPC)
982
  @rtype: None
983

984
  """
985
  running_instances = GetInstanceList([instance.hypervisor])
986

    
987
  if instance.name not in running_instances:
988
    _Fail("Cannot reboot instance %s that is not running", instance.name)
989

    
990
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
991
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
992
    try:
993
      hyper.RebootInstance(instance)
994
    except errors.HypervisorError, err:
995
      _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
996
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
997
    try:
998
      InstanceShutdown(instance)
999
      return StartInstance(instance)
1000
    except errors.HypervisorError, err:
1001
      _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1002
  else:
1003
    _Fail("Invalid reboot_type received: %s", reboot_type)
1004

    
1005

    
1006
def MigrationInfo(instance):
1007
  """Gather information about an instance to be migrated.
1008

1009
  @type instance: L{objects.Instance}
1010
  @param instance: the instance definition
1011

1012
  """
1013
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1014
  try:
1015
    info = hyper.MigrationInfo(instance)
1016
  except errors.HypervisorError, err:
1017
    _Fail("Failed to fetch migration information: %s", err, exc=True)
1018
  return info
1019

    
1020

    
1021
def AcceptInstance(instance, info, target):
1022
  """Prepare the node to accept an instance.
1023

1024
  @type instance: L{objects.Instance}
1025
  @param instance: the instance definition
1026
  @type info: string/data (opaque)
1027
  @param info: migration information, from the source node
1028
  @type target: string
1029
  @param target: target host (usually ip), on this node
1030

1031
  """
1032
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1033
  try:
1034
    hyper.AcceptInstance(instance, info, target)
1035
  except errors.HypervisorError, err:
1036
    _Fail("Failed to accept instance: %s", err, exc=True)
1037

    
1038

    
1039
def FinalizeMigration(instance, info, success):
1040
  """Finalize any preparation to accept an instance.
1041

1042
  @type instance: L{objects.Instance}
1043
  @param instance: the instance definition
1044
  @type info: string/data (opaque)
1045
  @param info: migration information, from the source node
1046
  @type success: boolean
1047
  @param success: whether the migration was a success or a failure
1048

1049
  """
1050
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1051
  try:
1052
    hyper.FinalizeMigration(instance, info, success)
1053
  except errors.HypervisorError, err:
1054
    _Fail("Failed to finalize migration: %s", err, exc=True)
1055

    
1056

    
1057
def MigrateInstance(instance, target, live):
1058
  """Migrates an instance to another node.
1059

1060
  @type instance: L{objects.Instance}
1061
  @param instance: the instance definition
1062
  @type target: string
1063
  @param target: the target node name
1064
  @type live: boolean
1065
  @param live: whether the migration should be done live or not (the
1066
      interpretation of this parameter is left to the hypervisor)
1067
  @rtype: tuple
1068
  @return: a tuple of (success, msg) where:
1069
      - succes is a boolean denoting the success/failure of the operation
1070
      - msg is a string with details in case of failure
1071

1072
  """
1073
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1074

    
1075
  try:
1076
    hyper.MigrateInstance(instance.name, target, live)
1077
  except errors.HypervisorError, err:
1078
    _Fail("Failed to migrate instance: %s", err, exc=True)
1079

    
1080

    
1081
def BlockdevCreate(disk, size, owner, on_primary, info):
1082
  """Creates a block device for an instance.
1083

1084
  @type disk: L{objects.Disk}
1085
  @param disk: the object describing the disk we should create
1086
  @type size: int
1087
  @param size: the size of the physical underlying device, in MiB
1088
  @type owner: str
1089
  @param owner: the name of the instance for which disk is created,
1090
      used for device cache data
1091
  @type on_primary: boolean
1092
  @param on_primary:  indicates if it is the primary node or not
1093
  @type info: string
1094
  @param info: string that will be sent to the physical device
1095
      creation, used for example to set (LVM) tags on LVs
1096

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

1101
  """
1102
  clist = []
1103
  if disk.children:
1104
    for child in disk.children:
1105
      try:
1106
        crdev = _RecursiveAssembleBD(child, owner, on_primary)
1107
      except errors.BlockDeviceError, err:
1108
        _Fail("Can't assemble device %s: %s", child, err)
1109
      if on_primary or disk.AssembleOnSecondary():
1110
        # we need the children open in case the device itself has to
1111
        # be assembled
1112
        try:
1113
          crdev.Open()
1114
        except errors.BlockDeviceError, err:
1115
          _Fail("Can't make child '%s' read-write: %s", child, err)
1116
      clist.append(crdev)
1117

    
1118
  try:
1119
    device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
1120
  except errors.BlockDeviceError, err:
1121
    _Fail("Can't create block device: %s", err)
1122

    
1123
  if on_primary or disk.AssembleOnSecondary():
1124
    try:
1125
      device.Assemble()
1126
    except errors.BlockDeviceError, err:
1127
      _Fail("Can't assemble device after creation, unusual event: %s", err)
1128
    device.SetSyncSpeed(constants.SYNC_SPEED)
1129
    if on_primary or disk.OpenOnSecondary():
1130
      try:
1131
        device.Open(force=True)
1132
      except errors.BlockDeviceError, err:
1133
        _Fail("Can't make device r/w after creation, unusual event: %s", err)
1134
    DevCacheManager.UpdateCache(device.dev_path, owner,
1135
                                on_primary, disk.iv_name)
1136

    
1137
  device.SetInfo(info)
1138

    
1139
  return device.unique_id
1140

    
1141

    
1142
def BlockdevRemove(disk):
1143
  """Remove a block device.
1144

1145
  @note: This is intended to be called recursively.
1146

1147
  @type disk: L{objects.Disk}
1148
  @param disk: the disk object we should remove
1149
  @rtype: boolean
1150
  @return: the success of the operation
1151

1152
  """
1153
  msgs = []
1154
  try:
1155
    rdev = _RecursiveFindBD(disk)
1156
  except errors.BlockDeviceError, err:
1157
    # probably can't attach
1158
    logging.info("Can't attach to device %s in remove", disk)
1159
    rdev = None
1160
  if rdev is not None:
1161
    r_path = rdev.dev_path
1162
    try:
1163
      rdev.Remove()
1164
    except errors.BlockDeviceError, err:
1165
      msgs.append(str(err))
1166
    if not msgs:
1167
      DevCacheManager.RemoveCache(r_path)
1168

    
1169
  if disk.children:
1170
    for child in disk.children:
1171
      try:
1172
        BlockdevRemove(child)
1173
      except RPCFail, err:
1174
        msgs.append(str(err))
1175

    
1176
  if msgs:
1177
    _Fail("; ".join(msgs))
1178

    
1179

    
1180
def _RecursiveAssembleBD(disk, owner, as_primary):
1181
  """Activate a block device for an instance.
1182

1183
  This is run on the primary and secondary nodes for an instance.
1184

1185
  @note: this function is called recursively.
1186

1187
  @type disk: L{objects.Disk}
1188
  @param disk: the disk we try to assemble
1189
  @type owner: str
1190
  @param owner: the name of the instance which owns the disk
1191
  @type as_primary: boolean
1192
  @param as_primary: if we should make the block device
1193
      read/write
1194

1195
  @return: the assembled device or None (in case no device
1196
      was assembled)
1197
  @raise errors.BlockDeviceError: in case there is an error
1198
      during the activation of the children or the device
1199
      itself
1200

1201
  """
1202
  children = []
1203
  if disk.children:
1204
    mcn = disk.ChildrenNeeded()
1205
    if mcn == -1:
1206
      mcn = 0 # max number of Nones allowed
1207
    else:
1208
      mcn = len(disk.children) - mcn # max number of Nones
1209
    for chld_disk in disk.children:
1210
      try:
1211
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1212
      except errors.BlockDeviceError, err:
1213
        if children.count(None) >= mcn:
1214
          raise
1215
        cdev = None
1216
        logging.error("Error in child activation (but continuing): %s",
1217
                      str(err))
1218
      children.append(cdev)
1219

    
1220
  if as_primary or disk.AssembleOnSecondary():
1221
    r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
1222
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1223
    result = r_dev
1224
    if as_primary or disk.OpenOnSecondary():
1225
      r_dev.Open()
1226
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1227
                                as_primary, disk.iv_name)
1228

    
1229
  else:
1230
    result = True
1231
  return result
1232

    
1233

    
1234
def BlockdevAssemble(disk, owner, as_primary):
1235
  """Activate a block device for an instance.
1236

1237
  This is a wrapper over _RecursiveAssembleBD.
1238

1239
  @rtype: str or boolean
1240
  @return: a C{/dev/...} path for primary nodes, and
1241
      C{True} for secondary nodes
1242

1243
  """
1244
  try:
1245
    result = _RecursiveAssembleBD(disk, owner, as_primary)
1246
    if isinstance(result, bdev.BlockDev):
1247
      result = result.dev_path
1248
  except errors.BlockDeviceError, err:
1249
    _Fail("Error while assembling disk: %s", err, exc=True)
1250

    
1251
  return result
1252

    
1253

    
1254
def BlockdevShutdown(disk):
1255
  """Shut down a block device.
1256

1257
  First, if the device is assembled (Attach() is successful), then
1258
  the device is shutdown. Then the children of the device are
1259
  shutdown.
1260

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

1265
  @type disk: L{objects.Disk}
1266
  @param disk: the description of the disk we should
1267
      shutdown
1268
  @rtype: None
1269

1270
  """
1271
  msgs = []
1272
  r_dev = _RecursiveFindBD(disk)
1273
  if r_dev is not None:
1274
    r_path = r_dev.dev_path
1275
    try:
1276
      r_dev.Shutdown()
1277
      DevCacheManager.RemoveCache(r_path)
1278
    except errors.BlockDeviceError, err:
1279
      msgs.append(str(err))
1280

    
1281
  if disk.children:
1282
    for child in disk.children:
1283
      try:
1284
        BlockdevShutdown(child)
1285
      except RPCFail, err:
1286
        msgs.append(str(err))
1287

    
1288
  if msgs:
1289
    _Fail("; ".join(msgs))
1290

    
1291

    
1292
def BlockdevAddchildren(parent_cdev, new_cdevs):
1293
  """Extend a mirrored block device.
1294

1295
  @type parent_cdev: L{objects.Disk}
1296
  @param parent_cdev: the disk to which we should add children
1297
  @type new_cdevs: list of L{objects.Disk}
1298
  @param new_cdevs: the list of children which we should add
1299
  @rtype: None
1300

1301
  """
1302
  parent_bdev = _RecursiveFindBD(parent_cdev)
1303
  if parent_bdev is None:
1304
    _Fail("Can't find parent device '%s' in add children", parent_cdev)
1305
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1306
  if new_bdevs.count(None) > 0:
1307
    _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1308
  parent_bdev.AddChildren(new_bdevs)
1309

    
1310

    
1311
def BlockdevRemovechildren(parent_cdev, new_cdevs):
1312
  """Shrink a mirrored block device.
1313

1314
  @type parent_cdev: L{objects.Disk}
1315
  @param parent_cdev: the disk from which we should remove children
1316
  @type new_cdevs: list of L{objects.Disk}
1317
  @param new_cdevs: the list of children which we should remove
1318
  @rtype: None
1319

1320
  """
1321
  parent_bdev = _RecursiveFindBD(parent_cdev)
1322
  if parent_bdev is None:
1323
    _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1324
  devs = []
1325
  for disk in new_cdevs:
1326
    rpath = disk.StaticDevPath()
1327
    if rpath is None:
1328
      bd = _RecursiveFindBD(disk)
1329
      if bd is None:
1330
        _Fail("Can't find device %s while removing children", disk)
1331
      else:
1332
        devs.append(bd.dev_path)
1333
    else:
1334
      devs.append(rpath)
1335
  parent_bdev.RemoveChildren(devs)
1336

    
1337

    
1338
def BlockdevGetmirrorstatus(disks):
1339
  """Get the mirroring status of a list of devices.
1340

1341
  @type disks: list of L{objects.Disk}
1342
  @param disks: the list of disks which we should query
1343
  @rtype: disk
1344
  @return:
1345
      a list of (mirror_done, estimated_time) tuples, which
1346
      are the result of L{bdev.BlockDev.CombinedSyncStatus}
1347
  @raise errors.BlockDeviceError: if any of the disks cannot be
1348
      found
1349

1350
  """
1351
  stats = []
1352
  for dsk in disks:
1353
    rbd = _RecursiveFindBD(dsk)
1354
    if rbd is None:
1355
      _Fail("Can't find device %s", dsk)
1356
    stats.append(rbd.CombinedSyncStatus())
1357
  return stats
1358

    
1359

    
1360
def _RecursiveFindBD(disk):
1361
  """Check if a device is activated.
1362

1363
  If so, return information about the real device.
1364

1365
  @type disk: L{objects.Disk}
1366
  @param disk: the disk object we need to find
1367

1368
  @return: None if the device can't be found,
1369
      otherwise the device instance
1370

1371
  """
1372
  children = []
1373
  if disk.children:
1374
    for chdisk in disk.children:
1375
      children.append(_RecursiveFindBD(chdisk))
1376

    
1377
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1378

    
1379

    
1380
def BlockdevFind(disk):
1381
  """Check if a device is activated.
1382

1383
  If it is, return information about the real device.
1384

1385
  @type disk: L{objects.Disk}
1386
  @param disk: the disk to find
1387
  @rtype: None or tuple
1388
  @return: None if the disk cannot be found, otherwise a
1389
      tuple (device_path, major, minor, sync_percent,
1390
      estimated_time, is_degraded)
1391

1392
  """
1393
  try:
1394
    rbd = _RecursiveFindBD(disk)
1395
  except errors.BlockDeviceError, err:
1396
    _Fail("Failed to find device: %s", err, exc=True)
1397
  if rbd is None:
1398
    return None
1399
  return (rbd.dev_path, rbd.major, rbd.minor) + rbd.GetSyncStatus()
1400

    
1401

    
1402
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1403
  """Write a file to the filesystem.
1404

1405
  This allows the master to overwrite(!) a file. It will only perform
1406
  the operation if the file belongs to a list of configuration files.
1407

1408
  @type file_name: str
1409
  @param file_name: the target file name
1410
  @type data: str
1411
  @param data: the new contents of the file
1412
  @type mode: int
1413
  @param mode: the mode to give the file (can be None)
1414
  @type uid: int
1415
  @param uid: the owner of the file (can be -1 for default)
1416
  @type gid: int
1417
  @param gid: the group of the file (can be -1 for default)
1418
  @type atime: float
1419
  @param atime: the atime to set on the file (can be None)
1420
  @type mtime: float
1421
  @param mtime: the mtime to set on the file (can be None)
1422
  @rtype: None
1423

1424
  """
1425
  if not os.path.isabs(file_name):
1426
    _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
1427

    
1428
  allowed_files = set([
1429
    constants.CLUSTER_CONF_FILE,
1430
    constants.ETC_HOSTS,
1431
    constants.SSH_KNOWN_HOSTS_FILE,
1432
    constants.VNC_PASSWORD_FILE,
1433
    constants.RAPI_CERT_FILE,
1434
    constants.RAPI_USERS_FILE,
1435
    ])
1436

    
1437
  for hv_name in constants.HYPER_TYPES:
1438
    hv_class = hypervisor.GetHypervisor(hv_name)
1439
    allowed_files.update(hv_class.GetAncillaryFiles())
1440

    
1441
  if file_name not in allowed_files:
1442
    _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
1443
          file_name)
1444

    
1445
  raw_data = _Decompress(data)
1446

    
1447
  utils.WriteFile(file_name, data=raw_data, mode=mode, uid=uid, gid=gid,
1448
                  atime=atime, mtime=mtime)
1449

    
1450

    
1451
def WriteSsconfFiles(values):
1452
  """Update all ssconf files.
1453

1454
  Wrapper around the SimpleStore.WriteFiles.
1455

1456
  """
1457
  ssconf.SimpleStore().WriteFiles(values)
1458

    
1459

    
1460
def _ErrnoOrStr(err):
1461
  """Format an EnvironmentError exception.
1462

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

1467
  @type err: L{EnvironmentError}
1468
  @param err: the exception to format
1469

1470
  """
1471
  if hasattr(err, 'errno'):
1472
    detail = errno.errorcode[err.errno]
1473
  else:
1474
    detail = str(err)
1475
  return detail
1476

    
1477

    
1478
def _OSOndiskAPIVersion(name, os_dir):
1479
  """Compute and return the API version of a given OS.
1480

1481
  This function will try to read the API version of the OS given by
1482
  the 'name' parameter and residing in the 'os_dir' directory.
1483

1484
  @type name: str
1485
  @param name: the OS name we should look for
1486
  @type os_dir: str
1487
  @param os_dir: the directory inwhich we should look for the OS
1488
  @rtype: tuple
1489
  @return: tuple (status, data) with status denoting the validity and
1490
      data holding either the vaid versions or an error message
1491

1492
  """
1493
  api_file = os.path.sep.join([os_dir, "ganeti_api_version"])
1494

    
1495
  try:
1496
    st = os.stat(api_file)
1497
  except EnvironmentError, err:
1498
    return False, ("Required file 'ganeti_api_version' file not"
1499
                   " found under path %s: %s" % (os_dir, _ErrnoOrStr(err)))
1500

    
1501
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1502
    return False, ("File 'ganeti_api_version' file at %s is not"
1503
                   " a regular file" % os_dir)
1504

    
1505
  try:
1506
    api_versions = utils.ReadFile(api_file).splitlines()
1507
  except EnvironmentError, err:
1508
    return False, ("Error while reading the API version file at %s: %s" %
1509
                   (api_file, _ErrnoOrStr(err)))
1510

    
1511
  try:
1512
    api_versions = [int(version.strip()) for version in api_versions]
1513
  except (TypeError, ValueError), err:
1514
    return False, ("API version(s) can't be converted to integer: %s" %
1515
                   str(err))
1516

    
1517
  return True, api_versions
1518

    
1519

    
1520
def DiagnoseOS(top_dirs=None):
1521
  """Compute the validity for all OSes.
1522

1523
  @type top_dirs: list
1524
  @param top_dirs: the list of directories in which to
1525
      search (if not given defaults to
1526
      L{constants.OS_SEARCH_PATH})
1527
  @rtype: list of L{objects.OS}
1528
  @return: a list of tuples (name, path, status, diagnose)
1529
      for all (potential) OSes under all search paths, where:
1530
          - name is the (potential) OS name
1531
          - path is the full path to the OS
1532
          - status True/False is the validity of the OS
1533
          - diagnose is the error message for an invalid OS, otherwise empty
1534

1535
  """
1536
  if top_dirs is None:
1537
    top_dirs = constants.OS_SEARCH_PATH
1538

    
1539
  result = []
1540
  for dir_name in top_dirs:
1541
    if os.path.isdir(dir_name):
1542
      try:
1543
        f_names = utils.ListVisibleFiles(dir_name)
1544
      except EnvironmentError, err:
1545
        logging.exception("Can't list the OS directory %s: %s", dir_name, err)
1546
        break
1547
      for name in f_names:
1548
        os_path = os.path.sep.join([dir_name, name])
1549
        status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
1550
        if status:
1551
          diagnose = ""
1552
        else:
1553
          diagnose = os_inst
1554
        result.append((name, os_path, status, diagnose))
1555

    
1556
  return result
1557

    
1558

    
1559
def _TryOSFromDisk(name, base_dir=None):
1560
  """Create an OS instance from disk.
1561

1562
  This function will return an OS instance if the given name is a
1563
  valid OS name.
1564

1565
  @type base_dir: string
1566
  @keyword base_dir: Base directory containing OS installations.
1567
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1568
  @rtype: tuple
1569
  @return: success and either the OS instance if we find a valid one,
1570
      or error message
1571

1572
  """
1573
  if base_dir is None:
1574
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1575
    if os_dir is None:
1576
      return False, "Directory for OS %s not found in search path" % name
1577
  else:
1578
    os_dir = os.path.sep.join([base_dir, name])
1579

    
1580
  status, api_versions = _OSOndiskAPIVersion(name, os_dir)
1581
  if not status:
1582
    # push the error up
1583
    return status, api_versions
1584

    
1585
  if not constants.OS_API_VERSIONS.intersection(api_versions):
1586
    return False, ("API version mismatch for path '%s': found %s, want %s." %
1587
                   (os_dir, api_versions, constants.OS_API_VERSIONS))
1588

    
1589
  # OS Scripts dictionary, we will populate it with the actual script names
1590
  os_scripts = dict.fromkeys(constants.OS_SCRIPTS)
1591

    
1592
  for script in os_scripts:
1593
    os_scripts[script] = os.path.sep.join([os_dir, script])
1594

    
1595
    try:
1596
      st = os.stat(os_scripts[script])
1597
    except EnvironmentError, err:
1598
      return False, ("Script '%s' under path '%s' is missing (%s)" %
1599
                     (script, os_dir, _ErrnoOrStr(err)))
1600

    
1601
    if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1602
      return False, ("Script '%s' under path '%s' is not executable" %
1603
                     (script, os_dir))
1604

    
1605
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1606
      return False, ("Script '%s' under path '%s' is not a regular file" %
1607
                     (script, os_dir))
1608

    
1609
  os_obj = objects.OS(name=name, path=os_dir,
1610
                      create_script=os_scripts[constants.OS_SCRIPT_CREATE],
1611
                      export_script=os_scripts[constants.OS_SCRIPT_EXPORT],
1612
                      import_script=os_scripts[constants.OS_SCRIPT_IMPORT],
1613
                      rename_script=os_scripts[constants.OS_SCRIPT_RENAME],
1614
                      api_versions=api_versions)
1615
  return True, os_obj
1616

    
1617

    
1618
def OSFromDisk(name, base_dir=None):
1619
  """Create an OS instance from disk.
1620

1621
  This function will return an OS instance if the given name is a
1622
  valid OS name. Otherwise, it will raise an appropriate
1623
  L{RPCFail} exception, detailing why this is not a valid OS.
1624

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

1628
  @type base_dir: string
1629
  @keyword base_dir: Base directory containing OS installations.
1630
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1631
  @rtype: L{objects.OS}
1632
  @return: the OS instance if we find a valid one
1633
  @raise RPCFail: if we don't find a valid OS
1634

1635
  """
1636
  status, payload = _TryOSFromDisk(name, base_dir)
1637

    
1638
  if not status:
1639
    _Fail(payload)
1640

    
1641
  return payload
1642

    
1643

    
1644
def OSEnvironment(instance, os, debug=0):
1645
  """Calculate the environment for an os script.
1646

1647
  @type instance: L{objects.Instance}
1648
  @param instance: target instance for the os script run
1649
  @type os: L{objects.OS}
1650
  @param os: operating system for which the environment is being built
1651
  @type debug: integer
1652
  @param debug: debug level (0 or 1, for OS Api 10)
1653
  @rtype: dict
1654
  @return: dict of environment variables
1655
  @raise errors.BlockDeviceError: if the block device
1656
      cannot be found
1657

1658
  """
1659
  result = {}
1660
  api_version = max(constants.OS_API_VERSIONS.intersection(os.api_versions))
1661
  result['OS_API_VERSION'] = '%d' % api_version
1662
  result['INSTANCE_NAME'] = instance.name
1663
  result['INSTANCE_OS'] = instance.os
1664
  result['HYPERVISOR'] = instance.hypervisor
1665
  result['DISK_COUNT'] = '%d' % len(instance.disks)
1666
  result['NIC_COUNT'] = '%d' % len(instance.nics)
1667
  result['DEBUG_LEVEL'] = '%d' % debug
1668
  for idx, disk in enumerate(instance.disks):
1669
    real_disk = _RecursiveFindBD(disk)
1670
    if real_disk is None:
1671
      raise errors.BlockDeviceError("Block device '%s' is not set up" %
1672
                                    str(disk))
1673
    real_disk.Open()
1674
    result['DISK_%d_PATH' % idx] = real_disk.dev_path
1675
    result['DISK_%d_ACCESS' % idx] = disk.mode
1676
    if constants.HV_DISK_TYPE in instance.hvparams:
1677
      result['DISK_%d_FRONTEND_TYPE' % idx] = \
1678
        instance.hvparams[constants.HV_DISK_TYPE]
1679
    if disk.dev_type in constants.LDS_BLOCK:
1680
      result['DISK_%d_BACKEND_TYPE' % idx] = 'block'
1681
    elif disk.dev_type == constants.LD_FILE:
1682
      result['DISK_%d_BACKEND_TYPE' % idx] = \
1683
        'file:%s' % disk.physical_id[0]
1684
  for idx, nic in enumerate(instance.nics):
1685
    result['NIC_%d_MAC' % idx] = nic.mac
1686
    if nic.ip:
1687
      result['NIC_%d_IP' % idx] = nic.ip
1688
    result['NIC_%d_MODE' % idx] = nic.nicparams[constants.NIC_MODE]
1689
    if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
1690
      result['NIC_%d_BRIDGE' % idx] = nic.nicparams[constants.NIC_LINK]
1691
    if nic.nicparams[constants.NIC_LINK]:
1692
      result['NIC_%d_LINK' % idx] = nic.nicparams[constants.NIC_LINK]
1693
    if constants.HV_NIC_TYPE in instance.hvparams:
1694
      result['NIC_%d_FRONTEND_TYPE' % idx] = \
1695
        instance.hvparams[constants.HV_NIC_TYPE]
1696

    
1697
  for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
1698
    for key, value in source.items():
1699
      result["INSTANCE_%s_%s" % (kind, key)] = str(value)
1700

    
1701
  return result
1702

    
1703
def BlockdevGrow(disk, amount):
1704
  """Grow a stack of block devices.
1705

1706
  This function is called recursively, with the childrens being the
1707
  first ones to resize.
1708

1709
  @type disk: L{objects.Disk}
1710
  @param disk: the disk to be grown
1711
  @rtype: (status, result)
1712
  @return: a tuple with the status of the operation
1713
      (True/False), and the errors message if status
1714
      is False
1715

1716
  """
1717
  r_dev = _RecursiveFindBD(disk)
1718
  if r_dev is None:
1719
    _Fail("Cannot find block device %s", disk)
1720

    
1721
  try:
1722
    r_dev.Grow(amount)
1723
  except errors.BlockDeviceError, err:
1724
    _Fail("Failed to grow block device: %s", err, exc=True)
1725

    
1726

    
1727
def BlockdevSnapshot(disk):
1728
  """Create a snapshot copy of a block device.
1729

1730
  This function is called recursively, and the snapshot is actually created
1731
  just for the leaf lvm backend device.
1732

1733
  @type disk: L{objects.Disk}
1734
  @param disk: the disk to be snapshotted
1735
  @rtype: string
1736
  @return: snapshot disk path
1737

1738
  """
1739
  if disk.children:
1740
    if len(disk.children) == 1:
1741
      # only one child, let's recurse on it
1742
      return BlockdevSnapshot(disk.children[0])
1743
    else:
1744
      # more than one child, choose one that matches
1745
      for child in disk.children:
1746
        if child.size == disk.size:
1747
          # return implies breaking the loop
1748
          return BlockdevSnapshot(child)
1749
  elif disk.dev_type == constants.LD_LV:
1750
    r_dev = _RecursiveFindBD(disk)
1751
    if r_dev is not None:
1752
      # let's stay on the safe side and ask for the full size, for now
1753
      return r_dev.Snapshot(disk.size)
1754
    else:
1755
      _Fail("Cannot find block device %s", disk)
1756
  else:
1757
    _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
1758
          disk.unique_id, disk.dev_type)
1759

    
1760

    
1761
def ExportSnapshot(disk, dest_node, instance, cluster_name, idx):
1762
  """Export a block device snapshot to a remote node.
1763

1764
  @type disk: L{objects.Disk}
1765
  @param disk: the description of the disk to export
1766
  @type dest_node: str
1767
  @param dest_node: the destination node to export to
1768
  @type instance: L{objects.Instance}
1769
  @param instance: the instance object to whom the disk belongs
1770
  @type cluster_name: str
1771
  @param cluster_name: the cluster name, needed for SSH hostalias
1772
  @type idx: int
1773
  @param idx: the index of the disk in the instance's disk list,
1774
      used to export to the OS scripts environment
1775
  @rtype: None
1776

1777
  """
1778
  inst_os = OSFromDisk(instance.os)
1779
  export_env = OSEnvironment(instance, inst_os)
1780

    
1781
  export_script = inst_os.export_script
1782

    
1783
  logfile = "%s/exp-%s-%s-%s.log" % (constants.LOG_OS_DIR, inst_os.name,
1784
                                     instance.name, int(time.time()))
1785
  if not os.path.exists(constants.LOG_OS_DIR):
1786
    os.mkdir(constants.LOG_OS_DIR, 0750)
1787
  real_disk = _RecursiveFindBD(disk)
1788
  if real_disk is None:
1789
    _Fail("Block device '%s' is not set up", disk)
1790

    
1791
  real_disk.Open()
1792

    
1793
  export_env['EXPORT_DEVICE'] = real_disk.dev_path
1794
  export_env['EXPORT_INDEX'] = str(idx)
1795

    
1796
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1797
  destfile = disk.physical_id[1]
1798

    
1799
  # the target command is built out of three individual commands,
1800
  # which are joined by pipes; we check each individual command for
1801
  # valid parameters
1802
  expcmd = utils.BuildShellCmd("cd %s; %s 2>%s", inst_os.path,
1803
                               export_script, logfile)
1804

    
1805
  comprcmd = "gzip"
1806

    
1807
  destcmd = utils.BuildShellCmd("mkdir -p %s && cat > %s/%s",
1808
                                destdir, destdir, destfile)
1809
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1810
                                                   constants.GANETI_RUNAS,
1811
                                                   destcmd)
1812

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

    
1816
  result = utils.RunCmd(command, env=export_env)
1817

    
1818
  if result.failed:
1819
    _Fail("OS snapshot export command '%s' returned error: %s"
1820
          " output: %s", command, result.fail_reason, result.output)
1821

    
1822

    
1823
def FinalizeExport(instance, snap_disks):
1824
  """Write out the export configuration information.
1825

1826
  @type instance: L{objects.Instance}
1827
  @param instance: the instance which we export, used for
1828
      saving configuration
1829
  @type snap_disks: list of L{objects.Disk}
1830
  @param snap_disks: list of snapshot block devices, which
1831
      will be used to get the actual name of the dump file
1832

1833
  @rtype: None
1834

1835
  """
1836
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1837
  finaldestdir = os.path.join(constants.EXPORT_DIR, instance.name)
1838

    
1839
  config = objects.SerializableConfigParser()
1840

    
1841
  config.add_section(constants.INISECT_EXP)
1842
  config.set(constants.INISECT_EXP, 'version', '0')
1843
  config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
1844
  config.set(constants.INISECT_EXP, 'source', instance.primary_node)
1845
  config.set(constants.INISECT_EXP, 'os', instance.os)
1846
  config.set(constants.INISECT_EXP, 'compression', 'gzip')
1847

    
1848
  config.add_section(constants.INISECT_INS)
1849
  config.set(constants.INISECT_INS, 'name', instance.name)
1850
  config.set(constants.INISECT_INS, 'memory', '%d' %
1851
             instance.beparams[constants.BE_MEMORY])
1852
  config.set(constants.INISECT_INS, 'vcpus', '%d' %
1853
             instance.beparams[constants.BE_VCPUS])
1854
  config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
1855

    
1856
  nic_total = 0
1857
  for nic_count, nic in enumerate(instance.nics):
1858
    nic_total += 1
1859
    config.set(constants.INISECT_INS, 'nic%d_mac' %
1860
               nic_count, '%s' % nic.mac)
1861
    config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
1862
    config.set(constants.INISECT_INS, 'nic%d_bridge' % nic_count,
1863
               '%s' % nic.bridge)
1864
  # TODO: redundant: on load can read nics until it doesn't exist
1865
  config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_total)
1866

    
1867
  disk_total = 0
1868
  for disk_count, disk in enumerate(snap_disks):
1869
    if disk:
1870
      disk_total += 1
1871
      config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
1872
                 ('%s' % disk.iv_name))
1873
      config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
1874
                 ('%s' % disk.physical_id[1]))
1875
      config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
1876
                 ('%d' % disk.size))
1877

    
1878
  config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_total)
1879

    
1880
  utils.WriteFile(os.path.join(destdir, constants.EXPORT_CONF_FILE),
1881
                  data=config.Dumps())
1882
  shutil.rmtree(finaldestdir, True)
1883
  shutil.move(destdir, finaldestdir)
1884

    
1885

    
1886
def ExportInfo(dest):
1887
  """Get export configuration information.
1888

1889
  @type dest: str
1890
  @param dest: directory containing the export
1891

1892
  @rtype: L{objects.SerializableConfigParser}
1893
  @return: a serializable config file containing the
1894
      export info
1895

1896
  """
1897
  cff = os.path.join(dest, constants.EXPORT_CONF_FILE)
1898

    
1899
  config = objects.SerializableConfigParser()
1900
  config.read(cff)
1901

    
1902
  if (not config.has_section(constants.INISECT_EXP) or
1903
      not config.has_section(constants.INISECT_INS)):
1904
    _Fail("Export info file doesn't have the required fields")
1905

    
1906
  return config.Dumps()
1907

    
1908

    
1909
def ImportOSIntoInstance(instance, src_node, src_images, cluster_name):
1910
  """Import an os image into an instance.
1911

1912
  @type instance: L{objects.Instance}
1913
  @param instance: instance to import the disks into
1914
  @type src_node: string
1915
  @param src_node: source node for the disk images
1916
  @type src_images: list of string
1917
  @param src_images: absolute paths of the disk images
1918
  @rtype: list of boolean
1919
  @return: each boolean represent the success of importing the n-th disk
1920

1921
  """
1922
  inst_os = OSFromDisk(instance.os)
1923
  import_env = OSEnvironment(instance, inst_os)
1924
  import_script = inst_os.import_script
1925

    
1926
  logfile = "%s/import-%s-%s-%s.log" % (constants.LOG_OS_DIR, instance.os,
1927
                                        instance.name, int(time.time()))
1928
  if not os.path.exists(constants.LOG_OS_DIR):
1929
    os.mkdir(constants.LOG_OS_DIR, 0750)
1930

    
1931
  comprcmd = "gunzip"
1932
  impcmd = utils.BuildShellCmd("(cd %s; %s >%s 2>&1)", inst_os.path,
1933
                               import_script, logfile)
1934

    
1935
  final_result = []
1936
  for idx, image in enumerate(src_images):
1937
    if image:
1938
      destcmd = utils.BuildShellCmd('cat %s', image)
1939
      remotecmd = _GetSshRunner(cluster_name).BuildCmd(src_node,
1940
                                                       constants.GANETI_RUNAS,
1941
                                                       destcmd)
1942
      command = '|'.join([utils.ShellQuoteArgs(remotecmd), comprcmd, impcmd])
1943
      import_env['IMPORT_DEVICE'] = import_env['DISK_%d_PATH' % idx]
1944
      import_env['IMPORT_INDEX'] = str(idx)
1945
      result = utils.RunCmd(command, env=import_env)
1946
      if result.failed:
1947
        logging.error("Disk import command '%s' returned error: %s"
1948
                      " output: %s", command, result.fail_reason,
1949
                      result.output)
1950
        final_result.append("error importing disk %d: %s, %s" %
1951
                            (idx, result.fail_reason, result.output[-100]))
1952

    
1953
  if final_result:
1954
    _Fail("; ".join(final_result), log=False)
1955

    
1956

    
1957
def ListExports():
1958
  """Return a list of exports currently available on this machine.
1959

1960
  @rtype: list
1961
  @return: list of the exports
1962

1963
  """
1964
  if os.path.isdir(constants.EXPORT_DIR):
1965
    return utils.ListVisibleFiles(constants.EXPORT_DIR)
1966
  else:
1967
    _Fail("No exports directory")
1968

    
1969

    
1970
def RemoveExport(export):
1971
  """Remove an existing export from the node.
1972

1973
  @type export: str
1974
  @param export: the name of the export to remove
1975
  @rtype: None
1976

1977
  """
1978
  target = os.path.join(constants.EXPORT_DIR, export)
1979

    
1980
  try:
1981
    shutil.rmtree(target)
1982
  except EnvironmentError, err:
1983
    _Fail("Error while removing the export: %s", err, exc=True)
1984

    
1985

    
1986
def BlockdevRename(devlist):
1987
  """Rename a list of block devices.
1988

1989
  @type devlist: list of tuples
1990
  @param devlist: list of tuples of the form  (disk,
1991
      new_logical_id, new_physical_id); disk is an
1992
      L{objects.Disk} object describing the current disk,
1993
      and new logical_id/physical_id is the name we
1994
      rename it to
1995
  @rtype: boolean
1996
  @return: True if all renames succeeded, False otherwise
1997

1998
  """
1999
  msgs = []
2000
  result = True
2001
  for disk, unique_id in devlist:
2002
    dev = _RecursiveFindBD(disk)
2003
    if dev is None:
2004
      msgs.append("Can't find device %s in rename" % str(disk))
2005
      result = False
2006
      continue
2007
    try:
2008
      old_rpath = dev.dev_path
2009
      dev.Rename(unique_id)
2010
      new_rpath = dev.dev_path
2011
      if old_rpath != new_rpath:
2012
        DevCacheManager.RemoveCache(old_rpath)
2013
        # FIXME: we should add the new cache information here, like:
2014
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2015
        # but we don't have the owner here - maybe parse from existing
2016
        # cache? for now, we only lose lvm data when we rename, which
2017
        # is less critical than DRBD or MD
2018
    except errors.BlockDeviceError, err:
2019
      msgs.append("Can't rename device '%s' to '%s': %s" %
2020
                  (dev, unique_id, err))
2021
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2022
      result = False
2023
  if not result:
2024
    _Fail("; ".join(msgs))
2025

    
2026

    
2027
def _TransformFileStorageDir(file_storage_dir):
2028
  """Checks whether given file_storage_dir is valid.
2029

2030
  Checks wheter the given file_storage_dir is within the cluster-wide
2031
  default file_storage_dir stored in SimpleStore. Only paths under that
2032
  directory are allowed.
2033

2034
  @type file_storage_dir: str
2035
  @param file_storage_dir: the path to check
2036

2037
  @return: the normalized path if valid, None otherwise
2038

2039
  """
2040
  cfg = _GetConfig()
2041
  file_storage_dir = os.path.normpath(file_storage_dir)
2042
  base_file_storage_dir = cfg.GetFileStorageDir()
2043
  if (not os.path.commonprefix([file_storage_dir, base_file_storage_dir]) ==
2044
      base_file_storage_dir):
2045
    _Fail("File storage directory '%s' is not under base file"
2046
          " storage directory '%s'", file_storage_dir, base_file_storage_dir)
2047
  return file_storage_dir
2048

    
2049

    
2050
def CreateFileStorageDir(file_storage_dir):
2051
  """Create file storage directory.
2052

2053
  @type file_storage_dir: str
2054
  @param file_storage_dir: directory to create
2055

2056
  @rtype: tuple
2057
  @return: tuple with first element a boolean indicating wheter dir
2058
      creation was successful or not
2059

2060
  """
2061
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2062
  if os.path.exists(file_storage_dir):
2063
    if not os.path.isdir(file_storage_dir):
2064
      _Fail("Specified storage dir '%s' is not a directory",
2065
            file_storage_dir)
2066
  else:
2067
    try:
2068
      os.makedirs(file_storage_dir, 0750)
2069
    except OSError, err:
2070
      _Fail("Cannot create file storage directory '%s': %s",
2071
            file_storage_dir, err, exc=True)
2072

    
2073

    
2074
def RemoveFileStorageDir(file_storage_dir):
2075
  """Remove file storage directory.
2076

2077
  Remove it only if it's empty. If not log an error and return.
2078

2079
  @type file_storage_dir: str
2080
  @param file_storage_dir: the directory we should cleanup
2081
  @rtype: tuple (success,)
2082
  @return: tuple of one element, C{success}, denoting
2083
      whether the operation was successful
2084

2085
  """
2086
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2087
  if os.path.exists(file_storage_dir):
2088
    if not os.path.isdir(file_storage_dir):
2089
      _Fail("Specified Storage directory '%s' is not a directory",
2090
            file_storage_dir)
2091
    # deletes dir only if empty, otherwise we want to fail the rpc call
2092
    try:
2093
      os.rmdir(file_storage_dir)
2094
    except OSError, err:
2095
      _Fail("Cannot remove file storage directory '%s': %s",
2096
            file_storage_dir, err)
2097

    
2098

    
2099
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2100
  """Rename the file storage directory.
2101

2102
  @type old_file_storage_dir: str
2103
  @param old_file_storage_dir: the current path
2104
  @type new_file_storage_dir: str
2105
  @param new_file_storage_dir: the name we should rename to
2106
  @rtype: tuple (success,)
2107
  @return: tuple of one element, C{success}, denoting
2108
      whether the operation was successful
2109

2110
  """
2111
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2112
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2113
  if not os.path.exists(new_file_storage_dir):
2114
    if os.path.isdir(old_file_storage_dir):
2115
      try:
2116
        os.rename(old_file_storage_dir, new_file_storage_dir)
2117
      except OSError, err:
2118
        _Fail("Cannot rename '%s' to '%s': %s",
2119
              old_file_storage_dir, new_file_storage_dir, err)
2120
    else:
2121
      _Fail("Specified storage dir '%s' is not a directory",
2122
            old_file_storage_dir)
2123
  else:
2124
    if os.path.exists(old_file_storage_dir):
2125
      _Fail("Cannot rename '%s' to '%s': both locations exist",
2126
            old_file_storage_dir, new_file_storage_dir)
2127

    
2128

    
2129
def _EnsureJobQueueFile(file_name):
2130
  """Checks whether the given filename is in the queue directory.
2131

2132
  @type file_name: str
2133
  @param file_name: the file name we should check
2134
  @rtype: None
2135
  @raises RPCFail: if the file is not valid
2136

2137
  """
2138
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2139
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2140

    
2141
  if not result:
2142
    _Fail("Passed job queue file '%s' does not belong to"
2143
          " the queue directory '%s'", file_name, queue_dir)
2144

    
2145

    
2146
def JobQueueUpdate(file_name, content):
2147
  """Updates a file in the queue directory.
2148

2149
  This is just a wrapper over L{utils.WriteFile}, with proper
2150
  checking.
2151

2152
  @type file_name: str
2153
  @param file_name: the job file name
2154
  @type content: str
2155
  @param content: the new job contents
2156
  @rtype: boolean
2157
  @return: the success of the operation
2158

2159
  """
2160
  _EnsureJobQueueFile(file_name)
2161

    
2162
  # Write and replace the file atomically
2163
  utils.WriteFile(file_name, data=_Decompress(content))
2164

    
2165

    
2166
def JobQueueRename(old, new):
2167
  """Renames a job queue file.
2168

2169
  This is just a wrapper over os.rename with proper checking.
2170

2171
  @type old: str
2172
  @param old: the old (actual) file name
2173
  @type new: str
2174
  @param new: the desired file name
2175
  @rtype: tuple
2176
  @return: the success of the operation and payload
2177

2178
  """
2179
  _EnsureJobQueueFile(old)
2180
  _EnsureJobQueueFile(new)
2181

    
2182
  utils.RenameFile(old, new, mkdir=True)
2183

    
2184

    
2185
def JobQueueSetDrainFlag(drain_flag):
2186
  """Set the drain flag for the queue.
2187

2188
  This will set or unset the queue drain flag.
2189

2190
  @type drain_flag: boolean
2191
  @param drain_flag: if True, will set the drain flag, otherwise reset it.
2192
  @rtype: truple
2193
  @return: always True, None
2194
  @warning: the function always returns True
2195

2196
  """
2197
  if drain_flag:
2198
    utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True)
2199
  else:
2200
    utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
2201

    
2202

    
2203
def BlockdevClose(instance_name, disks):
2204
  """Closes the given block devices.
2205

2206
  This means they will be switched to secondary mode (in case of
2207
  DRBD).
2208

2209
  @param instance_name: if the argument is not empty, the symlinks
2210
      of this instance will be removed
2211
  @type disks: list of L{objects.Disk}
2212
  @param disks: the list of disks to be closed
2213
  @rtype: tuple (success, message)
2214
  @return: a tuple of success and message, where success
2215
      indicates the succes of the operation, and message
2216
      which will contain the error details in case we
2217
      failed
2218

2219
  """
2220
  bdevs = []
2221
  for cf in disks:
2222
    rd = _RecursiveFindBD(cf)
2223
    if rd is None:
2224
      _Fail("Can't find device %s", cf)
2225
    bdevs.append(rd)
2226

    
2227
  msg = []
2228
  for rd in bdevs:
2229
    try:
2230
      rd.Close()
2231
    except errors.BlockDeviceError, err:
2232
      msg.append(str(err))
2233
  if msg:
2234
    _Fail("Can't make devices secondary: %s", ",".join(msg))
2235
  else:
2236
    if instance_name:
2237
      _RemoveBlockDevLinks(instance_name, disks)
2238

    
2239

    
2240
def ValidateHVParams(hvname, hvparams):
2241
  """Validates the given hypervisor parameters.
2242

2243
  @type hvname: string
2244
  @param hvname: the hypervisor name
2245
  @type hvparams: dict
2246
  @param hvparams: the hypervisor parameters to be validated
2247
  @rtype: None
2248

2249
  """
2250
  try:
2251
    hv_type = hypervisor.GetHypervisor(hvname)
2252
    hv_type.ValidateParameters(hvparams)
2253
  except errors.HypervisorError, err:
2254
    _Fail(str(err), log=False)
2255

    
2256

    
2257
def DemoteFromMC():
2258
  """Demotes the current node from master candidate role.
2259

2260
  """
2261
  # try to ensure we're not the master by mistake
2262
  master, myself = ssconf.GetMasterAndMyself()
2263
  if master == myself:
2264
    _Fail("ssconf status shows I'm the master node, will not demote")
2265
  pid_file = utils.DaemonPidFileName(constants.MASTERD_PID)
2266
  if utils.IsProcessAlive(utils.ReadPidFile(pid_file)):
2267
    _Fail("The master daemon is running, will not demote")
2268
  try:
2269
    if os.path.isfile(constants.CLUSTER_CONF_FILE):
2270
      utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2271
  except EnvironmentError, err:
2272
    if err.errno != errno.ENOENT:
2273
      _Fail("Error while backing up cluster file: %s", err, exc=True)
2274
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2275

    
2276

    
2277
def _FindDisks(nodes_ip, disks):
2278
  """Sets the physical ID on disks and returns the block devices.
2279

2280
  """
2281
  # set the correct physical ID
2282
  my_name = utils.HostInfo().name
2283
  for cf in disks:
2284
    cf.SetPhysicalID(my_name, nodes_ip)
2285

    
2286
  bdevs = []
2287

    
2288
  for cf in disks:
2289
    rd = _RecursiveFindBD(cf)
2290
    if rd is None:
2291
      _Fail("Can't find device %s", cf)
2292
    bdevs.append(rd)
2293
  return bdevs
2294

    
2295

    
2296
def DrbdDisconnectNet(nodes_ip, disks):
2297
  """Disconnects the network on a list of drbd devices.
2298

2299
  """
2300
  bdevs = _FindDisks(nodes_ip, disks)
2301

    
2302
  # disconnect disks
2303
  for rd in bdevs:
2304
    try:
2305
      rd.DisconnectNet()
2306
    except errors.BlockDeviceError, err:
2307
      _Fail("Can't change network configuration to standalone mode: %s",
2308
            err, exc=True)
2309

    
2310

    
2311
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
2312
  """Attaches the network on a list of drbd devices.
2313

2314
  """
2315
  bdevs = _FindDisks(nodes_ip, disks)
2316

    
2317
  if multimaster:
2318
    for idx, rd in enumerate(bdevs):
2319
      try:
2320
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
2321
      except EnvironmentError, err:
2322
        _Fail("Can't create symlink: %s", err)
2323
  # reconnect disks, switch to new master configuration and if
2324
  # needed primary mode
2325
  for rd in bdevs:
2326
    try:
2327
      rd.AttachNet(multimaster)
2328
    except errors.BlockDeviceError, err:
2329
      _Fail("Can't change network configuration: %s", err)
2330
  # wait until the disks are connected; we need to retry the re-attach
2331
  # if the device becomes standalone, as this might happen if the one
2332
  # node disconnects and reconnects in a different mode before the
2333
  # other node reconnects; in this case, one or both of the nodes will
2334
  # decide it has wrong configuration and switch to standalone
2335
  RECONNECT_TIMEOUT = 2 * 60
2336
  sleep_time = 0.100 # start with 100 miliseconds
2337
  timeout_limit = time.time() + RECONNECT_TIMEOUT
2338
  while time.time() < timeout_limit:
2339
    all_connected = True
2340
    for rd in bdevs:
2341
      stats = rd.GetProcStatus()
2342
      if not (stats.is_connected or stats.is_in_resync):
2343
        all_connected = False
2344
      if stats.is_standalone:
2345
        # peer had different config info and this node became
2346
        # standalone, even though this should not happen with the
2347
        # new staged way of changing disk configs
2348
        try:
2349
          rd.AttachNet(multimaster)
2350
        except errors.BlockDeviceError, err:
2351
          _Fail("Can't change network configuration: %s", err)
2352
    if all_connected:
2353
      break
2354
    time.sleep(sleep_time)
2355
    sleep_time = min(5, sleep_time * 1.5)
2356
  if not all_connected:
2357
    _Fail("Timeout in disk reconnecting")
2358
  if multimaster:
2359
    # change to primary mode
2360
    for rd in bdevs:
2361
      try:
2362
        rd.Open()
2363
      except errors.BlockDeviceError, err:
2364
        _Fail("Can't change to primary mode: %s", err)
2365

    
2366

    
2367
def DrbdWaitSync(nodes_ip, disks):
2368
  """Wait until DRBDs have synchronized.
2369

2370
  """
2371
  bdevs = _FindDisks(nodes_ip, disks)
2372

    
2373
  min_resync = 100
2374
  alldone = True
2375
  for rd in bdevs:
2376
    stats = rd.GetProcStatus()
2377
    if not (stats.is_connected or stats.is_in_resync):
2378
      _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
2379
    alldone = alldone and (not stats.is_in_resync)
2380
    if stats.sync_percent is not None:
2381
      min_resync = min(min_resync, stats.sync_percent)
2382

    
2383
  return (alldone, min_resync)
2384

    
2385

    
2386
def PowercycleNode(hypervisor_type):
2387
  """Hard-powercycle the node.
2388

2389
  Because we need to return first, and schedule the powercycle in the
2390
  background, we won't be able to report failures nicely.
2391

2392
  """
2393
  hyper = hypervisor.GetHypervisor(hypervisor_type)
2394
  try:
2395
    pid = os.fork()
2396
  except OSError:
2397
    # if we can't fork, we'll pretend that we're in the child process
2398
    pid = 0
2399
  if pid > 0:
2400
    return "Reboot scheduled in 5 seconds"
2401
  time.sleep(5)
2402
  hyper.PowercycleNode()
2403

    
2404

    
2405
class HooksRunner(object):
2406
  """Hook runner.
2407

2408
  This class is instantiated on the node side (ganeti-noded) and not
2409
  on the master side.
2410

2411
  """
2412
  RE_MASK = re.compile("^[a-zA-Z0-9_-]+$")
2413

    
2414
  def __init__(self, hooks_base_dir=None):
2415
    """Constructor for hooks runner.
2416

2417
    @type hooks_base_dir: str or None
2418
    @param hooks_base_dir: if not None, this overrides the
2419
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
2420

2421
    """
2422
    if hooks_base_dir is None:
2423
      hooks_base_dir = constants.HOOKS_BASE_DIR
2424
    self._BASE_DIR = hooks_base_dir
2425

    
2426
  @staticmethod
2427
  def ExecHook(script, env):
2428
    """Exec one hook script.
2429

2430
    @type script: str
2431
    @param script: the full path to the script
2432
    @type env: dict
2433
    @param env: the environment with which to exec the script
2434
    @rtype: tuple (success, message)
2435
    @return: a tuple of success and message, where success
2436
        indicates the succes of the operation, and message
2437
        which will contain the error details in case we
2438
        failed
2439

2440
    """
2441
    # exec the process using subprocess and log the output
2442
    fdstdin = None
2443
    try:
2444
      fdstdin = open("/dev/null", "r")
2445
      child = subprocess.Popen([script], stdin=fdstdin, stdout=subprocess.PIPE,
2446
                               stderr=subprocess.STDOUT, close_fds=True,
2447
                               shell=False, cwd="/", env=env)
2448
      output = ""
2449
      try:
2450
        output = child.stdout.read(4096)
2451
        child.stdout.close()
2452
      except EnvironmentError, err:
2453
        output += "Hook script error: %s" % str(err)
2454

    
2455
      while True:
2456
        try:
2457
          result = child.wait()
2458
          break
2459
        except EnvironmentError, err:
2460
          if err.errno == errno.EINTR:
2461
            continue
2462
          raise
2463
    finally:
2464
      # try not to leak fds
2465
      for fd in (fdstdin, ):
2466
        if fd is not None:
2467
          try:
2468
            fd.close()
2469
          except EnvironmentError, err:
2470
            # just log the error
2471
            #logging.exception("Error while closing fd %s", fd)
2472
            pass
2473

    
2474
    return result == 0, utils.SafeEncode(output.strip())
2475

    
2476
  def RunHooks(self, hpath, phase, env):
2477
    """Run the scripts in the hooks directory.
2478

2479
    @type hpath: str
2480
    @param hpath: the path to the hooks directory which
2481
        holds the scripts
2482
    @type phase: str
2483
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
2484
        L{constants.HOOKS_PHASE_POST}
2485
    @type env: dict
2486
    @param env: dictionary with the environment for the hook
2487
    @rtype: list
2488
    @return: list of 3-element tuples:
2489
      - script path
2490
      - script result, either L{constants.HKR_SUCCESS} or
2491
        L{constants.HKR_FAIL}
2492
      - output of the script
2493

2494
    @raise errors.ProgrammerError: for invalid input
2495
        parameters
2496

2497
    """
2498
    if phase == constants.HOOKS_PHASE_PRE:
2499
      suffix = "pre"
2500
    elif phase == constants.HOOKS_PHASE_POST:
2501
      suffix = "post"
2502
    else:
2503
      _Fail("Unknown hooks phase '%s'", phase)
2504

    
2505
    rr = []
2506

    
2507
    subdir = "%s-%s.d" % (hpath, suffix)
2508
    dir_name = "%s/%s" % (self._BASE_DIR, subdir)
2509
    try:
2510
      dir_contents = utils.ListVisibleFiles(dir_name)
2511
    except OSError:
2512
      # FIXME: must log output in case of failures
2513
      return rr
2514

    
2515
    # we use the standard python sort order,
2516
    # so 00name is the recommended naming scheme
2517
    dir_contents.sort()
2518
    for relname in dir_contents:
2519
      fname = os.path.join(dir_name, relname)
2520
      if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and
2521
          self.RE_MASK.match(relname) is not None):
2522
        rrval = constants.HKR_SKIP
2523
        output = ""
2524
      else:
2525
        result, output = self.ExecHook(fname, env)
2526
        if not result:
2527
          rrval = constants.HKR_FAIL
2528
        else:
2529
          rrval = constants.HKR_SUCCESS
2530
      rr.append(("%s/%s" % (subdir, relname), rrval, output))
2531

    
2532
    return rr
2533

    
2534

    
2535
class IAllocatorRunner(object):
2536
  """IAllocator runner.
2537

2538
  This class is instantiated on the node side (ganeti-noded) and not on
2539
  the master side.
2540

2541
  """
2542
  def Run(self, name, idata):
2543
    """Run an iallocator script.
2544

2545
    @type name: str
2546
    @param name: the iallocator script name
2547
    @type idata: str
2548
    @param idata: the allocator input data
2549

2550
    @rtype: tuple
2551
    @return: two element tuple of:
2552
       - status
2553
       - either error message or stdout of allocator (for success)
2554

2555
    """
2556
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
2557
                                  os.path.isfile)
2558
    if alloc_script is None:
2559
      _Fail("iallocator module '%s' not found in the search path", name)
2560

    
2561
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
2562
    try:
2563
      os.write(fd, idata)
2564
      os.close(fd)
2565
      result = utils.RunCmd([alloc_script, fin_name])
2566
      if result.failed:
2567
        _Fail("iallocator module '%s' failed: %s, output '%s'",
2568
              name, result.fail_reason, result.output)
2569
    finally:
2570
      os.unlink(fin_name)
2571

    
2572
    return result.stdout
2573

    
2574

    
2575
class DevCacheManager(object):
2576
  """Simple class for managing a cache of block device information.
2577

2578
  """
2579
  _DEV_PREFIX = "/dev/"
2580
  _ROOT_DIR = constants.BDEV_CACHE_DIR
2581

    
2582
  @classmethod
2583
  def _ConvertPath(cls, dev_path):
2584
    """Converts a /dev/name path to the cache file name.
2585

2586
    This replaces slashes with underscores and strips the /dev
2587
    prefix. It then returns the full path to the cache file.
2588

2589
    @type dev_path: str
2590
    @param dev_path: the C{/dev/} path name
2591
    @rtype: str
2592
    @return: the converted path name
2593

2594
    """
2595
    if dev_path.startswith(cls._DEV_PREFIX):
2596
      dev_path = dev_path[len(cls._DEV_PREFIX):]
2597
    dev_path = dev_path.replace("/", "_")
2598
    fpath = "%s/bdev_%s" % (cls._ROOT_DIR, dev_path)
2599
    return fpath
2600

    
2601
  @classmethod
2602
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
2603
    """Updates the cache information for a given device.
2604

2605
    @type dev_path: str
2606
    @param dev_path: the pathname of the device
2607
    @type owner: str
2608
    @param owner: the owner (instance name) of the device
2609
    @type on_primary: bool
2610
    @param on_primary: whether this is the primary
2611
        node nor not
2612
    @type iv_name: str
2613
    @param iv_name: the instance-visible name of the
2614
        device, as in objects.Disk.iv_name
2615

2616
    @rtype: None
2617

2618
    """
2619
    if dev_path is None:
2620
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
2621
      return
2622
    fpath = cls._ConvertPath(dev_path)
2623
    if on_primary:
2624
      state = "primary"
2625
    else:
2626
      state = "secondary"
2627
    if iv_name is None:
2628
      iv_name = "not_visible"
2629
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
2630
    try:
2631
      utils.WriteFile(fpath, data=fdata)
2632
    except EnvironmentError, err:
2633
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
2634

    
2635
  @classmethod
2636
  def RemoveCache(cls, dev_path):
2637
    """Remove data for a dev_path.
2638

2639
    This is just a wrapper over L{utils.RemoveFile} with a converted
2640
    path name and logging.
2641

2642
    @type dev_path: str
2643
    @param dev_path: the pathname of the device
2644

2645
    @rtype: None
2646

2647
    """
2648
    if dev_path is None:
2649
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
2650
      return
2651
    fpath = cls._ConvertPath(dev_path)
2652
    try:
2653
      utils.RemoveFile(fpath)
2654
    except EnvironmentError, err:
2655
      logging.exception("Can't update bdev cache for %s: %s", dev_path, err)