Avoid absolute path for privileged commands
[ganeti-local] / lib / backend.py
1 #
2 #
3
4 # Copyright (C) 2006, 2007 Google Inc.
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 # General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 # 02110-1301, USA.
20
21
22 """Functions used by the node daemon
23
24 @var _ALLOWED_UPLOAD_FILES: denotes which files are accepted in
25      the L{UploadFile} function
26
27 """
28
29 # pylint: disable-msg=E1103
30
31 # E1103: %s %r has no %r member (but some types could not be
32 # inferred), because the _TryOSFromDisk returns either (True, os_obj)
33 # or (False, "string") which confuses pylint
34
35
36 import os
37 import os.path
38 import shutil
39 import time
40 import stat
41 import errno
42 import re
43 import random
44 import logging
45 import tempfile
46 import zlib
47 import base64
48
49 from ganeti import errors
50 from ganeti import utils
51 from ganeti import ssh
52 from ganeti import hypervisor
53 from ganeti import constants
54 from ganeti import bdev
55 from ganeti import objects
56 from ganeti import ssconf
57
58
59 _BOOT_ID_PATH = "/proc/sys/kernel/random/boot_id"
60
61
62 class RPCFail(Exception):
63   """Class denoting RPC failure.
64
65   Its argument is the error message.
66
67   """
68
69
70 def _Fail(msg, *args, **kwargs):
71   """Log an error and the raise an RPCFail exception.
72
73   This exception is then handled specially in the ganeti daemon and
74   turned into a 'failed' return type. As such, this function is a
75   useful shortcut for logging the error and returning it to the master
76   daemon.
77
78   @type msg: string
79   @param msg: the text of the exception
80   @raise RPCFail
81
82   """
83   if args:
84     msg = msg % args
85   if "log" not in kwargs or kwargs["log"]: # if we should log this error
86     if "exc" in kwargs and kwargs["exc"]:
87       logging.exception(msg)
88     else:
89       logging.error(msg)
90   raise RPCFail(msg)
91
92
93 def _GetConfig():
94   """Simple wrapper to return a SimpleStore.
95
96   @rtype: L{ssconf.SimpleStore}
97   @return: a SimpleStore instance
98
99   """
100   return ssconf.SimpleStore()
101
102
103 def _GetSshRunner(cluster_name):
104   """Simple wrapper to return an SshRunner.
105
106   @type cluster_name: str
107   @param cluster_name: the cluster name, which is needed
108       by the SshRunner constructor
109   @rtype: L{ssh.SshRunner}
110   @return: an SshRunner instance
111
112   """
113   return ssh.SshRunner(cluster_name)
114
115
116 def _Decompress(data):
117   """Unpacks data compressed by the RPC client.
118
119   @type data: list or tuple
120   @param data: Data sent by RPC client
121   @rtype: str
122   @return: Decompressed data
123
124   """
125   assert isinstance(data, (list, tuple))
126   assert len(data) == 2
127   (encoding, content) = data
128   if encoding == constants.RPC_ENCODING_NONE:
129     return content
130   elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
131     return zlib.decompress(base64.b64decode(content))
132   else:
133     raise AssertionError("Unknown data encoding")
134
135
136 def _CleanDirectory(path, exclude=None):
137   """Removes all regular files in a directory.
138
139   @type path: str
140   @param path: the directory to clean
141   @type exclude: list
142   @param exclude: list of files to be excluded, defaults
143       to the empty list
144
145   """
146   if not os.path.isdir(path):
147     return
148   if exclude is None:
149     exclude = []
150   else:
151     # Normalize excluded paths
152     exclude = [os.path.normpath(i) for i in exclude]
153
154   for rel_name in utils.ListVisibleFiles(path):
155     full_name = os.path.normpath(os.path.join(path, rel_name))
156     if full_name in exclude:
157       continue
158     if os.path.isfile(full_name) and not os.path.islink(full_name):
159       utils.RemoveFile(full_name)
160
161
162 def _BuildUploadFileList():
163   """Build the list of allowed upload files.
164
165   This is abstracted so that it's built only once at module import time.
166
167   """
168   allowed_files = set([
169     constants.CLUSTER_CONF_FILE,
170     constants.ETC_HOSTS,
171     constants.SSH_KNOWN_HOSTS_FILE,
172     constants.VNC_PASSWORD_FILE,
173     constants.RAPI_CERT_FILE,
174     constants.RAPI_USERS_FILE,
175     constants.HMAC_CLUSTER_KEY,
176     ])
177
178   for hv_name in constants.HYPER_TYPES:
179     hv_class = hypervisor.GetHypervisorClass(hv_name)
180     allowed_files.update(hv_class.GetAncillaryFiles())
181
182   return frozenset(allowed_files)
183
184
185 _ALLOWED_UPLOAD_FILES = _BuildUploadFileList()
186
187
188 def JobQueuePurge():
189   """Removes job queue files and archived jobs.
190
191   @rtype: tuple
192   @return: True, None
193
194   """
195   _CleanDirectory(constants.QUEUE_DIR, exclude=[constants.JOB_QUEUE_LOCK_FILE])
196   _CleanDirectory(constants.JOB_QUEUE_ARCHIVE_DIR)
197
198
199 def GetMasterInfo():
200   """Returns master information.
201
202   This is an utility function to compute master information, either
203   for consumption here or from the node daemon.
204
205   @rtype: tuple
206   @return: master_netdev, master_ip, master_name
207   @raise RPCFail: in case of errors
208
209   """
210   try:
211     cfg = _GetConfig()
212     master_netdev = cfg.GetMasterNetdev()
213     master_ip = cfg.GetMasterIP()
214     master_node = cfg.GetMasterNode()
215   except errors.ConfigurationError, err:
216     _Fail("Cluster configuration incomplete: %s", err, exc=True)
217   return (master_netdev, master_ip, master_node)
218
219
220 def StartMaster(start_daemons, no_voting):
221   """Activate local node as master node.
222
223   The function will always try activate the IP address of the master
224   (unless someone else has it). It will also start the master daemons,
225   based on the start_daemons parameter.
226
227   @type start_daemons: boolean
228   @param start_daemons: whether to also start the master
229       daemons (ganeti-masterd and ganeti-rapi)
230   @type no_voting: boolean
231   @param no_voting: whether to start ganeti-masterd without a node vote
232       (if start_daemons is True), but still non-interactively
233   @rtype: None
234
235   """
236   # GetMasterInfo will raise an exception if not able to return data
237   master_netdev, master_ip, _ = GetMasterInfo()
238
239   err_msgs = []
240   if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
241     if utils.OwnIpAddress(master_ip):
242       # we already have the ip:
243       logging.debug("Master IP already configured, doing nothing")
244     else:
245       msg = "Someone else has the master ip, not activating"
246       logging.error(msg)
247       err_msgs.append(msg)
248   else:
249     result = utils.RunCmd(["ip", "address", "add", "%s/32" % master_ip,
250                            "dev", master_netdev, "label",
251                            "%s:0" % master_netdev])
252     if result.failed:
253       msg = "Can't activate master IP: %s" % result.output
254       logging.error(msg)
255       err_msgs.append(msg)
256
257     result = utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev,
258                            "-s", master_ip, master_ip])
259     # we'll ignore the exit code of arping
260
261   # and now start the master and rapi daemons
262   if start_daemons:
263     if no_voting:
264       masterd_args = "--no-voting --yes-do-it"
265     else:
266       masterd_args = ""
267
268     env = {
269       "EXTRA_MASTERD_ARGS": masterd_args,
270       }
271
272     result = utils.RunCmd([constants.DAEMON_UTIL, "start-master"], env=env)
273     if result.failed:
274       msg = "Can't start Ganeti master: %s" % result.output
275       logging.error(msg)
276       err_msgs.append(msg)
277
278   if err_msgs:
279     _Fail("; ".join(err_msgs))
280
281
282 def StopMaster(stop_daemons):
283   """Deactivate this node as master.
284
285   The function will always try to deactivate the IP address of the
286   master. It will also stop the master daemons depending on the
287   stop_daemons parameter.
288
289   @type stop_daemons: boolean
290   @param stop_daemons: whether to also stop the master daemons
291       (ganeti-masterd and ganeti-rapi)
292   @rtype: None
293
294   """
295   # TODO: log and report back to the caller the error failures; we
296   # need to decide in which case we fail the RPC for this
297
298   # GetMasterInfo will raise an exception if not able to return data
299   master_netdev, master_ip, _ = GetMasterInfo()
300
301   result = utils.RunCmd(["ip", "address", "del", "%s/32" % master_ip,
302                          "dev", master_netdev])
303   if result.failed:
304     logging.error("Can't remove the master IP, error: %s", result.output)
305     # but otherwise ignore the failure
306
307   if stop_daemons:
308     result = utils.RunCmd([constants.DAEMON_UTIL, "stop-master"])
309     if result.failed:
310       logging.error("Could not stop Ganeti master, command %s had exitcode %s"
311                     " and error %s",
312                     result.cmd, result.exit_code, result.output)
313
314
315 def AddNode(dsa, dsapub, rsa, rsapub, sshkey, sshpub):
316   """Joins this node to the cluster.
317
318   This does the following:
319       - updates the hostkeys of the machine (rsa and dsa)
320       - adds the ssh private key to the user
321       - adds the ssh public key to the users' authorized_keys file
322
323   @type dsa: str
324   @param dsa: the DSA private key to write
325   @type dsapub: str
326   @param dsapub: the DSA public key to write
327   @type rsa: str
328   @param rsa: the RSA private key to write
329   @type rsapub: str
330   @param rsapub: the RSA public key to write
331   @type sshkey: str
332   @param sshkey: the SSH private key to write
333   @type sshpub: str
334   @param sshpub: the SSH public key to write
335   @rtype: boolean
336   @return: the success of the operation
337
338   """
339   sshd_keys =  [(constants.SSH_HOST_RSA_PRIV, rsa, 0600),
340                 (constants.SSH_HOST_RSA_PUB, rsapub, 0644),
341                 (constants.SSH_HOST_DSA_PRIV, dsa, 0600),
342                 (constants.SSH_HOST_DSA_PUB, dsapub, 0644)]
343   for name, content, mode in sshd_keys:
344     utils.WriteFile(name, data=content, mode=mode)
345
346   try:
347     priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS,
348                                                     mkdir=True)
349   except errors.OpExecError, err:
350     _Fail("Error while processing user ssh files: %s", err, exc=True)
351
352   for name, content in [(priv_key, sshkey), (pub_key, sshpub)]:
353     utils.WriteFile(name, data=content, mode=0600)
354
355   utils.AddAuthorizedKey(auth_keys, sshpub)
356
357   result = utils.RunCmd([constants.DAEMON_UTIL, "reload-ssh-keys"])
358   if result.failed:
359     _Fail("Unable to reload SSH keys (command %r, exit code %s, output %r)",
360           result.cmd, result.exit_code, result.output)
361
362
363 def LeaveCluster(modify_ssh_setup):
364   """Cleans up and remove the current node.
365
366   This function cleans up and prepares the current node to be removed
367   from the cluster.
368
369   If processing is successful, then it raises an
370   L{errors.QuitGanetiException} which is used as a special case to
371   shutdown the node daemon.
372
373   @param modify_ssh_setup: boolean
374
375   """
376   _CleanDirectory(constants.DATA_DIR)
377   JobQueuePurge()
378
379   if modify_ssh_setup:
380     try:
381       priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
382
383       utils.RemoveAuthorizedKey(auth_keys, utils.ReadFile(pub_key))
384
385       utils.RemoveFile(priv_key)
386       utils.RemoveFile(pub_key)
387     except errors.OpExecError:
388       logging.exception("Error while processing ssh files")
389
390   try:
391     utils.RemoveFile(constants.HMAC_CLUSTER_KEY)
392     utils.RemoveFile(constants.RAPI_CERT_FILE)
393     utils.RemoveFile(constants.SSL_CERT_FILE)
394   except: # pylint: disable-msg=W0702
395     logging.exception("Error while removing cluster secrets")
396
397   result = utils.RunCmd([constants.DAEMON_UTIL, "stop", constants.CONFD])
398   if result.failed:
399     logging.error("Command %s failed with exitcode %s and error %s",
400                   result.cmd, result.exit_code, result.output)
401
402   # Raise a custom exception (handled in ganeti-noded)
403   raise errors.QuitGanetiException(True, 'Shutdown scheduled')
404
405
406 def GetNodeInfo(vgname, hypervisor_type):
407   """Gives back a hash with different information about the node.
408
409   @type vgname: C{string}
410   @param vgname: the name of the volume group to ask for disk space information
411   @type hypervisor_type: C{str}
412   @param hypervisor_type: the name of the hypervisor to ask for
413       memory information
414   @rtype: C{dict}
415   @return: dictionary with the following keys:
416       - vg_size is the size of the configured volume group in MiB
417       - vg_free is the free size of the volume group in MiB
418       - memory_dom0 is the memory allocated for domain0 in MiB
419       - memory_free is the currently available (free) ram in MiB
420       - memory_total is the total number of ram in MiB
421
422   """
423   outputarray = {}
424   vginfo = _GetVGInfo(vgname)
425   outputarray['vg_size'] = vginfo['vg_size']
426   outputarray['vg_free'] = vginfo['vg_free']
427
428   hyper = hypervisor.GetHypervisor(hypervisor_type)
429   hyp_info = hyper.GetNodeInfo()
430   if hyp_info is not None:
431     outputarray.update(hyp_info)
432
433   outputarray["bootid"] = utils.ReadFile(_BOOT_ID_PATH, size=128).rstrip("\n")
434
435   return outputarray
436
437
438 def VerifyNode(what, cluster_name):
439   """Verify the status of the local node.
440
441   Based on the input L{what} parameter, various checks are done on the
442   local node.
443
444   If the I{filelist} key is present, this list of
445   files is checksummed and the file/checksum pairs are returned.
446
447   If the I{nodelist} key is present, we check that we have
448   connectivity via ssh with the target nodes (and check the hostname
449   report).
450
451   If the I{node-net-test} key is present, we check that we have
452   connectivity to the given nodes via both primary IP and, if
453   applicable, secondary IPs.
454
455   @type what: C{dict}
456   @param what: a dictionary of things to check:
457       - filelist: list of files for which to compute checksums
458       - nodelist: list of nodes we should check ssh communication with
459       - node-net-test: list of nodes we should check node daemon port
460         connectivity with
461       - hypervisor: list with hypervisors to run the verify for
462   @rtype: dict
463   @return: a dictionary with the same keys as the input dict, and
464       values representing the result of the checks
465
466   """
467   result = {}
468
469   if constants.NV_HYPERVISOR in what:
470     result[constants.NV_HYPERVISOR] = tmp = {}
471     for hv_name in what[constants.NV_HYPERVISOR]:
472       tmp[hv_name] = hypervisor.GetHypervisor(hv_name).Verify()
473
474   if constants.NV_FILELIST in what:
475     result[constants.NV_FILELIST] = utils.FingerprintFiles(
476       what[constants.NV_FILELIST])
477
478   if constants.NV_NODELIST in what:
479     result[constants.NV_NODELIST] = tmp = {}
480     random.shuffle(what[constants.NV_NODELIST])
481     for node in what[constants.NV_NODELIST]:
482       success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
483       if not success:
484         tmp[node] = message
485
486   if constants.NV_NODENETTEST in what:
487     result[constants.NV_NODENETTEST] = tmp = {}
488     my_name = utils.HostInfo().name
489     my_pip = my_sip = None
490     for name, pip, sip in what[constants.NV_NODENETTEST]:
491       if name == my_name:
492         my_pip = pip
493         my_sip = sip
494         break
495     if not my_pip:
496       tmp[my_name] = ("Can't find my own primary/secondary IP"
497                       " in the node list")
498     else:
499       port = utils.GetDaemonPort(constants.NODED)
500       for name, pip, sip in what[constants.NV_NODENETTEST]:
501         fail = []
502         if not utils.TcpPing(pip, port, source=my_pip):
503           fail.append("primary")
504         if sip != pip:
505           if not utils.TcpPing(sip, port, source=my_sip):
506             fail.append("secondary")
507         if fail:
508           tmp[name] = ("failure using the %s interface(s)" %
509                        " and ".join(fail))
510
511   if constants.NV_LVLIST in what:
512     result[constants.NV_LVLIST] = GetVolumeList(what[constants.NV_LVLIST])
513
514   if constants.NV_INSTANCELIST in what:
515     result[constants.NV_INSTANCELIST] = GetInstanceList(
516       what[constants.NV_INSTANCELIST])
517
518   if constants.NV_VGLIST in what:
519     result[constants.NV_VGLIST] = utils.ListVolumeGroups()
520
521   if constants.NV_PVLIST in what:
522     result[constants.NV_PVLIST] = \
523       bdev.LogicalVolume.GetPVInfo(what[constants.NV_PVLIST],
524                                    filter_allocatable=False)
525
526   if constants.NV_VERSION in what:
527     result[constants.NV_VERSION] = (constants.PROTOCOL_VERSION,
528                                     constants.RELEASE_VERSION)
529
530   if constants.NV_HVINFO in what:
531     hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
532     result[constants.NV_HVINFO] = hyper.GetNodeInfo()
533
534   if constants.NV_DRBDLIST in what:
535     try:
536       used_minors = bdev.DRBD8.GetUsedDevs().keys()
537     except errors.BlockDeviceError, err:
538       logging.warning("Can't get used minors list", exc_info=True)
539       used_minors = str(err)
540     result[constants.NV_DRBDLIST] = used_minors
541
542   if constants.NV_NODESETUP in what:
543     result[constants.NV_NODESETUP] = tmpr = []
544     if not os.path.isdir("/sys/block") or not os.path.isdir("/sys/class/net"):
545       tmpr.append("The sysfs filesytem doesn't seem to be mounted"
546                   " under /sys, missing required directories /sys/block"
547                   " and /sys/class/net")
548     if (not os.path.isdir("/proc/sys") or
549         not os.path.isfile("/proc/sysrq-trigger")):
550       tmpr.append("The procfs filesystem doesn't seem to be mounted"
551                   " under /proc, missing required directory /proc/sys and"
552                   " the file /proc/sysrq-trigger")
553
554   if constants.NV_TIME in what:
555     result[constants.NV_TIME] = utils.SplitTime(time.time())
556
557   return result
558
559
560 def GetVolumeList(vg_name):
561   """Compute list of logical volumes and their size.
562
563   @type vg_name: str
564   @param vg_name: the volume group whose LVs we should list
565   @rtype: dict
566   @return:
567       dictionary of all partions (key) with value being a tuple of
568       their size (in MiB), inactive and online status::
569
570         {'test1': ('20.06', True, True)}
571
572       in case of errors, a string is returned with the error
573       details.
574
575   """
576   lvs = {}
577   sep = '|'
578   result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
579                          "--separator=%s" % sep,
580                          "-olv_name,lv_size,lv_attr", vg_name])
581   if result.failed:
582     _Fail("Failed to list logical volumes, lvs output: %s", result.output)
583
584   valid_line_re = re.compile("^ *([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
585   for line in result.stdout.splitlines():
586     line = line.strip()
587     match = valid_line_re.match(line)
588     if not match:
589       logging.error("Invalid line returned from lvs output: '%s'", line)
590       continue
591     name, size, attr = match.groups()
592     inactive = attr[4] == '-'
593     online = attr[5] == 'o'
594     virtual = attr[0] == 'v'
595     if virtual:
596       # we don't want to report such volumes as existing, since they
597       # don't really hold data
598       continue
599     lvs[name] = (size, inactive, online)
600
601   return lvs
602
603
604 def ListVolumeGroups():
605   """List the volume groups and their size.
606
607   @rtype: dict
608   @return: dictionary with keys volume name and values the
609       size of the volume
610
611   """
612   return utils.ListVolumeGroups()
613
614
615 def NodeVolumes():
616   """List all volumes on this node.
617
618   @rtype: list
619   @return:
620     A list of dictionaries, each having four keys:
621       - name: the logical volume name,
622       - size: the size of the logical volume
623       - dev: the physical device on which the LV lives
624       - vg: the volume group to which it belongs
625
626     In case of errors, we return an empty list and log the
627     error.
628
629     Note that since a logical volume can live on multiple physical
630     volumes, the resulting list might include a logical volume
631     multiple times.
632
633   """
634   result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
635                          "--separator=|",
636                          "--options=lv_name,lv_size,devices,vg_name"])
637   if result.failed:
638     _Fail("Failed to list logical volumes, lvs output: %s",
639           result.output)
640
641   def parse_dev(dev):
642     if '(' in dev:
643       return dev.split('(')[0]
644     else:
645       return dev
646
647   def map_line(line):
648     return {
649       'name': line[0].strip(),
650       'size': line[1].strip(),
651       'dev': parse_dev(line[2].strip()),
652       'vg': line[3].strip(),
653     }
654
655   return [map_line(line.split('|')) for line in result.stdout.splitlines()
656           if line.count('|') >= 3]
657
658
659 def BridgesExist(bridges_list):
660   """Check if a list of bridges exist on the current node.
661
662   @rtype: boolean
663   @return: C{True} if all of them exist, C{False} otherwise
664
665   """
666   missing = []
667   for bridge in bridges_list:
668     if not utils.BridgeExists(bridge):
669       missing.append(bridge)
670
671   if missing:
672     _Fail("Missing bridges %s", utils.CommaJoin(missing))
673
674
675 def GetInstanceList(hypervisor_list):
676   """Provides a list of instances.
677
678   @type hypervisor_list: list
679   @param hypervisor_list: the list of hypervisors to query information
680
681   @rtype: list
682   @return: a list of all running instances on the current node
683     - instance1.example.com
684     - instance2.example.com
685
686   """
687   results = []
688   for hname in hypervisor_list:
689     try:
690       names = hypervisor.GetHypervisor(hname).ListInstances()
691       results.extend(names)
692     except errors.HypervisorError, err:
693       _Fail("Error enumerating instances (hypervisor %s): %s",
694             hname, err, exc=True)
695
696   return results
697
698
699 def GetInstanceInfo(instance, hname):
700   """Gives back the information about an instance as a dictionary.
701
702   @type instance: string
703   @param instance: the instance name
704   @type hname: string
705   @param hname: the hypervisor type of the instance
706
707   @rtype: dict
708   @return: dictionary with the following keys:
709       - memory: memory size of instance (int)
710       - state: xen state of instance (string)
711       - time: cpu time of instance (float)
712
713   """
714   output = {}
715
716   iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
717   if iinfo is not None:
718     output['memory'] = iinfo[2]
719     output['state'] = iinfo[4]
720     output['time'] = iinfo[5]
721
722   return output
723
724
725 def GetInstanceMigratable(instance):
726   """Gives whether an instance can be migrated.
727
728   @type instance: L{objects.Instance}
729   @param instance: object representing the instance to be checked.
730
731   @rtype: tuple
732   @return: tuple of (result, description) where:
733       - result: whether the instance can be migrated or not
734       - description: a description of the issue, if relevant
735
736   """
737   hyper = hypervisor.GetHypervisor(instance.hypervisor)
738   iname = instance.name
739   if iname not in hyper.ListInstances():
740     _Fail("Instance %s is not running", iname)
741
742   for idx in range(len(instance.disks)):
743     link_name = _GetBlockDevSymlinkPath(iname, idx)
744     if not os.path.islink(link_name):
745       _Fail("Instance %s was not restarted since ganeti 1.2.5", iname)
746
747
748 def GetAllInstancesInfo(hypervisor_list):
749   """Gather data about all instances.
750
751   This is the equivalent of L{GetInstanceInfo}, except that it
752   computes data for all instances at once, thus being faster if one
753   needs data about more than one instance.
754
755   @type hypervisor_list: list
756   @param hypervisor_list: list of hypervisors to query for instance data
757
758   @rtype: dict
759   @return: dictionary of instance: data, with data having the following keys:
760       - memory: memory size of instance (int)
761       - state: xen state of instance (string)
762       - time: cpu time of instance (float)
763       - vcpus: the number of vcpus
764
765   """
766   output = {}
767
768   for hname in hypervisor_list:
769     iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
770     if iinfo:
771       for name, _, memory, vcpus, state, times in iinfo:
772         value = {
773           'memory': memory,
774           'vcpus': vcpus,
775           'state': state,
776           'time': times,
777           }
778         if name in output:
779           # we only check static parameters, like memory and vcpus,
780           # and not state and time which can change between the
781           # invocations of the different hypervisors
782           for key in 'memory', 'vcpus':
783             if value[key] != output[name][key]:
784               _Fail("Instance %s is running twice"
785                     " with different parameters", name)
786         output[name] = value
787
788   return output
789
790
791 def InstanceOsAdd(instance, reinstall, debug):
792   """Add an OS to an instance.
793
794   @type instance: L{objects.Instance}
795   @param instance: Instance whose OS is to be installed
796   @type reinstall: boolean
797   @param reinstall: whether this is an instance reinstall
798   @type debug: integer
799   @param debug: debug level, passed to the OS scripts
800   @rtype: None
801
802   """
803   inst_os = OSFromDisk(instance.os)
804
805   create_env = OSEnvironment(instance, inst_os, debug)
806   if reinstall:
807     create_env['INSTANCE_REINSTALL'] = "1"
808
809   logfile = "%s/add-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
810                                      instance.name, int(time.time()))
811
812   result = utils.RunCmd([inst_os.create_script], env=create_env,
813                         cwd=inst_os.path, output=logfile,)
814   if result.failed:
815     logging.error("os create command '%s' returned error: %s, logfile: %s,"
816                   " output: %s", result.cmd, result.fail_reason, logfile,
817                   result.output)
818     lines = [utils.SafeEncode(val)
819              for val in utils.TailFile(logfile, lines=20)]
820     _Fail("OS create script failed (%s), last lines in the"
821           " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
822
823
824 def RunRenameInstance(instance, old_name, debug):
825   """Run the OS rename script for an instance.
826
827   @type instance: L{objects.Instance}
828   @param instance: Instance whose OS is to be installed
829   @type old_name: string
830   @param old_name: previous instance name
831   @type debug: integer
832   @param debug: debug level, passed to the OS scripts
833   @rtype: boolean
834   @return: the success of the operation
835
836   """
837   inst_os = OSFromDisk(instance.os)
838
839   rename_env = OSEnvironment(instance, inst_os, debug)
840   rename_env['OLD_INSTANCE_NAME'] = old_name
841
842   logfile = "%s/rename-%s-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
843                                            old_name,
844                                            instance.name, int(time.time()))
845
846   result = utils.RunCmd([inst_os.rename_script], env=rename_env,
847                         cwd=inst_os.path, output=logfile)
848
849   if result.failed:
850     logging.error("os create command '%s' returned error: %s output: %s",
851                   result.cmd, result.fail_reason, result.output)
852     lines = [utils.SafeEncode(val)
853              for val in utils.TailFile(logfile, lines=20)]
854     _Fail("OS rename script failed (%s), last lines in the"
855           " log file:\n%s", result.fail_reason, "\n".join(lines), log=False)
856
857
858 def _GetVGInfo(vg_name):
859   """Get information about the volume group.
860
861   @type vg_name: str
862   @param vg_name: the volume group which we query
863   @rtype: dict
864   @return:
865     A dictionary with the following keys:
866       - C{vg_size} is the total size of the volume group in MiB
867       - C{vg_free} is the free size of the volume group in MiB
868       - C{pv_count} are the number of physical disks in that VG
869
870     If an error occurs during gathering of data, we return the same dict
871     with keys all set to None.
872
873   """
874   retdic = dict.fromkeys(["vg_size", "vg_free", "pv_count"])
875
876   retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings",
877                          "--nosuffix", "--units=m", "--separator=:", vg_name])
878
879   if retval.failed:
880     logging.error("volume group %s not present", vg_name)
881     return retdic
882   valarr = retval.stdout.strip().rstrip(':').split(':')
883   if len(valarr) == 3:
884     try:
885       retdic = {
886         "vg_size": int(round(float(valarr[0]), 0)),
887         "vg_free": int(round(float(valarr[1]), 0)),
888         "pv_count": int(valarr[2]),
889         }
890     except (TypeError, ValueError), err:
891       logging.exception("Fail to parse vgs output: %s", err)
892   else:
893     logging.error("vgs output has the wrong number of fields (expected"
894                   " three): %s", str(valarr))
895   return retdic
896
897
898 def _GetBlockDevSymlinkPath(instance_name, idx):
899   return os.path.join(constants.DISK_LINKS_DIR,
900                       "%s:%d" % (instance_name, idx))
901
902
903 def _SymlinkBlockDev(instance_name, device_path, idx):
904   """Set up symlinks to a instance's block device.
905
906   This is an auxiliary function run when an instance is start (on the primary
907   node) or when an instance is migrated (on the target node).
908
909
910   @param instance_name: the name of the target instance
911   @param device_path: path of the physical block device, on the node
912   @param idx: the disk index
913   @return: absolute path to the disk's symlink
914
915   """
916   link_name = _GetBlockDevSymlinkPath(instance_name, idx)
917   try:
918     os.symlink(device_path, link_name)
919   except OSError, err:
920     if err.errno == errno.EEXIST:
921       if (not os.path.islink(link_name) or
922           os.readlink(link_name) != device_path):
923         os.remove(link_name)
924         os.symlink(device_path, link_name)
925     else:
926       raise
927
928   return link_name
929
930
931 def _RemoveBlockDevLinks(instance_name, disks):
932   """Remove the block device symlinks belonging to the given instance.
933
934   """
935   for idx, _ in enumerate(disks):
936     link_name = _GetBlockDevSymlinkPath(instance_name, idx)
937     if os.path.islink(link_name):
938       try:
939         os.remove(link_name)
940       except OSError:
941         logging.exception("Can't remove symlink '%s'", link_name)
942
943
944 def _GatherAndLinkBlockDevs(instance):
945   """Set up an instance's block device(s).
946
947   This is run on the primary node at instance startup. The block
948   devices must be already assembled.
949
950   @type instance: L{objects.Instance}
951   @param instance: the instance whose disks we shoul assemble
952   @rtype: list
953   @return: list of (disk_object, device_path)
954
955   """
956   block_devices = []
957   for idx, disk in enumerate(instance.disks):
958     device = _RecursiveFindBD(disk)
959     if device is None:
960       raise errors.BlockDeviceError("Block device '%s' is not set up." %
961                                     str(disk))
962     device.Open()
963     try:
964       link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
965     except OSError, e:
966       raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
967                                     e.strerror)
968
969     block_devices.append((disk, link_name))
970
971   return block_devices
972
973
974 def StartInstance(instance):
975   """Start an instance.
976
977   @type instance: L{objects.Instance}
978   @param instance: the instance object
979   @rtype: None
980
981   """
982   running_instances = GetInstanceList([instance.hypervisor])
983
984   if instance.name in running_instances:
985     logging.info("Instance %s already running, not starting", instance.name)
986     return
987
988   try:
989     block_devices = _GatherAndLinkBlockDevs(instance)
990     hyper = hypervisor.GetHypervisor(instance.hypervisor)
991     hyper.StartInstance(instance, block_devices)
992   except errors.BlockDeviceError, err:
993     _Fail("Block device error: %s", err, exc=True)
994   except errors.HypervisorError, err:
995     _RemoveBlockDevLinks(instance.name, instance.disks)
996     _Fail("Hypervisor error: %s", err, exc=True)
997
998
999 def InstanceShutdown(instance, timeout):
1000   """Shut an instance down.
1001
1002   @note: this functions uses polling with a hardcoded timeout.
1003
1004   @type instance: L{objects.Instance}
1005   @param instance: the instance object
1006   @type timeout: integer
1007   @param timeout: maximum timeout for soft shutdown
1008   @rtype: None
1009
1010   """
1011   hv_name = instance.hypervisor
1012   hyper = hypervisor.GetHypervisor(hv_name)
1013   iname = instance.name
1014
1015   if instance.name not in hyper.ListInstances():
1016     logging.info("Instance %s not running, doing nothing", iname)
1017     return
1018
1019   class _TryShutdown:
1020     def __init__(self):
1021       self.tried_once = False
1022
1023     def __call__(self):
1024       if iname not in hyper.ListInstances():
1025         return
1026
1027       try:
1028         hyper.StopInstance(instance, retry=self.tried_once)
1029       except errors.HypervisorError, err:
1030         if iname not in hyper.ListInstances():
1031           # if the instance is no longer existing, consider this a
1032           # success and go to cleanup
1033           return
1034
1035         _Fail("Failed to stop instance %s: %s", iname, err)
1036
1037       self.tried_once = True
1038
1039       raise utils.RetryAgain()
1040
1041   try:
1042     utils.Retry(_TryShutdown(), 5, timeout)
1043   except utils.RetryTimeout:
1044     # the shutdown did not succeed
1045     logging.error("Shutdown of '%s' unsuccessful, forcing", iname)
1046
1047     try:
1048       hyper.StopInstance(instance, force=True)
1049     except errors.HypervisorError, err:
1050       if iname in hyper.ListInstances():
1051         # only raise an error if the instance still exists, otherwise
1052         # the error could simply be "instance ... unknown"!
1053         _Fail("Failed to force stop instance %s: %s", iname, err)
1054
1055     time.sleep(1)
1056
1057     if iname in hyper.ListInstances():
1058       _Fail("Could not shutdown instance %s even by destroy", iname)
1059
1060   _RemoveBlockDevLinks(iname, instance.disks)
1061
1062
1063 def InstanceReboot(instance, reboot_type, shutdown_timeout):
1064   """Reboot an instance.
1065
1066   @type instance: L{objects.Instance}
1067   @param instance: the instance object to reboot
1068   @type reboot_type: str
1069   @param reboot_type: the type of reboot, one the following
1070     constants:
1071       - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
1072         instance OS, do not recreate the VM
1073       - L{constants.INSTANCE_REBOOT_HARD}: tear down and
1074         restart the VM (at the hypervisor level)
1075       - the other reboot type (L{constants.INSTANCE_REBOOT_FULL}) is
1076         not accepted here, since that mode is handled differently, in
1077         cmdlib, and translates into full stop and start of the
1078         instance (instead of a call_instance_reboot RPC)
1079   @type shutdown_timeout: integer
1080   @param shutdown_timeout: maximum timeout for soft shutdown
1081   @rtype: None
1082
1083   """
1084   running_instances = GetInstanceList([instance.hypervisor])
1085
1086   if instance.name not in running_instances:
1087     _Fail("Cannot reboot instance %s that is not running", instance.name)
1088
1089   hyper = hypervisor.GetHypervisor(instance.hypervisor)
1090   if reboot_type == constants.INSTANCE_REBOOT_SOFT:
1091     try:
1092       hyper.RebootInstance(instance)
1093     except errors.HypervisorError, err:
1094       _Fail("Failed to soft reboot instance %s: %s", instance.name, err)
1095   elif reboot_type == constants.INSTANCE_REBOOT_HARD:
1096     try:
1097       InstanceShutdown(instance, shutdown_timeout)
1098       return StartInstance(instance)
1099     except errors.HypervisorError, err:
1100       _Fail("Failed to hard reboot instance %s: %s", instance.name, err)
1101   else:
1102     _Fail("Invalid reboot_type received: %s", reboot_type)
1103
1104
1105 def MigrationInfo(instance):
1106   """Gather information about an instance to be migrated.
1107
1108   @type instance: L{objects.Instance}
1109   @param instance: the instance definition
1110
1111   """
1112   hyper = hypervisor.GetHypervisor(instance.hypervisor)
1113   try:
1114     info = hyper.MigrationInfo(instance)
1115   except errors.HypervisorError, err:
1116     _Fail("Failed to fetch migration information: %s", err, exc=True)
1117   return info
1118
1119
1120 def AcceptInstance(instance, info, target):
1121   """Prepare the node to accept an instance.
1122
1123   @type instance: L{objects.Instance}
1124   @param instance: the instance definition
1125   @type info: string/data (opaque)
1126   @param info: migration information, from the source node
1127   @type target: string
1128   @param target: target host (usually ip), on this node
1129
1130   """
1131   hyper = hypervisor.GetHypervisor(instance.hypervisor)
1132   try:
1133     hyper.AcceptInstance(instance, info, target)
1134   except errors.HypervisorError, err:
1135     _Fail("Failed to accept instance: %s", err, exc=True)
1136
1137
1138 def FinalizeMigration(instance, info, success):
1139   """Finalize any preparation to accept an instance.
1140
1141   @type instance: L{objects.Instance}
1142   @param instance: the instance definition
1143   @type info: string/data (opaque)
1144   @param info: migration information, from the source node
1145   @type success: boolean
1146   @param success: whether the migration was a success or a failure
1147
1148   """
1149   hyper = hypervisor.GetHypervisor(instance.hypervisor)
1150   try:
1151     hyper.FinalizeMigration(instance, info, success)
1152   except errors.HypervisorError, err:
1153     _Fail("Failed to finalize migration: %s", err, exc=True)
1154
1155
1156 def MigrateInstance(instance, target, live):
1157   """Migrates an instance to another node.
1158
1159   @type instance: L{objects.Instance}
1160   @param instance: the instance definition
1161   @type target: string
1162   @param target: the target node name
1163   @type live: boolean
1164   @param live: whether the migration should be done live or not (the
1165       interpretation of this parameter is left to the hypervisor)
1166   @rtype: tuple
1167   @return: a tuple of (success, msg) where:
1168       - succes is a boolean denoting the success/failure of the operation
1169       - msg is a string with details in case of failure
1170
1171   """
1172   hyper = hypervisor.GetHypervisor(instance.hypervisor)
1173
1174   try:
1175     hyper.MigrateInstance(instance, target, live)
1176   except errors.HypervisorError, err:
1177     _Fail("Failed to migrate instance: %s", err, exc=True)
1178
1179
1180 def BlockdevCreate(disk, size, owner, on_primary, info):
1181   """Creates a block device for an instance.
1182
1183   @type disk: L{objects.Disk}
1184   @param disk: the object describing the disk we should create
1185   @type size: int
1186   @param size: the size of the physical underlying device, in MiB
1187   @type owner: str
1188   @param owner: the name of the instance for which disk is created,
1189       used for device cache data
1190   @type on_primary: boolean
1191   @param on_primary:  indicates if it is the primary node or not
1192   @type info: string
1193   @param info: string that will be sent to the physical device
1194       creation, used for example to set (LVM) tags on LVs
1195
1196   @return: the new unique_id of the device (this can sometime be
1197       computed only after creation), or None. On secondary nodes,
1198       it's not required to return anything.
1199
1200   """
1201   # TODO: remove the obsolete 'size' argument
1202   # pylint: disable-msg=W0613
1203   clist = []
1204   if disk.children:
1205     for child in disk.children:
1206       try:
1207         crdev = _RecursiveAssembleBD(child, owner, on_primary)
1208       except errors.BlockDeviceError, err:
1209         _Fail("Can't assemble device %s: %s", child, err)
1210       if on_primary or disk.AssembleOnSecondary():
1211         # we need the children open in case the device itself has to
1212         # be assembled
1213         try:
1214           # pylint: disable-msg=E1103
1215           crdev.Open()
1216         except errors.BlockDeviceError, err:
1217           _Fail("Can't make child '%s' read-write: %s", child, err)
1218       clist.append(crdev)
1219
1220   try:
1221     device = bdev.Create(disk.dev_type, disk.physical_id, clist, disk.size)
1222   except errors.BlockDeviceError, err:
1223     _Fail("Can't create block device: %s", err)
1224
1225   if on_primary or disk.AssembleOnSecondary():
1226     try:
1227       device.Assemble()
1228     except errors.BlockDeviceError, err:
1229       _Fail("Can't assemble device after creation, unusual event: %s", err)
1230     device.SetSyncSpeed(constants.SYNC_SPEED)
1231     if on_primary or disk.OpenOnSecondary():
1232       try:
1233         device.Open(force=True)
1234       except errors.BlockDeviceError, err:
1235         _Fail("Can't make device r/w after creation, unusual event: %s", err)
1236     DevCacheManager.UpdateCache(device.dev_path, owner,
1237                                 on_primary, disk.iv_name)
1238
1239   device.SetInfo(info)
1240
1241   return device.unique_id
1242
1243
1244 def BlockdevRemove(disk):
1245   """Remove a block device.
1246
1247   @note: This is intended to be called recursively.
1248
1249   @type disk: L{objects.Disk}
1250   @param disk: the disk object we should remove
1251   @rtype: boolean
1252   @return: the success of the operation
1253
1254   """
1255   msgs = []
1256   try:
1257     rdev = _RecursiveFindBD(disk)
1258   except errors.BlockDeviceError, err:
1259     # probably can't attach
1260     logging.info("Can't attach to device %s in remove", disk)
1261     rdev = None
1262   if rdev is not None:
1263     r_path = rdev.dev_path
1264     try:
1265       rdev.Remove()
1266     except errors.BlockDeviceError, err:
1267       msgs.append(str(err))
1268     if not msgs:
1269       DevCacheManager.RemoveCache(r_path)
1270
1271   if disk.children:
1272     for child in disk.children:
1273       try:
1274         BlockdevRemove(child)
1275       except RPCFail, err:
1276         msgs.append(str(err))
1277
1278   if msgs:
1279     _Fail("; ".join(msgs))
1280
1281
1282 def _RecursiveAssembleBD(disk, owner, as_primary):
1283   """Activate a block device for an instance.
1284
1285   This is run on the primary and secondary nodes for an instance.
1286
1287   @note: this function is called recursively.
1288
1289   @type disk: L{objects.Disk}
1290   @param disk: the disk we try to assemble
1291   @type owner: str
1292   @param owner: the name of the instance which owns the disk
1293   @type as_primary: boolean
1294   @param as_primary: if we should make the block device
1295       read/write
1296
1297   @return: the assembled device or None (in case no device
1298       was assembled)
1299   @raise errors.BlockDeviceError: in case there is an error
1300       during the activation of the children or the device
1301       itself
1302
1303   """
1304   children = []
1305   if disk.children:
1306     mcn = disk.ChildrenNeeded()
1307     if mcn == -1:
1308       mcn = 0 # max number of Nones allowed
1309     else:
1310       mcn = len(disk.children) - mcn # max number of Nones
1311     for chld_disk in disk.children:
1312       try:
1313         cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1314       except errors.BlockDeviceError, err:
1315         if children.count(None) >= mcn:
1316           raise
1317         cdev = None
1318         logging.error("Error in child activation (but continuing): %s",
1319                       str(err))
1320       children.append(cdev)
1321
1322   if as_primary or disk.AssembleOnSecondary():
1323     r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children, disk.size)
1324     r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1325     result = r_dev
1326     if as_primary or disk.OpenOnSecondary():
1327       r_dev.Open()
1328     DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1329                                 as_primary, disk.iv_name)
1330
1331   else:
1332     result = True
1333   return result
1334
1335
1336 def BlockdevAssemble(disk, owner, as_primary):
1337   """Activate a block device for an instance.
1338
1339   This is a wrapper over _RecursiveAssembleBD.
1340
1341   @rtype: str or boolean
1342   @return: a C{/dev/...} path for primary nodes, and
1343       C{True} for secondary nodes
1344
1345   """
1346   try:
1347     result = _RecursiveAssembleBD(disk, owner, as_primary)
1348     if isinstance(result, bdev.BlockDev):
1349       # pylint: disable-msg=E1103
1350       result = result.dev_path
1351   except errors.BlockDeviceError, err:
1352     _Fail("Error while assembling disk: %s", err, exc=True)
1353
1354   return result
1355
1356
1357 def BlockdevShutdown(disk):
1358   """Shut down a block device.
1359
1360   First, if the device is assembled (Attach() is successful), then
1361   the device is shutdown. Then the children of the device are
1362   shutdown.
1363
1364   This function is called recursively. Note that we don't cache the
1365   children or such, as oppossed to assemble, shutdown of different
1366   devices doesn't require that the upper device was active.
1367
1368   @type disk: L{objects.Disk}
1369   @param disk: the description of the disk we should
1370       shutdown
1371   @rtype: None
1372
1373   """
1374   msgs = []
1375   r_dev = _RecursiveFindBD(disk)
1376   if r_dev is not None:
1377     r_path = r_dev.dev_path
1378     try:
1379       r_dev.Shutdown()
1380       DevCacheManager.RemoveCache(r_path)
1381     except errors.BlockDeviceError, err:
1382       msgs.append(str(err))
1383
1384   if disk.children:
1385     for child in disk.children:
1386       try:
1387         BlockdevShutdown(child)
1388       except RPCFail, err:
1389         msgs.append(str(err))
1390
1391   if msgs:
1392     _Fail("; ".join(msgs))
1393
1394
1395 def BlockdevAddchildren(parent_cdev, new_cdevs):
1396   """Extend a mirrored block device.
1397
1398   @type parent_cdev: L{objects.Disk}
1399   @param parent_cdev: the disk to which we should add children
1400   @type new_cdevs: list of L{objects.Disk}
1401   @param new_cdevs: the list of children which we should add
1402   @rtype: None
1403
1404   """
1405   parent_bdev = _RecursiveFindBD(parent_cdev)
1406   if parent_bdev is None:
1407     _Fail("Can't find parent device '%s' in add children", parent_cdev)
1408   new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1409   if new_bdevs.count(None) > 0:
1410     _Fail("Can't find new device(s) to add: %s:%s", new_bdevs, new_cdevs)
1411   parent_bdev.AddChildren(new_bdevs)
1412
1413
1414 def BlockdevRemovechildren(parent_cdev, new_cdevs):
1415   """Shrink a mirrored block device.
1416
1417   @type parent_cdev: L{objects.Disk}
1418   @param parent_cdev: the disk from which we should remove children
1419   @type new_cdevs: list of L{objects.Disk}
1420   @param new_cdevs: the list of children which we should remove
1421   @rtype: None
1422
1423   """
1424   parent_bdev = _RecursiveFindBD(parent_cdev)
1425   if parent_bdev is None:
1426     _Fail("Can't find parent device '%s' in remove children", parent_cdev)
1427   devs = []
1428   for disk in new_cdevs:
1429     rpath = disk.StaticDevPath()
1430     if rpath is None:
1431       bd = _RecursiveFindBD(disk)
1432       if bd is None:
1433         _Fail("Can't find device %s while removing children", disk)
1434       else:
1435         devs.append(bd.dev_path)
1436     else:
1437       devs.append(rpath)
1438   parent_bdev.RemoveChildren(devs)
1439
1440
1441 def BlockdevGetmirrorstatus(disks):
1442   """Get the mirroring status of a list of devices.
1443
1444   @type disks: list of L{objects.Disk}
1445   @param disks: the list of disks which we should query
1446   @rtype: disk
1447   @return:
1448       a list of (mirror_done, estimated_time) tuples, which
1449       are the result of L{bdev.BlockDev.CombinedSyncStatus}
1450   @raise errors.BlockDeviceError: if any of the disks cannot be
1451       found
1452
1453   """
1454   stats = []
1455   for dsk in disks:
1456     rbd = _RecursiveFindBD(dsk)
1457     if rbd is None:
1458       _Fail("Can't find device %s", dsk)
1459
1460     stats.append(rbd.CombinedSyncStatus())
1461
1462   return stats
1463
1464
1465 def _RecursiveFindBD(disk):
1466   """Check if a device is activated.
1467
1468   If so, return information about the real device.
1469
1470   @type disk: L{objects.Disk}
1471   @param disk: the disk object we need to find
1472
1473   @return: None if the device can't be found,
1474       otherwise the device instance
1475
1476   """
1477   children = []
1478   if disk.children:
1479     for chdisk in disk.children:
1480       children.append(_RecursiveFindBD(chdisk))
1481
1482   return bdev.FindDevice(disk.dev_type, disk.physical_id, children, disk.size)
1483
1484
1485 def BlockdevFind(disk):
1486   """Check if a device is activated.
1487
1488   If it is, return information about the real device.
1489
1490   @type disk: L{objects.Disk}
1491   @param disk: the disk to find
1492   @rtype: None or objects.BlockDevStatus
1493   @return: None if the disk cannot be found, otherwise a the current
1494            information
1495
1496   """
1497   try:
1498     rbd = _RecursiveFindBD(disk)
1499   except errors.BlockDeviceError, err:
1500     _Fail("Failed to find device: %s", err, exc=True)
1501
1502   if rbd is None:
1503     return None
1504
1505   return rbd.GetSyncStatus()
1506
1507
1508 def BlockdevGetsize(disks):
1509   """Computes the size of the given disks.
1510
1511   If a disk is not found, returns None instead.
1512
1513   @type disks: list of L{objects.Disk}
1514   @param disks: the list of disk to compute the size for
1515   @rtype: list
1516   @return: list with elements None if the disk cannot be found,
1517       otherwise the size
1518
1519   """
1520   result = []
1521   for cf in disks:
1522     try:
1523       rbd = _RecursiveFindBD(cf)
1524     except errors.BlockDeviceError:
1525       result.append(None)
1526       continue
1527     if rbd is None:
1528       result.append(None)
1529     else:
1530       result.append(rbd.GetActualSize())
1531   return result
1532
1533
1534 def BlockdevExport(disk, dest_node, dest_path, cluster_name):
1535   """Export a block device to a remote node.
1536
1537   @type disk: L{objects.Disk}
1538   @param disk: the description of the disk to export
1539   @type dest_node: str
1540   @param dest_node: the destination node to export to
1541   @type dest_path: str
1542   @param dest_path: the destination path on the target node
1543   @type cluster_name: str
1544   @param cluster_name: the cluster name, needed for SSH hostalias
1545   @rtype: None
1546
1547   """
1548   real_disk = _RecursiveFindBD(disk)
1549   if real_disk is None:
1550     _Fail("Block device '%s' is not set up", disk)
1551
1552   real_disk.Open()
1553
1554   # the block size on the read dd is 1MiB to match our units
1555   expcmd = utils.BuildShellCmd("set -e; set -o pipefail; "
1556                                "dd if=%s bs=1048576 count=%s",
1557                                real_disk.dev_path, str(disk.size))
1558
1559   # we set here a smaller block size as, due to ssh buffering, more
1560   # than 64-128k will mostly ignored; we use nocreat to fail if the
1561   # device is not already there or we pass a wrong path; we use
1562   # notrunc to no attempt truncate on an LV device; we use oflag=dsync
1563   # to not buffer too much memory; this means that at best, we flush
1564   # every 64k, which will not be very fast
1565   destcmd = utils.BuildShellCmd("dd of=%s conv=nocreat,notrunc bs=65536"
1566                                 " oflag=dsync", dest_path)
1567
1568   remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1569                                                    constants.GANETI_RUNAS,
1570                                                    destcmd)
1571
1572   # all commands have been checked, so we're safe to combine them
1573   command = '|'.join([expcmd, utils.ShellQuoteArgs(remotecmd)])
1574
1575   result = utils.RunCmd(["bash", "-c", command])
1576
1577   if result.failed:
1578     _Fail("Disk copy command '%s' returned error: %s"
1579           " output: %s", command, result.fail_reason, result.output)
1580
1581
1582 def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1583   """Write a file to the filesystem.
1584
1585   This allows the master to overwrite(!) a file. It will only perform
1586   the operation if the file belongs to a list of configuration files.
1587
1588   @type file_name: str
1589   @param file_name: the target file name
1590   @type data: str
1591   @param data: the new contents of the file
1592   @type mode: int
1593   @param mode: the mode to give the file (can be None)
1594   @type uid: int
1595   @param uid: the owner of the file (can be -1 for default)
1596   @type gid: int
1597   @param gid: the group of the file (can be -1 for default)
1598   @type atime: float
1599   @param atime: the atime to set on the file (can be None)
1600   @type mtime: float
1601   @param mtime: the mtime to set on the file (can be None)
1602   @rtype: None
1603
1604   """
1605   if not os.path.isabs(file_name):
1606     _Fail("Filename passed to UploadFile is not absolute: '%s'", file_name)
1607
1608   if file_name not in _ALLOWED_UPLOAD_FILES:
1609     _Fail("Filename passed to UploadFile not in allowed upload targets: '%s'",
1610           file_name)
1611
1612   raw_data = _Decompress(data)
1613
1614   utils.WriteFile(file_name, data=raw_data, mode=mode, uid=uid, gid=gid,
1615                   atime=atime, mtime=mtime)
1616
1617
1618 def WriteSsconfFiles(values):
1619   """Update all ssconf files.
1620
1621   Wrapper around the SimpleStore.WriteFiles.
1622
1623   """
1624   ssconf.SimpleStore().WriteFiles(values)
1625
1626
1627 def _ErrnoOrStr(err):
1628   """Format an EnvironmentError exception.
1629
1630   If the L{err} argument has an errno attribute, it will be looked up
1631   and converted into a textual C{E...} description. Otherwise the
1632   string representation of the error will be returned.
1633
1634   @type err: L{EnvironmentError}
1635   @param err: the exception to format
1636
1637   """
1638   if hasattr(err, 'errno'):
1639     detail = errno.errorcode[err.errno]
1640   else:
1641     detail = str(err)
1642   return detail
1643
1644
1645 def _OSOndiskAPIVersion(os_dir):
1646   """Compute and return the API version of a given OS.
1647
1648   This function will try to read the API version of the OS residing in
1649   the 'os_dir' directory.
1650
1651   @type os_dir: str
1652   @param os_dir: the directory in which we should look for the OS
1653   @rtype: tuple
1654   @return: tuple (status, data) with status denoting the validity and
1655       data holding either the vaid versions or an error message
1656
1657   """
1658   api_file = os.path.sep.join([os_dir, constants.OS_API_FILE])
1659
1660   try:
1661     st = os.stat(api_file)
1662   except EnvironmentError, err:
1663     return False, ("Required file '%s' not found under path %s: %s" %
1664                    (constants.OS_API_FILE, os_dir, _ErrnoOrStr(err)))
1665
1666   if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1667     return False, ("File '%s' in %s is not a regular file" %
1668                    (constants.OS_API_FILE, os_dir))
1669
1670   try:
1671     api_versions = utils.ReadFile(api_file).splitlines()
1672   except EnvironmentError, err:
1673     return False, ("Error while reading the API version file at %s: %s" %
1674                    (api_file, _ErrnoOrStr(err)))
1675
1676   try:
1677     api_versions = [int(version.strip()) for version in api_versions]
1678   except (TypeError, ValueError), err:
1679     return False, ("API version(s) can't be converted to integer: %s" %
1680                    str(err))
1681
1682   return True, api_versions
1683
1684
1685 def DiagnoseOS(top_dirs=None):
1686   """Compute the validity for all OSes.
1687
1688   @type top_dirs: list
1689   @param top_dirs: the list of directories in which to
1690       search (if not given defaults to
1691       L{constants.OS_SEARCH_PATH})
1692   @rtype: list of L{objects.OS}
1693   @return: a list of tuples (name, path, status, diagnose, variants)
1694       for all (potential) OSes under all search paths, where:
1695           - name is the (potential) OS name
1696           - path is the full path to the OS
1697           - status True/False is the validity of the OS
1698           - diagnose is the error message for an invalid OS, otherwise empty
1699           - variants is a list of supported OS variants, if any
1700
1701   """
1702   if top_dirs is None:
1703     top_dirs = constants.OS_SEARCH_PATH
1704
1705   result = []
1706   for dir_name in top_dirs:
1707     if os.path.isdir(dir_name):
1708       try:
1709         f_names = utils.ListVisibleFiles(dir_name)
1710       except EnvironmentError, err:
1711         logging.exception("Can't list the OS directory %s: %s", dir_name, err)
1712         break
1713       for name in f_names:
1714         os_path = os.path.sep.join([dir_name, name])
1715         status, os_inst = _TryOSFromDisk(name, base_dir=dir_name)
1716         if status:
1717           diagnose = ""
1718           variants = os_inst.supported_variants
1719         else:
1720           diagnose = os_inst
1721           variants = []
1722         result.append((name, os_path, status, diagnose, variants))
1723
1724   return result
1725
1726
1727 def _TryOSFromDisk(name, base_dir=None):
1728   """Create an OS instance from disk.
1729
1730   This function will return an OS instance if the given name is a
1731   valid OS name.
1732
1733   @type base_dir: string
1734   @keyword base_dir: Base directory containing OS installations.
1735                      Defaults to a search in all the OS_SEARCH_PATH dirs.
1736   @rtype: tuple
1737   @return: success and either the OS instance if we find a valid one,
1738       or error message
1739
1740   """
1741   if base_dir is None:
1742     os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1743   else:
1744     os_dir = utils.FindFile(name, [base_dir], os.path.isdir)
1745
1746   if os_dir is None:
1747     return False, "Directory for OS %s not found in search path" % name
1748
1749   status, api_versions = _OSOndiskAPIVersion(os_dir)
1750   if not status:
1751     # push the error up
1752     return status, api_versions
1753
1754   if not constants.OS_API_VERSIONS.intersection(api_versions):
1755     return False, ("API version mismatch for path '%s': found %s, want %s." %
1756                    (os_dir, api_versions, constants.OS_API_VERSIONS))
1757
1758   # OS Files dictionary, we will populate it with the absolute path names
1759   os_files = dict.fromkeys(constants.OS_SCRIPTS)
1760
1761   if max(api_versions) >= constants.OS_API_V15:
1762     os_files[constants.OS_VARIANTS_FILE] = ''
1763
1764   for filename in os_files:
1765     os_files[filename] = os.path.sep.join([os_dir, filename])
1766
1767     try:
1768       st = os.stat(os_files[filename])
1769     except EnvironmentError, err:
1770       return False, ("File '%s' under path '%s' is missing (%s)" %
1771                      (filename, os_dir, _ErrnoOrStr(err)))
1772
1773     if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1774       return False, ("File '%s' under path '%s' is not a regular file" %
1775                      (filename, os_dir))
1776
1777     if filename in constants.OS_SCRIPTS:
1778       if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1779         return False, ("File '%s' under path '%s' is not executable" %
1780                        (filename, os_dir))
1781
1782   variants = None
1783   if constants.OS_VARIANTS_FILE in os_files:
1784     variants_file = os_files[constants.OS_VARIANTS_FILE]
1785     try:
1786       variants = utils.ReadFile(variants_file).splitlines()
1787     except EnvironmentError, err:
1788       return False, ("Error while reading the OS variants file at %s: %s" %
1789                      (variants_file, _ErrnoOrStr(err)))
1790     if not variants:
1791       return False, ("No supported os variant found")
1792
1793   os_obj = objects.OS(name=name, path=os_dir,
1794                       create_script=os_files[constants.OS_SCRIPT_CREATE],
1795                       export_script=os_files[constants.OS_SCRIPT_EXPORT],
1796                       import_script=os_files[constants.OS_SCRIPT_IMPORT],
1797                       rename_script=os_files[constants.OS_SCRIPT_RENAME],
1798                       supported_variants=variants,
1799                       api_versions=api_versions)
1800   return True, os_obj
1801
1802
1803 def OSFromDisk(name, base_dir=None):
1804   """Create an OS instance from disk.
1805
1806   This function will return an OS instance if the given name is a
1807   valid OS name. Otherwise, it will raise an appropriate
1808   L{RPCFail} exception, detailing why this is not a valid OS.
1809
1810   This is just a wrapper over L{_TryOSFromDisk}, which doesn't raise
1811   an exception but returns true/false status data.
1812
1813   @type base_dir: string
1814   @keyword base_dir: Base directory containing OS installations.
1815                      Defaults to a search in all the OS_SEARCH_PATH dirs.
1816   @rtype: L{objects.OS}
1817   @return: the OS instance if we find a valid one
1818   @raise RPCFail: if we don't find a valid OS
1819
1820   """
1821   name_only = name.split("+", 1)[0]
1822   status, payload = _TryOSFromDisk(name_only, base_dir)
1823
1824   if not status:
1825     _Fail(payload)
1826
1827   return payload
1828
1829
1830 def OSEnvironment(instance, inst_os, debug=0):
1831   """Calculate the environment for an os script.
1832
1833   @type instance: L{objects.Instance}
1834   @param instance: target instance for the os script run
1835   @type inst_os: L{objects.OS}
1836   @param inst_os: operating system for which the environment is being built
1837   @type debug: integer
1838   @param debug: debug level (0 or 1, for OS Api 10)
1839   @rtype: dict
1840   @return: dict of environment variables
1841   @raise errors.BlockDeviceError: if the block device
1842       cannot be found
1843
1844   """
1845   result = {}
1846   api_version = \
1847     max(constants.OS_API_VERSIONS.intersection(inst_os.api_versions))
1848   result['OS_API_VERSION'] = '%d' % api_version
1849   result['INSTANCE_NAME'] = instance.name
1850   result['INSTANCE_OS'] = instance.os
1851   result['HYPERVISOR'] = instance.hypervisor
1852   result['DISK_COUNT'] = '%d' % len(instance.disks)
1853   result['NIC_COUNT'] = '%d' % len(instance.nics)
1854   result['DEBUG_LEVEL'] = '%d' % debug
1855   if api_version >= constants.OS_API_V15:
1856     try:
1857       variant = instance.os.split('+', 1)[1]
1858     except IndexError:
1859       variant = inst_os.supported_variants[0]
1860     result['OS_VARIANT'] = variant
1861   for idx, disk in enumerate(instance.disks):
1862     real_disk = _RecursiveFindBD(disk)
1863     if real_disk is None:
1864       raise errors.BlockDeviceError("Block device '%s' is not set up" %
1865                                     str(disk))
1866     real_disk.Open()
1867     result['DISK_%d_PATH' % idx] = real_disk.dev_path
1868     result['DISK_%d_ACCESS' % idx] = disk.mode
1869     if constants.HV_DISK_TYPE in instance.hvparams:
1870       result['DISK_%d_FRONTEND_TYPE' % idx] = \
1871         instance.hvparams[constants.HV_DISK_TYPE]
1872     if disk.dev_type in constants.LDS_BLOCK:
1873       result['DISK_%d_BACKEND_TYPE' % idx] = 'block'
1874     elif disk.dev_type == constants.LD_FILE:
1875       result['DISK_%d_BACKEND_TYPE' % idx] = \
1876         'file:%s' % disk.physical_id[0]
1877   for idx, nic in enumerate(instance.nics):
1878     result['NIC_%d_MAC' % idx] = nic.mac
1879     if nic.ip:
1880       result['NIC_%d_IP' % idx] = nic.ip
1881     result['NIC_%d_MODE' % idx] = nic.nicparams[constants.NIC_MODE]
1882     if nic.nicparams[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
1883       result['NIC_%d_BRIDGE' % idx] = nic.nicparams[constants.NIC_LINK]
1884     if nic.nicparams[constants.NIC_LINK]:
1885       result['NIC_%d_LINK' % idx] = nic.nicparams[constants.NIC_LINK]
1886     if constants.HV_NIC_TYPE in instance.hvparams:
1887       result['NIC_%d_FRONTEND_TYPE' % idx] = \
1888         instance.hvparams[constants.HV_NIC_TYPE]
1889
1890   for source, kind in [(instance.beparams, "BE"), (instance.hvparams, "HV")]:
1891     for key, value in source.items():
1892       result["INSTANCE_%s_%s" % (kind, key)] = str(value)
1893
1894   return result
1895
1896 def BlockdevGrow(disk, amount):
1897   """Grow a stack of block devices.
1898
1899   This function is called recursively, with the childrens being the
1900   first ones to resize.
1901
1902   @type disk: L{objects.Disk}
1903   @param disk: the disk to be grown
1904   @rtype: (status, result)
1905   @return: a tuple with the status of the operation
1906       (True/False), and the errors message if status
1907       is False
1908
1909   """
1910   r_dev = _RecursiveFindBD(disk)
1911   if r_dev is None:
1912     _Fail("Cannot find block device %s", disk)
1913
1914   try:
1915     r_dev.Grow(amount)
1916   except errors.BlockDeviceError, err:
1917     _Fail("Failed to grow block device: %s", err, exc=True)
1918
1919
1920 def BlockdevSnapshot(disk):
1921   """Create a snapshot copy of a block device.
1922
1923   This function is called recursively, and the snapshot is actually created
1924   just for the leaf lvm backend device.
1925
1926   @type disk: L{objects.Disk}
1927   @param disk: the disk to be snapshotted
1928   @rtype: string
1929   @return: snapshot disk path
1930
1931   """
1932   if disk.dev_type == constants.LD_DRBD8:
1933     if not disk.children:
1934       _Fail("DRBD device '%s' without backing storage cannot be snapshotted",
1935             disk.unique_id)
1936     return BlockdevSnapshot(disk.children[0])
1937   elif disk.dev_type == constants.LD_LV:
1938     r_dev = _RecursiveFindBD(disk)
1939     if r_dev is not None:
1940       # FIXME: choose a saner value for the snapshot size
1941       # let's stay on the safe side and ask for the full size, for now
1942       return r_dev.Snapshot(disk.size)
1943     else:
1944       _Fail("Cannot find block device %s", disk)
1945   else:
1946     _Fail("Cannot snapshot non-lvm block device '%s' of type '%s'",
1947           disk.unique_id, disk.dev_type)
1948
1949
1950 def ExportSnapshot(disk, dest_node, instance, cluster_name, idx, debug):
1951   """Export a block device snapshot to a remote node.
1952
1953   @type disk: L{objects.Disk}
1954   @param disk: the description of the disk to export
1955   @type dest_node: str
1956   @param dest_node: the destination node to export to
1957   @type instance: L{objects.Instance}
1958   @param instance: the instance object to whom the disk belongs
1959   @type cluster_name: str
1960   @param cluster_name: the cluster name, needed for SSH hostalias
1961   @type idx: int
1962   @param idx: the index of the disk in the instance's disk list,
1963       used to export to the OS scripts environment
1964   @type debug: integer
1965   @param debug: debug level, passed to the OS scripts
1966   @rtype: None
1967
1968   """
1969   inst_os = OSFromDisk(instance.os)
1970   export_env = OSEnvironment(instance, inst_os, debug)
1971
1972   export_script = inst_os.export_script
1973
1974   logfile = "%s/exp-%s-%s-%s.log" % (constants.LOG_OS_DIR, inst_os.name,
1975                                      instance.name, int(time.time()))
1976   if not os.path.exists(constants.LOG_OS_DIR):
1977     os.mkdir(constants.LOG_OS_DIR, 0750)
1978   real_disk = _RecursiveFindBD(disk)
1979   if real_disk is None:
1980     _Fail("Block device '%s' is not set up", disk)
1981
1982   real_disk.Open()
1983
1984   export_env['EXPORT_DEVICE'] = real_disk.dev_path
1985   export_env['EXPORT_INDEX'] = str(idx)
1986
1987   destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1988   destfile = disk.physical_id[1]
1989
1990   # the target command is built out of three individual commands,
1991   # which are joined by pipes; we check each individual command for
1992   # valid parameters
1993   expcmd = utils.BuildShellCmd("set -e; set -o pipefail; cd %s; %s 2>%s",
1994                                inst_os.path, export_script, logfile)
1995
1996   comprcmd = "gzip"
1997
1998   destcmd = utils.BuildShellCmd("mkdir -p %s && cat > %s/%s",
1999                                 destdir, destdir, destfile)
2000   remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
2001                                                    constants.GANETI_RUNAS,
2002                                                    destcmd)
2003
2004   # all commands have been checked, so we're safe to combine them
2005   command = '|'.join([expcmd, comprcmd, utils.ShellQuoteArgs(remotecmd)])
2006
2007   result = utils.RunCmd(["bash", "-c", command], env=export_env)
2008
2009   if result.failed:
2010     _Fail("OS snapshot export command '%s' returned error: %s"
2011           " output: %s", command, result.fail_reason, result.output)
2012
2013
2014 def FinalizeExport(instance, snap_disks):
2015   """Write out the export configuration information.
2016
2017   @type instance: L{objects.Instance}
2018   @param instance: the instance which we export, used for
2019       saving configuration
2020   @type snap_disks: list of L{objects.Disk}
2021   @param snap_disks: list of snapshot block devices, which
2022       will be used to get the actual name of the dump file
2023
2024   @rtype: None
2025
2026   """
2027   destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
2028   finaldestdir = os.path.join(constants.EXPORT_DIR, instance.name)
2029
2030   config = objects.SerializableConfigParser()
2031
2032   config.add_section(constants.INISECT_EXP)
2033   config.set(constants.INISECT_EXP, 'version', '0')
2034   config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
2035   config.set(constants.INISECT_EXP, 'source', instance.primary_node)
2036   config.set(constants.INISECT_EXP, 'os', instance.os)
2037   config.set(constants.INISECT_EXP, 'compression', 'gzip')
2038
2039   config.add_section(constants.INISECT_INS)
2040   config.set(constants.INISECT_INS, 'name', instance.name)
2041   config.set(constants.INISECT_INS, 'memory', '%d' %
2042              instance.beparams[constants.BE_MEMORY])
2043   config.set(constants.INISECT_INS, 'vcpus', '%d' %
2044              instance.beparams[constants.BE_VCPUS])
2045   config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
2046
2047   nic_total = 0
2048   for nic_count, nic in enumerate(instance.nics):
2049     nic_total += 1
2050     config.set(constants.INISECT_INS, 'nic%d_mac' %
2051                nic_count, '%s' % nic.mac)
2052     config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
2053     config.set(constants.INISECT_INS, 'nic%d_bridge' % nic_count,
2054                '%s' % nic.bridge)
2055   # TODO: redundant: on load can read nics until it doesn't exist
2056   config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_total)
2057
2058   disk_total = 0
2059   for disk_count, disk in enumerate(snap_disks):
2060     if disk:
2061       disk_total += 1
2062       config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
2063                  ('%s' % disk.iv_name))
2064       config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
2065                  ('%s' % disk.physical_id[1]))
2066       config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
2067                  ('%d' % disk.size))
2068
2069   config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_total)
2070
2071   utils.WriteFile(os.path.join(destdir, constants.EXPORT_CONF_FILE),
2072                   data=config.Dumps())
2073   shutil.rmtree(finaldestdir, True)
2074   shutil.move(destdir, finaldestdir)
2075
2076
2077 def ExportInfo(dest):
2078   """Get export configuration information.
2079
2080   @type dest: str
2081   @param dest: directory containing the export
2082
2083   @rtype: L{objects.SerializableConfigParser}
2084   @return: a serializable config file containing the
2085       export info
2086
2087   """
2088   cff = os.path.join(dest, constants.EXPORT_CONF_FILE)
2089
2090   config = objects.SerializableConfigParser()
2091   config.read(cff)
2092
2093   if (not config.has_section(constants.INISECT_EXP) or
2094       not config.has_section(constants.INISECT_INS)):
2095     _Fail("Export info file doesn't have the required fields")
2096
2097   return config.Dumps()
2098
2099
2100 def ImportOSIntoInstance(instance, src_node, src_images, cluster_name, debug):
2101   """Import an os image into an instance.
2102
2103   @type instance: L{objects.Instance}
2104   @param instance: instance to import the disks into
2105   @type src_node: string
2106   @param src_node: source node for the disk images
2107   @type src_images: list of string
2108   @param src_images: absolute paths of the disk images
2109   @type debug: integer
2110   @param debug: debug level, passed to the OS scripts
2111   @rtype: list of boolean
2112   @return: each boolean represent the success of importing the n-th disk
2113
2114   """
2115   inst_os = OSFromDisk(instance.os)
2116   import_env = OSEnvironment(instance, inst_os, debug)
2117   import_script = inst_os.import_script
2118
2119   logfile = "%s/import-%s-%s-%s.log" % (constants.LOG_OS_DIR, instance.os,
2120                                         instance.name, int(time.time()))
2121   if not os.path.exists(constants.LOG_OS_DIR):
2122     os.mkdir(constants.LOG_OS_DIR, 0750)
2123
2124   comprcmd = "gunzip"
2125   impcmd = utils.BuildShellCmd("(cd %s; %s >%s 2>&1)", inst_os.path,
2126                                import_script, logfile)
2127
2128   final_result = []
2129   for idx, image in enumerate(src_images):
2130     if image:
2131       destcmd = utils.BuildShellCmd('cat %s', image)
2132       remotecmd = _GetSshRunner(cluster_name).BuildCmd(src_node,
2133                                                        constants.GANETI_RUNAS,
2134                                                        destcmd)
2135       command = '|'.join([utils.ShellQuoteArgs(remotecmd), comprcmd, impcmd])
2136       import_env['IMPORT_DEVICE'] = import_env['DISK_%d_PATH' % idx]
2137       import_env['IMPORT_INDEX'] = str(idx)
2138       result = utils.RunCmd(command, env=import_env)
2139       if result.failed:
2140         logging.error("Disk import command '%s' returned error: %s"
2141                       " output: %s", command, result.fail_reason,
2142                       result.output)
2143         final_result.append("error importing disk %d: %s, %s" %
2144                             (idx, result.fail_reason, result.output[-100]))
2145
2146   if final_result:
2147     _Fail("; ".join(final_result), log=False)
2148
2149
2150 def ListExports():
2151   """Return a list of exports currently available on this machine.
2152
2153   @rtype: list
2154   @return: list of the exports
2155
2156   """
2157   if os.path.isdir(constants.EXPORT_DIR):
2158     return utils.ListVisibleFiles(constants.EXPORT_DIR)
2159   else:
2160     _Fail("No exports directory")
2161
2162
2163 def RemoveExport(export):
2164   """Remove an existing export from the node.
2165
2166   @type export: str
2167   @param export: the name of the export to remove
2168   @rtype: None
2169
2170   """
2171   target = os.path.join(constants.EXPORT_DIR, export)
2172
2173   try:
2174     shutil.rmtree(target)
2175   except EnvironmentError, err:
2176     _Fail("Error while removing the export: %s", err, exc=True)
2177
2178
2179 def BlockdevRename(devlist):
2180   """Rename a list of block devices.
2181
2182   @type devlist: list of tuples
2183   @param devlist: list of tuples of the form  (disk,
2184       new_logical_id, new_physical_id); disk is an
2185       L{objects.Disk} object describing the current disk,
2186       and new logical_id/physical_id is the name we
2187       rename it to
2188   @rtype: boolean
2189   @return: True if all renames succeeded, False otherwise
2190
2191   """
2192   msgs = []
2193   result = True
2194   for disk, unique_id in devlist:
2195     dev = _RecursiveFindBD(disk)
2196     if dev is None:
2197       msgs.append("Can't find device %s in rename" % str(disk))
2198       result = False
2199       continue
2200     try:
2201       old_rpath = dev.dev_path
2202       dev.Rename(unique_id)
2203       new_rpath = dev.dev_path
2204       if old_rpath != new_rpath:
2205         DevCacheManager.RemoveCache(old_rpath)
2206         # FIXME: we should add the new cache information here, like:
2207         # DevCacheManager.UpdateCache(new_rpath, owner, ...)
2208         # but we don't have the owner here - maybe parse from existing
2209         # cache? for now, we only lose lvm data when we rename, which
2210         # is less critical than DRBD or MD
2211     except errors.BlockDeviceError, err:
2212       msgs.append("Can't rename device '%s' to '%s': %s" %
2213                   (dev, unique_id, err))
2214       logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
2215       result = False
2216   if not result:
2217     _Fail("; ".join(msgs))
2218
2219
2220 def _TransformFileStorageDir(file_storage_dir):
2221   """Checks whether given file_storage_dir is valid.
2222
2223   Checks wheter the given file_storage_dir is within the cluster-wide
2224   default file_storage_dir stored in SimpleStore. Only paths under that
2225   directory are allowed.
2226
2227   @type file_storage_dir: str
2228   @param file_storage_dir: the path to check
2229
2230   @return: the normalized path if valid, None otherwise
2231
2232   """
2233   cfg = _GetConfig()
2234   file_storage_dir = os.path.normpath(file_storage_dir)
2235   base_file_storage_dir = cfg.GetFileStorageDir()
2236   if (not os.path.commonprefix([file_storage_dir, base_file_storage_dir]) ==
2237       base_file_storage_dir):
2238     _Fail("File storage directory '%s' is not under base file"
2239           " storage directory '%s'", file_storage_dir, base_file_storage_dir)
2240   return file_storage_dir
2241
2242
2243 def CreateFileStorageDir(file_storage_dir):
2244   """Create file storage directory.
2245
2246   @type file_storage_dir: str
2247   @param file_storage_dir: directory to create
2248
2249   @rtype: tuple
2250   @return: tuple with first element a boolean indicating wheter dir
2251       creation was successful or not
2252
2253   """
2254   file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2255   if os.path.exists(file_storage_dir):
2256     if not os.path.isdir(file_storage_dir):
2257       _Fail("Specified storage dir '%s' is not a directory",
2258             file_storage_dir)
2259   else:
2260     try:
2261       os.makedirs(file_storage_dir, 0750)
2262     except OSError, err:
2263       _Fail("Cannot create file storage directory '%s': %s",
2264             file_storage_dir, err, exc=True)
2265
2266
2267 def RemoveFileStorageDir(file_storage_dir):
2268   """Remove file storage directory.
2269
2270   Remove it only if it's empty. If not log an error and return.
2271
2272   @type file_storage_dir: str
2273   @param file_storage_dir: the directory we should cleanup
2274   @rtype: tuple (success,)
2275   @return: tuple of one element, C{success}, denoting
2276       whether the operation was successful
2277
2278   """
2279   file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2280   if os.path.exists(file_storage_dir):
2281     if not os.path.isdir(file_storage_dir):
2282       _Fail("Specified Storage directory '%s' is not a directory",
2283             file_storage_dir)
2284     # deletes dir only if empty, otherwise we want to fail the rpc call
2285     try:
2286       os.rmdir(file_storage_dir)
2287     except OSError, err:
2288       _Fail("Cannot remove file storage directory '%s': %s",
2289             file_storage_dir, err)
2290
2291
2292 def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2293   """Rename the file storage directory.
2294
2295   @type old_file_storage_dir: str
2296   @param old_file_storage_dir: the current path
2297   @type new_file_storage_dir: str
2298   @param new_file_storage_dir: the name we should rename to
2299   @rtype: tuple (success,)
2300   @return: tuple of one element, C{success}, denoting
2301       whether the operation was successful
2302
2303   """
2304   old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2305   new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2306   if not os.path.exists(new_file_storage_dir):
2307     if os.path.isdir(old_file_storage_dir):
2308       try:
2309         os.rename(old_file_storage_dir, new_file_storage_dir)
2310       except OSError, err:
2311         _Fail("Cannot rename '%s' to '%s': %s",
2312               old_file_storage_dir, new_file_storage_dir, err)
2313     else:
2314       _Fail("Specified storage dir '%s' is not a directory",
2315             old_file_storage_dir)
2316   else:
2317     if os.path.exists(old_file_storage_dir):
2318       _Fail("Cannot rename '%s' to '%s': both locations exist",
2319             old_file_storage_dir, new_file_storage_dir)
2320
2321
2322 def _EnsureJobQueueFile(file_name):
2323   """Checks whether the given filename is in the queue directory.
2324
2325   @type file_name: str
2326   @param file_name: the file name we should check
2327   @rtype: None
2328   @raises RPCFail: if the file is not valid
2329
2330   """
2331   queue_dir = os.path.normpath(constants.QUEUE_DIR)
2332   result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2333
2334   if not result:
2335     _Fail("Passed job queue file '%s' does not belong to"
2336           " the queue directory '%s'", file_name, queue_dir)
2337
2338
2339 def JobQueueUpdate(file_name, content):
2340   """Updates a file in the queue directory.
2341
2342   This is just a wrapper over L{utils.WriteFile}, with proper
2343   checking.
2344
2345   @type file_name: str
2346   @param file_name: the job file name
2347   @type content: str
2348   @param content: the new job contents
2349   @rtype: boolean
2350   @return: the success of the operation
2351
2352   """
2353   _EnsureJobQueueFile(file_name)
2354
2355   # Write and replace the file atomically
2356   utils.WriteFile(file_name, data=_Decompress(content))
2357
2358
2359 def JobQueueRename(old, new):
2360   """Renames a job queue file.
2361
2362   This is just a wrapper over os.rename with proper checking.
2363
2364   @type old: str
2365   @param old: the old (actual) file name
2366   @type new: str
2367   @param new: the desired file name
2368   @rtype: tuple
2369   @return: the success of the operation and payload
2370
2371   """
2372   _EnsureJobQueueFile(old)
2373   _EnsureJobQueueFile(new)
2374
2375   utils.RenameFile(old, new, mkdir=True)
2376
2377
2378 def JobQueueSetDrainFlag(drain_flag):
2379   """Set the drain flag for the queue.
2380
2381   This will set or unset the queue drain flag.
2382
2383   @type drain_flag: boolean
2384   @param drain_flag: if True, will set the drain flag, otherwise reset it.
2385   @rtype: truple
2386   @return: always True, None
2387   @warning: the function always returns True
2388
2389   """
2390   if drain_flag:
2391     utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True)
2392   else:
2393     utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
2394
2395
2396 def BlockdevClose(instance_name, disks):
2397   """Closes the given block devices.
2398
2399   This means they will be switched to secondary mode (in case of
2400   DRBD).
2401
2402   @param instance_name: if the argument is not empty, the symlinks
2403       of this instance will be removed
2404   @type disks: list of L{objects.Disk}
2405   @param disks: the list of disks to be closed
2406   @rtype: tuple (success, message)
2407   @return: a tuple of success and message, where success
2408       indicates the succes of the operation, and message
2409       which will contain the error details in case we
2410       failed
2411
2412   """
2413   bdevs = []
2414   for cf in disks:
2415     rd = _RecursiveFindBD(cf)
2416     if rd is None:
2417       _Fail("Can't find device %s", cf)
2418     bdevs.append(rd)
2419
2420   msg = []
2421   for rd in bdevs:
2422     try:
2423       rd.Close()
2424     except errors.BlockDeviceError, err:
2425       msg.append(str(err))
2426   if msg:
2427     _Fail("Can't make devices secondary: %s", ",".join(msg))
2428   else:
2429     if instance_name:
2430       _RemoveBlockDevLinks(instance_name, disks)
2431
2432
2433 def ValidateHVParams(hvname, hvparams):
2434   """Validates the given hypervisor parameters.
2435
2436   @type hvname: string
2437   @param hvname: the hypervisor name
2438   @type hvparams: dict
2439   @param hvparams: the hypervisor parameters to be validated
2440   @rtype: None
2441
2442   """
2443   try:
2444     hv_type = hypervisor.GetHypervisor(hvname)
2445     hv_type.ValidateParameters(hvparams)
2446   except errors.HypervisorError, err:
2447     _Fail(str(err), log=False)
2448
2449
2450 def DemoteFromMC():
2451   """Demotes the current node from master candidate role.
2452
2453   """
2454   # try to ensure we're not the master by mistake
2455   master, myself = ssconf.GetMasterAndMyself()
2456   if master == myself:
2457     _Fail("ssconf status shows I'm the master node, will not demote")
2458
2459   result = utils.RunCmd([constants.DAEMON_UTIL, "check", constants.MASTERD])
2460   if not result.failed:
2461     _Fail("The master daemon is running, will not demote")
2462
2463   try:
2464     if os.path.isfile(constants.CLUSTER_CONF_FILE):
2465       utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2466   except EnvironmentError, err:
2467     if err.errno != errno.ENOENT:
2468       _Fail("Error while backing up cluster file: %s", err, exc=True)
2469
2470   utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2471
2472
2473 def _FindDisks(nodes_ip, disks):
2474   """Sets the physical ID on disks and returns the block devices.
2475
2476   """
2477   # set the correct physical ID
2478   my_name = utils.HostInfo().name
2479   for cf in disks:
2480     cf.SetPhysicalID(my_name, nodes_ip)
2481
2482   bdevs = []
2483
2484   for cf in disks:
2485     rd = _RecursiveFindBD(cf)
2486     if rd is None:
2487       _Fail("Can't find device %s", cf)
2488     bdevs.append(rd)
2489   return bdevs
2490
2491
2492 def DrbdDisconnectNet(nodes_ip, disks):
2493   """Disconnects the network on a list of drbd devices.
2494
2495   """
2496   bdevs = _FindDisks(nodes_ip, disks)
2497
2498   # disconnect disks
2499   for rd in bdevs:
2500     try:
2501       rd.DisconnectNet()
2502     except errors.BlockDeviceError, err:
2503       _Fail("Can't change network configuration to standalone mode: %s",
2504             err, exc=True)
2505
2506
2507 def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
2508   """Attaches the network on a list of drbd devices.
2509
2510   """
2511   bdevs = _FindDisks(nodes_ip, disks)
2512
2513   if multimaster:
2514     for idx, rd in enumerate(bdevs):
2515       try:
2516         _SymlinkBlockDev(instance_name, rd.dev_path, idx)
2517       except EnvironmentError, err:
2518         _Fail("Can't create symlink: %s", err)
2519   # reconnect disks, switch to new master configuration and if
2520   # needed primary mode
2521   for rd in bdevs:
2522     try:
2523       rd.AttachNet(multimaster)
2524     except errors.BlockDeviceError, err:
2525       _Fail("Can't change network configuration: %s", err)
2526
2527   # wait until the disks are connected; we need to retry the re-attach
2528   # if the device becomes standalone, as this might happen if the one
2529   # node disconnects and reconnects in a different mode before the
2530   # other node reconnects; in this case, one or both of the nodes will
2531   # decide it has wrong configuration and switch to standalone
2532
2533   def _Attach():
2534     all_connected = True
2535
2536     for rd in bdevs:
2537       stats = rd.GetProcStatus()
2538
2539       all_connected = (all_connected and
2540                        (stats.is_connected or stats.is_in_resync))
2541
2542       if stats.is_standalone:
2543         # peer had different config info and this node became
2544         # standalone, even though this should not happen with the
2545         # new staged way of changing disk configs
2546         try:
2547           rd.AttachNet(multimaster)
2548         except errors.BlockDeviceError, err:
2549           _Fail("Can't change network configuration: %s", err)
2550
2551     if not all_connected:
2552       raise utils.RetryAgain()
2553
2554   try:
2555     # Start with a delay of 100 miliseconds and go up to 5 seconds
2556     utils.Retry(_Attach, (0.1, 1.5, 5.0), 2 * 60)
2557   except utils.RetryTimeout:
2558     _Fail("Timeout in disk reconnecting")
2559
2560   if multimaster:
2561     # change to primary mode
2562     for rd in bdevs:
2563       try:
2564         rd.Open()
2565       except errors.BlockDeviceError, err:
2566         _Fail("Can't change to primary mode: %s", err)
2567
2568
2569 def DrbdWaitSync(nodes_ip, disks):
2570   """Wait until DRBDs have synchronized.
2571
2572   """
2573   def _helper(rd):
2574     stats = rd.GetProcStatus()
2575     if not (stats.is_connected or stats.is_in_resync):
2576       raise utils.RetryAgain()
2577     return stats
2578
2579   bdevs = _FindDisks(nodes_ip, disks)
2580
2581   min_resync = 100
2582   alldone = True
2583   for rd in bdevs:
2584     try:
2585       # poll each second for 15 seconds
2586       stats = utils.Retry(_helper, 1, 15, args=[rd])
2587     except utils.RetryTimeout:
2588       stats = rd.GetProcStatus()
2589       # last check
2590       if not (stats.is_connected or stats.is_in_resync):
2591         _Fail("DRBD device %s is not in sync: stats=%s", rd, stats)
2592     alldone = alldone and (not stats.is_in_resync)
2593     if stats.sync_percent is not None:
2594       min_resync = min(min_resync, stats.sync_percent)
2595
2596   return (alldone, min_resync)
2597
2598
2599 def PowercycleNode(hypervisor_type):
2600   """Hard-powercycle the node.
2601
2602   Because we need to return first, and schedule the powercycle in the
2603   background, we won't be able to report failures nicely.
2604
2605   """
2606   hyper = hypervisor.GetHypervisor(hypervisor_type)
2607   try:
2608     pid = os.fork()
2609   except OSError:
2610     # if we can't fork, we'll pretend that we're in the child process
2611     pid = 0
2612   if pid > 0:
2613     return "Reboot scheduled in 5 seconds"
2614   time.sleep(5)
2615   hyper.PowercycleNode()
2616
2617
2618 class HooksRunner(object):
2619   """Hook runner.
2620
2621   This class is instantiated on the node side (ganeti-noded) and not
2622   on the master side.
2623
2624   """
2625   def __init__(self, hooks_base_dir=None):
2626     """Constructor for hooks runner.
2627
2628     @type hooks_base_dir: str or None
2629     @param hooks_base_dir: if not None, this overrides the
2630         L{constants.HOOKS_BASE_DIR} (useful for unittests)
2631
2632     """
2633     if hooks_base_dir is None:
2634       hooks_base_dir = constants.HOOKS_BASE_DIR
2635     # yeah, _BASE_DIR is not valid for attributes, we use it like a
2636     # constant
2637     self._BASE_DIR = hooks_base_dir # pylint: disable-msg=C0103
2638
2639   def RunHooks(self, hpath, phase, env):
2640     """Run the scripts in the hooks directory.
2641
2642     @type hpath: str
2643     @param hpath: the path to the hooks directory which
2644         holds the scripts
2645     @type phase: str
2646     @param phase: either L{constants.HOOKS_PHASE_PRE} or
2647         L{constants.HOOKS_PHASE_POST}
2648     @type env: dict
2649     @param env: dictionary with the environment for the hook
2650     @rtype: list
2651     @return: list of 3-element tuples:
2652       - script path
2653       - script result, either L{constants.HKR_SUCCESS} or
2654         L{constants.HKR_FAIL}
2655       - output of the script
2656
2657     @raise errors.ProgrammerError: for invalid input
2658         parameters
2659
2660     """
2661     if phase == constants.HOOKS_PHASE_PRE:
2662       suffix = "pre"
2663     elif phase == constants.HOOKS_PHASE_POST:
2664       suffix = "post"
2665     else:
2666       _Fail("Unknown hooks phase '%s'", phase)
2667
2668
2669     subdir = "%s-%s.d" % (hpath, suffix)
2670     dir_name = "%s/%s" % (self._BASE_DIR, subdir)
2671     runparts_results = utils.RunParts(dir_name, env=env, reset_env=True)
2672
2673     results = []
2674     for (relname, relstatus, runresult)  in runparts_results:
2675       if relstatus == constants.RUNPARTS_SKIP:
2676         rrval = constants.HKR_SKIP
2677         output = ""
2678       elif relstatus == constants.RUNPARTS_ERR:
2679         rrval = constants.HKR_FAIL
2680         output = "Hook script execution error: %s" % runresult
2681       elif relstatus == constants.RUNPARTS_RUN:
2682         if runresult.failed:
2683           rrval = constants.HKR_FAIL
2684         else:
2685           rrval = constants.HKR_SUCCESS
2686         output = utils.SafeEncode(runresult.output.strip())
2687       results.append(("%s/%s" % (subdir, relname), rrval, output))
2688
2689     return results
2690
2691
2692 class IAllocatorRunner(object):
2693   """IAllocator runner.
2694
2695   This class is instantiated on the node side (ganeti-noded) and not on
2696   the master side.
2697
2698   """
2699   @staticmethod
2700   def Run(name, idata):
2701     """Run an iallocator script.
2702
2703     @type name: str
2704     @param name: the iallocator script name
2705     @type idata: str
2706     @param idata: the allocator input data
2707
2708     @rtype: tuple
2709     @return: two element tuple of:
2710        - status
2711        - either error message or stdout of allocator (for success)
2712
2713     """
2714     alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
2715                                   os.path.isfile)
2716     if alloc_script is None:
2717       _Fail("iallocator module '%s' not found in the search path", name)
2718
2719     fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
2720     try:
2721       os.write(fd, idata)
2722       os.close(fd)
2723       result = utils.RunCmd([alloc_script, fin_name])
2724       if result.failed:
2725         _Fail("iallocator module '%s' failed: %s, output '%s'",
2726               name, result.fail_reason, result.output)
2727     finally:
2728       os.unlink(fin_name)
2729
2730     return result.stdout
2731
2732
2733 class DevCacheManager(object):
2734   """Simple class for managing a cache of block device information.
2735
2736   """
2737   _DEV_PREFIX = "/dev/"
2738   _ROOT_DIR = constants.BDEV_CACHE_DIR
2739
2740   @classmethod
2741   def _ConvertPath(cls, dev_path):
2742     """Converts a /dev/name path to the cache file name.
2743
2744     This replaces slashes with underscores and strips the /dev
2745     prefix. It then returns the full path to the cache file.
2746
2747     @type dev_path: str
2748     @param dev_path: the C{/dev/} path name
2749     @rtype: str
2750     @return: the converted path name
2751
2752     """
2753     if dev_path.startswith(cls._DEV_PREFIX):
2754       dev_path = dev_path[len(cls._DEV_PREFIX):]
2755     dev_path = dev_path.replace("/", "_")
2756     fpath = "%s/bdev_%s" % (cls._ROOT_DIR, dev_path)
2757     return fpath
2758
2759   @classmethod
2760   def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
2761     """Updates the cache information for a given device.
2762
2763     @type dev_path: str
2764     @param dev_path: the pathname of the device
2765     @type owner: str
2766     @param owner: the owner (instance name) of the device
2767     @type on_primary: bool
2768     @param on_primary: whether this is the primary
2769         node nor not
2770     @type iv_name: str
2771     @param iv_name: the instance-visible name of the
2772         device, as in objects.Disk.iv_name
2773
2774     @rtype: None
2775
2776     """
2777     if dev_path is None:
2778       logging.error("DevCacheManager.UpdateCache got a None dev_path")
2779       return
2780     fpath = cls._ConvertPath(dev_path)
2781     if on_primary:
2782       state = "primary"
2783     else:
2784       state = "secondary"
2785     if iv_name is None:
2786       iv_name = "not_visible"
2787     fdata = "%s %s %s\n" % (str(owner), state, iv_name)
2788     try:
2789       utils.WriteFile(fpath, data=fdata)
2790     except EnvironmentError, err:
2791       logging.exception("Can't update bdev cache for %s: %s", dev_path, err)
2792
2793   @classmethod
2794   def RemoveCache(cls, dev_path):
2795     """Remove data for a dev_path.
2796
2797     This is just a wrapper over L{utils.RemoveFile} with a converted
2798     path name and logging.
2799
2800     @type dev_path: str
2801     @param dev_path: the pathname of the device
2802
2803     @rtype: None
2804
2805     """
2806     if dev_path is None:
2807       logging.error("DevCacheManager.RemoveCache got a None dev_path")
2808       return
2809     fpath = cls._ConvertPath(dev_path)
2810     try:
2811       utils.RemoveFile(fpath)
2812     except EnvironmentError, err:
2813       logging.exception("Can't update bdev cache for %s: %s", dev_path, err)