Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ b1b6ea87

History | View | Annotate | Download (53.8 kB)

1 2f31098c Iustin Pop
#
2 a8083063 Iustin Pop
#
3 a8083063 Iustin Pop
4 a8083063 Iustin Pop
# Copyright (C) 2006, 2007 Google Inc.
5 a8083063 Iustin Pop
#
6 a8083063 Iustin Pop
# This program is free software; you can redistribute it and/or modify
7 a8083063 Iustin Pop
# it under the terms of the GNU General Public License as published by
8 a8083063 Iustin Pop
# the Free Software Foundation; either version 2 of the License, or
9 a8083063 Iustin Pop
# (at your option) any later version.
10 a8083063 Iustin Pop
#
11 a8083063 Iustin Pop
# This program is distributed in the hope that it will be useful, but
12 a8083063 Iustin Pop
# WITHOUT ANY WARRANTY; without even the implied warranty of
13 a8083063 Iustin Pop
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14 a8083063 Iustin Pop
# General Public License for more details.
15 a8083063 Iustin Pop
#
16 a8083063 Iustin Pop
# You should have received a copy of the GNU General Public License
17 a8083063 Iustin Pop
# along with this program; if not, write to the Free Software
18 a8083063 Iustin Pop
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 a8083063 Iustin Pop
# 02110-1301, USA.
20 a8083063 Iustin Pop
21 a8083063 Iustin Pop
22 a8083063 Iustin Pop
"""Functions used by the node daemon"""
23 a8083063 Iustin Pop
24 a8083063 Iustin Pop
25 a8083063 Iustin Pop
import os
26 a8083063 Iustin Pop
import os.path
27 a8083063 Iustin Pop
import shutil
28 a8083063 Iustin Pop
import time
29 a8083063 Iustin Pop
import stat
30 a8083063 Iustin Pop
import errno
31 a8083063 Iustin Pop
import re
32 a8083063 Iustin Pop
import subprocess
33 b544cfe0 Iustin Pop
import random
34 18682bca Iustin Pop
import logging
35 a8083063 Iustin Pop
36 a8083063 Iustin Pop
from ganeti import errors
37 a8083063 Iustin Pop
from ganeti import utils
38 a8083063 Iustin Pop
from ganeti import ssh
39 a8083063 Iustin Pop
from ganeti import hypervisor
40 a8083063 Iustin Pop
from ganeti import constants
41 a8083063 Iustin Pop
from ganeti import bdev
42 a8083063 Iustin Pop
from ganeti import objects
43 880478f8 Iustin Pop
from ganeti import ssconf
44 a8083063 Iustin Pop
45 a8083063 Iustin Pop
46 c92b310a Michael Hanselmann
def _GetSshRunner():
47 c92b310a Michael Hanselmann
  return ssh.SshRunner()
48 c92b310a Michael Hanselmann
49 c92b310a Michael Hanselmann
50 b1b6ea87 Iustin Pop
def _GetMasterInfo():
51 b1b6ea87 Iustin Pop
  """Return the master ip and netdev.
52 b1b6ea87 Iustin Pop

53 b1b6ea87 Iustin Pop
  """
54 b1b6ea87 Iustin Pop
  try:
55 b1b6ea87 Iustin Pop
    ss = ssconf.SimpleStore()
56 b1b6ea87 Iustin Pop
    master_netdev = ss.GetMasterNetdev()
57 b1b6ea87 Iustin Pop
    master_ip = ss.GetMasterIP()
58 b1b6ea87 Iustin Pop
  except errors.ConfigurationError, err:
59 b1b6ea87 Iustin Pop
    logging.exception("Cluster configuration incomplete")
60 b1b6ea87 Iustin Pop
    return (None, None)
61 b1b6ea87 Iustin Pop
  return (master_netdev, master_ip)
62 b1b6ea87 Iustin Pop
63 b1b6ea87 Iustin Pop
64 1c65840b Iustin Pop
def StartMaster(start_daemons):
65 a8083063 Iustin Pop
  """Activate local node as master node.
66 a8083063 Iustin Pop

67 1c65840b Iustin Pop
  The function will always try activate the IP address of the master
68 1c65840b Iustin Pop
  (if someone else has it, then it won't). Then, if the start_daemons
69 1c65840b Iustin Pop
  parameter is True, it will also start the master daemons
70 1c65840b Iustin Pop
  (ganet-masterd and ganeti-rapi).
71 a8083063 Iustin Pop

72 a8083063 Iustin Pop
  """
73 b1b6ea87 Iustin Pop
  ok = True
74 b1b6ea87 Iustin Pop
  master_netdev, master_ip = _GetMasterInfo()
75 b1b6ea87 Iustin Pop
  if not master_netdev:
76 a8083063 Iustin Pop
    return False
77 a8083063 Iustin Pop
78 b1b6ea87 Iustin Pop
  if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
79 b1b6ea87 Iustin Pop
    if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT,
80 b1b6ea87 Iustin Pop
                     source=constants.LOCALHOST_IP_ADDRESS):
81 b1b6ea87 Iustin Pop
      # we already have the ip:
82 b1b6ea87 Iustin Pop
      logging.debug("Already started")
83 b1b6ea87 Iustin Pop
    else:
84 b1b6ea87 Iustin Pop
      logging.error("Someone else has the master ip, not activating")
85 b1b6ea87 Iustin Pop
      ok = False
86 b1b6ea87 Iustin Pop
  else:
87 b1b6ea87 Iustin Pop
    result = utils.RunCmd(["ip", "address", "add", "%s/32" % master_ip,
88 b1b6ea87 Iustin Pop
                           "dev", master_netdev, "label",
89 b1b6ea87 Iustin Pop
                           "%s:0" % master_netdev])
90 b1b6ea87 Iustin Pop
    if result.failed:
91 b1b6ea87 Iustin Pop
      logging.error("Can't activate master IP: %s", result.output)
92 b1b6ea87 Iustin Pop
      ok = False
93 b1b6ea87 Iustin Pop
94 b1b6ea87 Iustin Pop
    result = utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev,
95 b1b6ea87 Iustin Pop
                           "-s", master_ip, master_ip])
96 b1b6ea87 Iustin Pop
    # we'll ignore the exit code of arping
97 b1b6ea87 Iustin Pop
98 b1b6ea87 Iustin Pop
  # and now start the master and rapi daemons
99 b1b6ea87 Iustin Pop
  if start_daemons:
100 b1b6ea87 Iustin Pop
    for daemon in 'ganeti-masterd', 'ganeti-rapi':
101 b1b6ea87 Iustin Pop
      result = utils.RunCmd([daemon])
102 b1b6ea87 Iustin Pop
      if result.failed:
103 b1b6ea87 Iustin Pop
        logging.error("Can't start daemon %s: %s", daemon, result.output)
104 b1b6ea87 Iustin Pop
        ok = False
105 b1b6ea87 Iustin Pop
  return ok
106 a8083063 Iustin Pop
107 a8083063 Iustin Pop
108 1c65840b Iustin Pop
def StopMaster(stop_daemons):
109 a8083063 Iustin Pop
  """Deactivate this node as master.
110 a8083063 Iustin Pop

111 1c65840b Iustin Pop
  The function will always try to deactivate the IP address of the
112 1c65840b Iustin Pop
  master. Then, if the stop_daemons parameter is True, it will also
113 1c65840b Iustin Pop
  stop the master daemons (ganet-masterd and ganeti-rapi).
114 a8083063 Iustin Pop

115 a8083063 Iustin Pop
  """
116 b1b6ea87 Iustin Pop
  master_netdev, master_ip = _GetMasterInfo()
117 b1b6ea87 Iustin Pop
  if not master_netdev:
118 b1b6ea87 Iustin Pop
    return False
119 a8083063 Iustin Pop
120 b1b6ea87 Iustin Pop
  result = utils.RunCmd(["ip", "address", "del", "%s/32" % master_ip,
121 b1b6ea87 Iustin Pop
                         "dev", master_netdev])
122 a8083063 Iustin Pop
  if result.failed:
123 b1b6ea87 Iustin Pop
    logger.error("Can't remove the master IP, error: %s", result.output)
124 b1b6ea87 Iustin Pop
    # but otherwise ignore the failure
125 b1b6ea87 Iustin Pop
126 b1b6ea87 Iustin Pop
  if stop_daemons:
127 b1b6ea87 Iustin Pop
    # stop/kill the rapi and the master daemon
128 b1b6ea87 Iustin Pop
    for daemon in constants.RAPI_PID, constants.MASTERD_PID:
129 b1b6ea87 Iustin Pop
      utils.KillProcess(utils.ReadPidFile(utils.DaemonPidFileName(daemon)))
130 a8083063 Iustin Pop
131 a8083063 Iustin Pop
  return True
132 a8083063 Iustin Pop
133 a8083063 Iustin Pop
134 9716fdce Iustin Pop
def AddNode(dsa, dsapub, rsa, rsapub, sshkey, sshpub):
135 7900ed01 Iustin Pop
  """Joins this node to the cluster.
136 a8083063 Iustin Pop

137 7900ed01 Iustin Pop
  This does the following:
138 7900ed01 Iustin Pop
      - updates the hostkeys of the machine (rsa and dsa)
139 7900ed01 Iustin Pop
      - adds the ssh private key to the user
140 7900ed01 Iustin Pop
      - adds the ssh public key to the users' authorized_keys file
141 a8083063 Iustin Pop

142 7900ed01 Iustin Pop
  """
143 70d9e3d8 Iustin Pop
  sshd_keys =  [(constants.SSH_HOST_RSA_PRIV, rsa, 0600),
144 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_RSA_PUB, rsapub, 0644),
145 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_DSA_PRIV, dsa, 0600),
146 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_DSA_PUB, dsapub, 0644)]
147 7900ed01 Iustin Pop
  for name, content, mode in sshd_keys:
148 70d9e3d8 Iustin Pop
    utils.WriteFile(name, data=content, mode=mode)
149 a8083063 Iustin Pop
150 70d9e3d8 Iustin Pop
  try:
151 70d9e3d8 Iustin Pop
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS,
152 70d9e3d8 Iustin Pop
                                                    mkdir=True)
153 70d9e3d8 Iustin Pop
  except errors.OpExecError, err:
154 18682bca Iustin Pop
    logging.exception("Error while processing user ssh files")
155 70d9e3d8 Iustin Pop
    return False
156 a8083063 Iustin Pop
157 70d9e3d8 Iustin Pop
  for name, content in [(priv_key, sshkey), (pub_key, sshpub)]:
158 70d9e3d8 Iustin Pop
    utils.WriteFile(name, data=content, mode=0600)
159 a8083063 Iustin Pop
160 70d9e3d8 Iustin Pop
  utils.AddAuthorizedKey(auth_keys, sshpub)
161 a8083063 Iustin Pop
162 f491c3a8 Michael Hanselmann
  utils.RunCmd([constants.SSH_INITD_SCRIPT, "restart"])
163 a8083063 Iustin Pop
164 a8083063 Iustin Pop
  return True
165 a8083063 Iustin Pop
166 a8083063 Iustin Pop
167 a8083063 Iustin Pop
def LeaveCluster():
168 a8083063 Iustin Pop
  """Cleans up the current node and prepares it to be removed from the cluster.
169 a8083063 Iustin Pop

170 a8083063 Iustin Pop
  """
171 71eca7c3 Iustin Pop
  if os.path.isdir(constants.DATA_DIR):
172 71eca7c3 Iustin Pop
    for rel_name in utils.ListVisibleFiles(constants.DATA_DIR):
173 71eca7c3 Iustin Pop
      full_name = os.path.join(constants.DATA_DIR, rel_name)
174 71eca7c3 Iustin Pop
      if os.path.isfile(full_name) and not os.path.islink(full_name):
175 71eca7c3 Iustin Pop
        utils.RemoveFile(full_name)
176 a8083063 Iustin Pop
177 70d9e3d8 Iustin Pop
  try:
178 70d9e3d8 Iustin Pop
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
179 18682bca Iustin Pop
  except errors.OpExecError:
180 18682bca Iustin Pop
    logging.exception("Error while processing ssh files")
181 7900ed01 Iustin Pop
    return
182 7900ed01 Iustin Pop
183 70d9e3d8 Iustin Pop
  f = open(pub_key, 'r')
184 a8083063 Iustin Pop
  try:
185 70d9e3d8 Iustin Pop
    utils.RemoveAuthorizedKey(auth_keys, f.read(8192))
186 a8083063 Iustin Pop
  finally:
187 a8083063 Iustin Pop
    f.close()
188 a8083063 Iustin Pop
189 70d9e3d8 Iustin Pop
  utils.RemoveFile(priv_key)
190 70d9e3d8 Iustin Pop
  utils.RemoveFile(pub_key)
191 a8083063 Iustin Pop
192 6d8b6238 Guido Trotter
  # Return a reassuring string to the caller, and quit
193 6d8b6238 Guido Trotter
  raise errors.QuitGanetiException(False, 'Shutdown scheduled')
194 6d8b6238 Guido Trotter
195 a8083063 Iustin Pop
196 a8083063 Iustin Pop
def GetNodeInfo(vgname):
197 2f8598a5 Alexander Schreiber
  """Gives back a hash with different informations about the node.
198 a8083063 Iustin Pop

199 a8083063 Iustin Pop
  Returns:
200 a8083063 Iustin Pop
    { 'vg_size' : xxx,  'vg_free' : xxx, 'memory_domain0': xxx,
201 a8083063 Iustin Pop
      'memory_free' : xxx, 'memory_total' : xxx }
202 a8083063 Iustin Pop
    where
203 a8083063 Iustin Pop
    vg_size is the size of the configured volume group in MiB
204 a8083063 Iustin Pop
    vg_free is the free size of the volume group in MiB
205 a8083063 Iustin Pop
    memory_dom0 is the memory allocated for domain0 in MiB
206 a8083063 Iustin Pop
    memory_free is the currently available (free) ram in MiB
207 a8083063 Iustin Pop
    memory_total is the total number of ram in MiB
208 a8083063 Iustin Pop

209 098c0958 Michael Hanselmann
  """
210 a8083063 Iustin Pop
  outputarray = {}
211 a8083063 Iustin Pop
  vginfo = _GetVGInfo(vgname)
212 a8083063 Iustin Pop
  outputarray['vg_size'] = vginfo['vg_size']
213 a8083063 Iustin Pop
  outputarray['vg_free'] = vginfo['vg_free']
214 a8083063 Iustin Pop
215 a8083063 Iustin Pop
  hyper = hypervisor.GetHypervisor()
216 a8083063 Iustin Pop
  hyp_info = hyper.GetNodeInfo()
217 a8083063 Iustin Pop
  if hyp_info is not None:
218 a8083063 Iustin Pop
    outputarray.update(hyp_info)
219 a8083063 Iustin Pop
220 3ef10550 Michael Hanselmann
  f = open("/proc/sys/kernel/random/boot_id", 'r')
221 3ef10550 Michael Hanselmann
  try:
222 3ef10550 Michael Hanselmann
    outputarray["bootid"] = f.read(128).rstrip("\n")
223 3ef10550 Michael Hanselmann
  finally:
224 3ef10550 Michael Hanselmann
    f.close()
225 3ef10550 Michael Hanselmann
226 a8083063 Iustin Pop
  return outputarray
227 a8083063 Iustin Pop
228 a8083063 Iustin Pop
229 a8083063 Iustin Pop
def VerifyNode(what):
230 a8083063 Iustin Pop
  """Verify the status of the local node.
231 a8083063 Iustin Pop

232 a8083063 Iustin Pop
  Args:
233 a8083063 Iustin Pop
    what - a dictionary of things to check:
234 a8083063 Iustin Pop
      'filelist' : list of files for which to compute checksums
235 a8083063 Iustin Pop
      'nodelist' : list of nodes we should check communication with
236 a8083063 Iustin Pop
      'hypervisor': run the hypervisor-specific verify
237 a8083063 Iustin Pop

238 a8083063 Iustin Pop
  Requested files on local node are checksummed and the result returned.
239 a8083063 Iustin Pop

240 a8083063 Iustin Pop
  The nodelist is traversed, with the following checks being made
241 a8083063 Iustin Pop
  for each node:
242 a8083063 Iustin Pop
  - known_hosts key correct
243 a8083063 Iustin Pop
  - correct resolving of node name (target node returns its own hostname
244 a8083063 Iustin Pop
    by ssh-execution of 'hostname', result compared against name in list.
245 a8083063 Iustin Pop

246 a8083063 Iustin Pop
  """
247 a8083063 Iustin Pop
  result = {}
248 a8083063 Iustin Pop
249 a8083063 Iustin Pop
  if 'hypervisor' in what:
250 a8083063 Iustin Pop
    result['hypervisor'] = hypervisor.GetHypervisor().Verify()
251 a8083063 Iustin Pop
252 a8083063 Iustin Pop
  if 'filelist' in what:
253 a8083063 Iustin Pop
    result['filelist'] = utils.FingerprintFiles(what['filelist'])
254 a8083063 Iustin Pop
255 a8083063 Iustin Pop
  if 'nodelist' in what:
256 a8083063 Iustin Pop
    result['nodelist'] = {}
257 b544cfe0 Iustin Pop
    random.shuffle(what['nodelist'])
258 a8083063 Iustin Pop
    for node in what['nodelist']:
259 c92b310a Michael Hanselmann
      success, message = _GetSshRunner().VerifyNodeHostname(node)
260 a8083063 Iustin Pop
      if not success:
261 a8083063 Iustin Pop
        result['nodelist'][node] = message
262 9d4bfc96 Iustin Pop
  if 'node-net-test' in what:
263 9d4bfc96 Iustin Pop
    result['node-net-test'] = {}
264 9d4bfc96 Iustin Pop
    my_name = utils.HostInfo().name
265 9d4bfc96 Iustin Pop
    my_pip = my_sip = None
266 9d4bfc96 Iustin Pop
    for name, pip, sip in what['node-net-test']:
267 9d4bfc96 Iustin Pop
      if name == my_name:
268 9d4bfc96 Iustin Pop
        my_pip = pip
269 9d4bfc96 Iustin Pop
        my_sip = sip
270 9d4bfc96 Iustin Pop
        break
271 9d4bfc96 Iustin Pop
    if not my_pip:
272 9d4bfc96 Iustin Pop
      result['node-net-test'][my_name] = ("Can't find my own"
273 9d4bfc96 Iustin Pop
                                          " primary/secondary IP"
274 9d4bfc96 Iustin Pop
                                          " in the node list")
275 9d4bfc96 Iustin Pop
    else:
276 9d4bfc96 Iustin Pop
      port = ssconf.SimpleStore().GetNodeDaemonPort()
277 9d4bfc96 Iustin Pop
      for name, pip, sip in what['node-net-test']:
278 9d4bfc96 Iustin Pop
        fail = []
279 9d4bfc96 Iustin Pop
        if not utils.TcpPing(pip, port, source=my_pip):
280 9d4bfc96 Iustin Pop
          fail.append("primary")
281 9d4bfc96 Iustin Pop
        if sip != pip:
282 9d4bfc96 Iustin Pop
          if not utils.TcpPing(sip, port, source=my_sip):
283 9d4bfc96 Iustin Pop
            fail.append("secondary")
284 9d4bfc96 Iustin Pop
        if fail:
285 9d4bfc96 Iustin Pop
          result['node-net-test'][name] = ("failure using the %s"
286 9d4bfc96 Iustin Pop
                                           " interface(s)" %
287 9d4bfc96 Iustin Pop
                                           " and ".join(fail))
288 9d4bfc96 Iustin Pop
289 a8083063 Iustin Pop
  return result
290 a8083063 Iustin Pop
291 a8083063 Iustin Pop
292 a8083063 Iustin Pop
def GetVolumeList(vg_name):
293 a8083063 Iustin Pop
  """Compute list of logical volumes and their size.
294 a8083063 Iustin Pop

295 a8083063 Iustin Pop
  Returns:
296 cb2037a2 Iustin Pop
    dictionary of all partions (key) with their size (in MiB), inactive
297 cb2037a2 Iustin Pop
    and online status:
298 cb2037a2 Iustin Pop
    {'test1': ('20.06', True, True)}
299 a8083063 Iustin Pop

300 a8083063 Iustin Pop
  """
301 cb2037a2 Iustin Pop
  lvs = {}
302 cb2037a2 Iustin Pop
  sep = '|'
303 cb2037a2 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
304 cb2037a2 Iustin Pop
                         "--separator=%s" % sep,
305 cb2037a2 Iustin Pop
                         "-olv_name,lv_size,lv_attr", vg_name])
306 a8083063 Iustin Pop
  if result.failed:
307 18682bca Iustin Pop
    logging.error("Failed to list logical volumes, lvs output: %s",
308 18682bca Iustin Pop
                  result.output)
309 b63ed789 Iustin Pop
    return result.output
310 cb2037a2 Iustin Pop
311 df4c2628 Iustin Pop
  valid_line_re = re.compile("^ *([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
312 cb2037a2 Iustin Pop
  for line in result.stdout.splitlines():
313 df4c2628 Iustin Pop
    line = line.strip()
314 df4c2628 Iustin Pop
    match = valid_line_re.match(line)
315 df4c2628 Iustin Pop
    if not match:
316 18682bca Iustin Pop
      logging.error("Invalid line returned from lvs output: '%s'", line)
317 df4c2628 Iustin Pop
      continue
318 df4c2628 Iustin Pop
    name, size, attr = match.groups()
319 cb2037a2 Iustin Pop
    inactive = attr[4] == '-'
320 cb2037a2 Iustin Pop
    online = attr[5] == 'o'
321 cb2037a2 Iustin Pop
    lvs[name] = (size, inactive, online)
322 cb2037a2 Iustin Pop
323 cb2037a2 Iustin Pop
  return lvs
324 a8083063 Iustin Pop
325 a8083063 Iustin Pop
326 a8083063 Iustin Pop
def ListVolumeGroups():
327 2f8598a5 Alexander Schreiber
  """List the volume groups and their size.
328 a8083063 Iustin Pop

329 a8083063 Iustin Pop
  Returns:
330 a8083063 Iustin Pop
    Dictionary with keys volume name and values the size of the volume
331 a8083063 Iustin Pop

332 a8083063 Iustin Pop
  """
333 a8083063 Iustin Pop
  return utils.ListVolumeGroups()
334 a8083063 Iustin Pop
335 a8083063 Iustin Pop
336 dcb93971 Michael Hanselmann
def NodeVolumes():
337 dcb93971 Michael Hanselmann
  """List all volumes on this node.
338 dcb93971 Michael Hanselmann

339 dcb93971 Michael Hanselmann
  """
340 dcb93971 Michael Hanselmann
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
341 dcb93971 Michael Hanselmann
                         "--separator=|",
342 dcb93971 Michael Hanselmann
                         "--options=lv_name,lv_size,devices,vg_name"])
343 dcb93971 Michael Hanselmann
  if result.failed:
344 18682bca Iustin Pop
    logging.error("Failed to list logical volumes, lvs output: %s",
345 18682bca Iustin Pop
                  result.output)
346 dcb93971 Michael Hanselmann
    return {}
347 dcb93971 Michael Hanselmann
348 dcb93971 Michael Hanselmann
  def parse_dev(dev):
349 dcb93971 Michael Hanselmann
    if '(' in dev:
350 dcb93971 Michael Hanselmann
      return dev.split('(')[0]
351 dcb93971 Michael Hanselmann
    else:
352 dcb93971 Michael Hanselmann
      return dev
353 dcb93971 Michael Hanselmann
354 dcb93971 Michael Hanselmann
  def map_line(line):
355 dcb93971 Michael Hanselmann
    return {
356 dcb93971 Michael Hanselmann
      'name': line[0].strip(),
357 dcb93971 Michael Hanselmann
      'size': line[1].strip(),
358 dcb93971 Michael Hanselmann
      'dev': parse_dev(line[2].strip()),
359 dcb93971 Michael Hanselmann
      'vg': line[3].strip(),
360 dcb93971 Michael Hanselmann
    }
361 dcb93971 Michael Hanselmann
362 a17a7623 Iustin Pop
  return [map_line(line.split('|')) for line in result.stdout.splitlines()
363 a17a7623 Iustin Pop
          if line.count('|') >= 3]
364 dcb93971 Michael Hanselmann
365 dcb93971 Michael Hanselmann
366 a8083063 Iustin Pop
def BridgesExist(bridges_list):
367 2f8598a5 Alexander Schreiber
  """Check if a list of bridges exist on the current node.
368 a8083063 Iustin Pop

369 a8083063 Iustin Pop
  Returns:
370 a8083063 Iustin Pop
    True if all of them exist, false otherwise
371 a8083063 Iustin Pop

372 a8083063 Iustin Pop
  """
373 a8083063 Iustin Pop
  for bridge in bridges_list:
374 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
375 a8083063 Iustin Pop
      return False
376 a8083063 Iustin Pop
377 a8083063 Iustin Pop
  return True
378 a8083063 Iustin Pop
379 a8083063 Iustin Pop
380 a8083063 Iustin Pop
def GetInstanceList():
381 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
382 a8083063 Iustin Pop

383 a8083063 Iustin Pop
  Returns:
384 a8083063 Iustin Pop
    A list of all running instances on the current node
385 a8083063 Iustin Pop
    - instance1.example.com
386 a8083063 Iustin Pop
    - instance2.example.com
387 a8083063 Iustin Pop

388 098c0958 Michael Hanselmann
  """
389 a8083063 Iustin Pop
  try:
390 a8083063 Iustin Pop
    names = hypervisor.GetHypervisor().ListInstances()
391 a8083063 Iustin Pop
  except errors.HypervisorError, err:
392 18682bca Iustin Pop
    logging.exception("Error enumerating instances")
393 a8083063 Iustin Pop
    raise
394 a8083063 Iustin Pop
395 a8083063 Iustin Pop
  return names
396 a8083063 Iustin Pop
397 a8083063 Iustin Pop
398 a8083063 Iustin Pop
def GetInstanceInfo(instance):
399 2f8598a5 Alexander Schreiber
  """Gives back the informations about an instance as a dictionary.
400 a8083063 Iustin Pop

401 a8083063 Iustin Pop
  Args:
402 a8083063 Iustin Pop
    instance: name of the instance (ex. instance1.example.com)
403 a8083063 Iustin Pop

404 a8083063 Iustin Pop
  Returns:
405 a8083063 Iustin Pop
    { 'memory' : 511, 'state' : '-b---', 'time' : 3188.8, }
406 a8083063 Iustin Pop
    where
407 a8083063 Iustin Pop
    memory: memory size of instance (int)
408 a8083063 Iustin Pop
    state: xen state of instance (string)
409 a8083063 Iustin Pop
    time: cpu time of instance (float)
410 a8083063 Iustin Pop

411 098c0958 Michael Hanselmann
  """
412 a8083063 Iustin Pop
  output = {}
413 a8083063 Iustin Pop
414 a8083063 Iustin Pop
  iinfo = hypervisor.GetHypervisor().GetInstanceInfo(instance)
415 a8083063 Iustin Pop
  if iinfo is not None:
416 a8083063 Iustin Pop
    output['memory'] = iinfo[2]
417 a8083063 Iustin Pop
    output['state'] = iinfo[4]
418 a8083063 Iustin Pop
    output['time'] = iinfo[5]
419 a8083063 Iustin Pop
420 a8083063 Iustin Pop
  return output
421 a8083063 Iustin Pop
422 a8083063 Iustin Pop
423 a8083063 Iustin Pop
def GetAllInstancesInfo():
424 a8083063 Iustin Pop
  """Gather data about all instances.
425 a8083063 Iustin Pop

426 a8083063 Iustin Pop
  This is the equivalent of `GetInstanceInfo()`, except that it
427 a8083063 Iustin Pop
  computes data for all instances at once, thus being faster if one
428 a8083063 Iustin Pop
  needs data about more than one instance.
429 a8083063 Iustin Pop

430 a8083063 Iustin Pop
  Returns: a dictionary of dictionaries, keys being the instance name,
431 a8083063 Iustin Pop
    and with values:
432 a8083063 Iustin Pop
    { 'memory' : 511, 'state' : '-b---', 'time' : 3188.8, }
433 a8083063 Iustin Pop
    where
434 a8083063 Iustin Pop
    memory: memory size of instance (int)
435 a8083063 Iustin Pop
    state: xen state of instance (string)
436 a8083063 Iustin Pop
    time: cpu time of instance (float)
437 a8083063 Iustin Pop
    vcpus: the number of cpus
438 a8083063 Iustin Pop

439 098c0958 Michael Hanselmann
  """
440 a8083063 Iustin Pop
  output = {}
441 a8083063 Iustin Pop
442 a8083063 Iustin Pop
  iinfo = hypervisor.GetHypervisor().GetAllInstancesInfo()
443 a8083063 Iustin Pop
  if iinfo:
444 3ecf6786 Iustin Pop
    for name, inst_id, memory, vcpus, state, times in iinfo:
445 a8083063 Iustin Pop
      output[name] = {
446 a8083063 Iustin Pop
        'memory': memory,
447 a8083063 Iustin Pop
        'vcpus': vcpus,
448 a8083063 Iustin Pop
        'state': state,
449 a8083063 Iustin Pop
        'time': times,
450 a8083063 Iustin Pop
        }
451 a8083063 Iustin Pop
452 a8083063 Iustin Pop
  return output
453 a8083063 Iustin Pop
454 a8083063 Iustin Pop
455 a8083063 Iustin Pop
def AddOSToInstance(instance, os_disk, swap_disk):
456 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
457 a8083063 Iustin Pop

458 a8083063 Iustin Pop
  Args:
459 a8083063 Iustin Pop
    instance: the instance object
460 a8083063 Iustin Pop
    os_disk: the instance-visible name of the os device
461 a8083063 Iustin Pop
    swap_disk: the instance-visible name of the swap device
462 a8083063 Iustin Pop

463 a8083063 Iustin Pop
  """
464 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
465 a8083063 Iustin Pop
466 a8083063 Iustin Pop
  create_script = inst_os.create_script
467 a8083063 Iustin Pop
468 9716fdce Iustin Pop
  os_device = instance.FindDisk(os_disk)
469 9716fdce Iustin Pop
  if os_device is None:
470 18682bca Iustin Pop
    logging.error("Can't find this device-visible name '%s'", os_disk)
471 a8083063 Iustin Pop
    return False
472 a8083063 Iustin Pop
473 9716fdce Iustin Pop
  swap_device = instance.FindDisk(swap_disk)
474 9716fdce Iustin Pop
  if swap_device is None:
475 18682bca Iustin Pop
    logging.error("Can't find this device-visible name '%s'", swap_disk)
476 a8083063 Iustin Pop
    return False
477 a8083063 Iustin Pop
478 a8083063 Iustin Pop
  real_os_dev = _RecursiveFindBD(os_device)
479 a8083063 Iustin Pop
  if real_os_dev is None:
480 a8083063 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
481 a8083063 Iustin Pop
                                  str(os_device))
482 a8083063 Iustin Pop
  real_os_dev.Open()
483 a8083063 Iustin Pop
484 a8083063 Iustin Pop
  real_swap_dev = _RecursiveFindBD(swap_device)
485 a8083063 Iustin Pop
  if real_swap_dev is None:
486 a8083063 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
487 a8083063 Iustin Pop
                                  str(swap_device))
488 a8083063 Iustin Pop
  real_swap_dev.Open()
489 a8083063 Iustin Pop
490 a8083063 Iustin Pop
  logfile = "%s/add-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
491 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
492 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
493 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
494 a8083063 Iustin Pop
495 c20494cd Iustin Pop
  command = utils.BuildShellCmd("cd %s && %s -i %s -b %s -s %s &>%s",
496 a8083063 Iustin Pop
                                inst_os.path, create_script, instance.name,
497 a8083063 Iustin Pop
                                real_os_dev.dev_path, real_swap_dev.dev_path,
498 a8083063 Iustin Pop
                                logfile)
499 decd5f45 Iustin Pop
500 decd5f45 Iustin Pop
  result = utils.RunCmd(command)
501 decd5f45 Iustin Pop
  if result.failed:
502 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
503 18682bca Iustin Pop
                  " output: %s", command, result.fail_reason, logfile,
504 18682bca Iustin Pop
                  result.output)
505 decd5f45 Iustin Pop
    return False
506 decd5f45 Iustin Pop
507 decd5f45 Iustin Pop
  return True
508 decd5f45 Iustin Pop
509 decd5f45 Iustin Pop
510 decd5f45 Iustin Pop
def RunRenameInstance(instance, old_name, os_disk, swap_disk):
511 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
512 decd5f45 Iustin Pop

513 decd5f45 Iustin Pop
  Args:
514 decd5f45 Iustin Pop
    instance: the instance object
515 decd5f45 Iustin Pop
    old_name: the old name of the instance
516 decd5f45 Iustin Pop
    os_disk: the instance-visible name of the os device
517 decd5f45 Iustin Pop
    swap_disk: the instance-visible name of the swap device
518 decd5f45 Iustin Pop

519 decd5f45 Iustin Pop
  """
520 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
521 decd5f45 Iustin Pop
522 decd5f45 Iustin Pop
  script = inst_os.rename_script
523 decd5f45 Iustin Pop
524 decd5f45 Iustin Pop
  os_device = instance.FindDisk(os_disk)
525 decd5f45 Iustin Pop
  if os_device is None:
526 18682bca Iustin Pop
    logging.error("Can't find this device-visible name '%s'", os_disk)
527 decd5f45 Iustin Pop
    return False
528 decd5f45 Iustin Pop
529 decd5f45 Iustin Pop
  swap_device = instance.FindDisk(swap_disk)
530 decd5f45 Iustin Pop
  if swap_device is None:
531 18682bca Iustin Pop
    logging.error("Can't find this device-visible name '%s'", swap_disk)
532 decd5f45 Iustin Pop
    return False
533 decd5f45 Iustin Pop
534 decd5f45 Iustin Pop
  real_os_dev = _RecursiveFindBD(os_device)
535 decd5f45 Iustin Pop
  if real_os_dev is None:
536 decd5f45 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
537 decd5f45 Iustin Pop
                                  str(os_device))
538 decd5f45 Iustin Pop
  real_os_dev.Open()
539 decd5f45 Iustin Pop
540 decd5f45 Iustin Pop
  real_swap_dev = _RecursiveFindBD(swap_device)
541 decd5f45 Iustin Pop
  if real_swap_dev is None:
542 decd5f45 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
543 decd5f45 Iustin Pop
                                  str(swap_device))
544 decd5f45 Iustin Pop
  real_swap_dev.Open()
545 decd5f45 Iustin Pop
546 decd5f45 Iustin Pop
  logfile = "%s/rename-%s-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
547 decd5f45 Iustin Pop
                                           old_name,
548 decd5f45 Iustin Pop
                                           instance.name, int(time.time()))
549 decd5f45 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
550 decd5f45 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
551 decd5f45 Iustin Pop
552 decd5f45 Iustin Pop
  command = utils.BuildShellCmd("cd %s && %s -o %s -n %s -b %s -s %s &>%s",
553 decd5f45 Iustin Pop
                                inst_os.path, script, old_name, instance.name,
554 decd5f45 Iustin Pop
                                real_os_dev.dev_path, real_swap_dev.dev_path,
555 decd5f45 Iustin Pop
                                logfile)
556 a8083063 Iustin Pop
557 a8083063 Iustin Pop
  result = utils.RunCmd(command)
558 a8083063 Iustin Pop
559 a8083063 Iustin Pop
  if result.failed:
560 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
561 18682bca Iustin Pop
                  command, result.fail_reason, result.output)
562 a8083063 Iustin Pop
    return False
563 a8083063 Iustin Pop
564 a8083063 Iustin Pop
  return True
565 a8083063 Iustin Pop
566 a8083063 Iustin Pop
567 a8083063 Iustin Pop
def _GetVGInfo(vg_name):
568 a8083063 Iustin Pop
  """Get informations about the volume group.
569 a8083063 Iustin Pop

570 a8083063 Iustin Pop
  Args:
571 a8083063 Iustin Pop
    vg_name: the volume group
572 a8083063 Iustin Pop

573 a8083063 Iustin Pop
  Returns:
574 a8083063 Iustin Pop
    { 'vg_size' : xxx, 'vg_free' : xxx, 'pv_count' : xxx }
575 a8083063 Iustin Pop
    where
576 a8083063 Iustin Pop
    vg_size is the total size of the volume group in MiB
577 a8083063 Iustin Pop
    vg_free is the free size of the volume group in MiB
578 a8083063 Iustin Pop
    pv_count are the number of physical disks in that vg
579 a8083063 Iustin Pop

580 f4d377e7 Iustin Pop
  If an error occurs during gathering of data, we return the same dict
581 f4d377e7 Iustin Pop
  with keys all set to None.
582 f4d377e7 Iustin Pop

583 a8083063 Iustin Pop
  """
584 f4d377e7 Iustin Pop
  retdic = dict.fromkeys(["vg_size", "vg_free", "pv_count"])
585 f4d377e7 Iustin Pop
586 a8083063 Iustin Pop
  retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings",
587 a8083063 Iustin Pop
                         "--nosuffix", "--units=m", "--separator=:", vg_name])
588 a8083063 Iustin Pop
589 a8083063 Iustin Pop
  if retval.failed:
590 18682bca Iustin Pop
    logging.error("volume group %s not present", vg_name)
591 f4d377e7 Iustin Pop
    return retdic
592 d87ae7d2 Iustin Pop
  valarr = retval.stdout.strip().rstrip(':').split(':')
593 f4d377e7 Iustin Pop
  if len(valarr) == 3:
594 f4d377e7 Iustin Pop
    try:
595 f4d377e7 Iustin Pop
      retdic = {
596 f4d377e7 Iustin Pop
        "vg_size": int(round(float(valarr[0]), 0)),
597 f4d377e7 Iustin Pop
        "vg_free": int(round(float(valarr[1]), 0)),
598 f4d377e7 Iustin Pop
        "pv_count": int(valarr[2]),
599 f4d377e7 Iustin Pop
        }
600 f4d377e7 Iustin Pop
    except ValueError, err:
601 18682bca Iustin Pop
      logging.exception("Fail to parse vgs output")
602 f4d377e7 Iustin Pop
  else:
603 18682bca Iustin Pop
    logging.error("vgs output has the wrong number of fields (expected"
604 18682bca Iustin Pop
                  " three): %s", str(valarr))
605 a8083063 Iustin Pop
  return retdic
606 a8083063 Iustin Pop
607 a8083063 Iustin Pop
608 a8083063 Iustin Pop
def _GatherBlockDevs(instance):
609 a8083063 Iustin Pop
  """Set up an instance's block device(s).
610 a8083063 Iustin Pop

611 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
612 a8083063 Iustin Pop
  devices must be already assembled.
613 a8083063 Iustin Pop

614 a8083063 Iustin Pop
  """
615 a8083063 Iustin Pop
  block_devices = []
616 a8083063 Iustin Pop
  for disk in instance.disks:
617 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
618 a8083063 Iustin Pop
    if device is None:
619 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
620 a8083063 Iustin Pop
                                    str(disk))
621 a8083063 Iustin Pop
    device.Open()
622 a8083063 Iustin Pop
    block_devices.append((disk, device))
623 a8083063 Iustin Pop
  return block_devices
624 a8083063 Iustin Pop
625 a8083063 Iustin Pop
626 a8083063 Iustin Pop
def StartInstance(instance, extra_args):
627 a8083063 Iustin Pop
  """Start an instance.
628 a8083063 Iustin Pop

629 a8083063 Iustin Pop
  Args:
630 a8083063 Iustin Pop
    instance - name of instance to start.
631 a8083063 Iustin Pop

632 098c0958 Michael Hanselmann
  """
633 a8083063 Iustin Pop
  running_instances = GetInstanceList()
634 a8083063 Iustin Pop
635 a8083063 Iustin Pop
  if instance.name in running_instances:
636 a8083063 Iustin Pop
    return True
637 a8083063 Iustin Pop
638 a8083063 Iustin Pop
  block_devices = _GatherBlockDevs(instance)
639 a8083063 Iustin Pop
  hyper = hypervisor.GetHypervisor()
640 a8083063 Iustin Pop
641 a8083063 Iustin Pop
  try:
642 a8083063 Iustin Pop
    hyper.StartInstance(instance, block_devices, extra_args)
643 a8083063 Iustin Pop
  except errors.HypervisorError, err:
644 18682bca Iustin Pop
    logging.exception("Failed to start instance")
645 a8083063 Iustin Pop
    return False
646 a8083063 Iustin Pop
647 a8083063 Iustin Pop
  return True
648 a8083063 Iustin Pop
649 a8083063 Iustin Pop
650 a8083063 Iustin Pop
def ShutdownInstance(instance):
651 a8083063 Iustin Pop
  """Shut an instance down.
652 a8083063 Iustin Pop

653 a8083063 Iustin Pop
  Args:
654 a8083063 Iustin Pop
    instance - name of instance to shutdown.
655 a8083063 Iustin Pop

656 098c0958 Michael Hanselmann
  """
657 a8083063 Iustin Pop
  running_instances = GetInstanceList()
658 a8083063 Iustin Pop
659 a8083063 Iustin Pop
  if instance.name not in running_instances:
660 a8083063 Iustin Pop
    return True
661 a8083063 Iustin Pop
662 a8083063 Iustin Pop
  hyper = hypervisor.GetHypervisor()
663 a8083063 Iustin Pop
  try:
664 a8083063 Iustin Pop
    hyper.StopInstance(instance)
665 a8083063 Iustin Pop
  except errors.HypervisorError, err:
666 18682bca Iustin Pop
    logging.error("Failed to stop instance")
667 a8083063 Iustin Pop
    return False
668 a8083063 Iustin Pop
669 a8083063 Iustin Pop
  # test every 10secs for 2min
670 a8083063 Iustin Pop
  shutdown_ok = False
671 a8083063 Iustin Pop
672 a8083063 Iustin Pop
  time.sleep(1)
673 a8083063 Iustin Pop
  for dummy in range(11):
674 a8083063 Iustin Pop
    if instance.name not in GetInstanceList():
675 a8083063 Iustin Pop
      break
676 a8083063 Iustin Pop
    time.sleep(10)
677 a8083063 Iustin Pop
  else:
678 a8083063 Iustin Pop
    # the shutdown did not succeed
679 18682bca Iustin Pop
    logging.error("shutdown of '%s' unsuccessful, using destroy", instance)
680 a8083063 Iustin Pop
681 a8083063 Iustin Pop
    try:
682 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
683 a8083063 Iustin Pop
    except errors.HypervisorError, err:
684 18682bca Iustin Pop
      logging.exception("Failed to stop instance")
685 a8083063 Iustin Pop
      return False
686 a8083063 Iustin Pop
687 a8083063 Iustin Pop
    time.sleep(1)
688 a8083063 Iustin Pop
    if instance.name in GetInstanceList():
689 18682bca Iustin Pop
      logging.error("could not shutdown instance '%s' even by destroy",
690 18682bca Iustin Pop
                    instance.name)
691 a8083063 Iustin Pop
      return False
692 a8083063 Iustin Pop
693 a8083063 Iustin Pop
  return True
694 a8083063 Iustin Pop
695 a8083063 Iustin Pop
696 007a2f3e Alexander Schreiber
def RebootInstance(instance, reboot_type, extra_args):
697 007a2f3e Alexander Schreiber
  """Reboot an instance.
698 007a2f3e Alexander Schreiber

699 007a2f3e Alexander Schreiber
  Args:
700 007a2f3e Alexander Schreiber
    instance    - name of instance to reboot
701 007a2f3e Alexander Schreiber
    reboot_type - how to reboot [soft,hard,full]
702 007a2f3e Alexander Schreiber

703 007a2f3e Alexander Schreiber
  """
704 007a2f3e Alexander Schreiber
  running_instances = GetInstanceList()
705 007a2f3e Alexander Schreiber
706 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
707 18682bca Iustin Pop
    logging.error("Cannot reboot instance that is not running")
708 007a2f3e Alexander Schreiber
    return False
709 007a2f3e Alexander Schreiber
710 007a2f3e Alexander Schreiber
  hyper = hypervisor.GetHypervisor()
711 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
712 007a2f3e Alexander Schreiber
    try:
713 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
714 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
715 18682bca Iustin Pop
      logging.exception("Failed to soft reboot instance")
716 007a2f3e Alexander Schreiber
      return False
717 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
718 007a2f3e Alexander Schreiber
    try:
719 007a2f3e Alexander Schreiber
      ShutdownInstance(instance)
720 007a2f3e Alexander Schreiber
      StartInstance(instance, extra_args)
721 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
722 18682bca Iustin Pop
      logging.exception("Failed to hard reboot instance")
723 007a2f3e Alexander Schreiber
      return False
724 007a2f3e Alexander Schreiber
  else:
725 007a2f3e Alexander Schreiber
    raise errors.ParameterError("reboot_type invalid")
726 007a2f3e Alexander Schreiber
727 007a2f3e Alexander Schreiber
728 007a2f3e Alexander Schreiber
  return True
729 007a2f3e Alexander Schreiber
730 007a2f3e Alexander Schreiber
731 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
732 2a10865c Iustin Pop
  """Migrates an instance to another node.
733 2a10865c Iustin Pop

734 2a10865c Iustin Pop
  """
735 2a10865c Iustin Pop
  hyper = hypervisor.GetHypervisor()
736 2a10865c Iustin Pop
737 2a10865c Iustin Pop
  try:
738 2a10865c Iustin Pop
    hyper.MigrateInstance(instance, target, live)
739 2a10865c Iustin Pop
  except errors.HypervisorError, err:
740 2a10865c Iustin Pop
    msg = "Failed to migrate instance: %s" % str(err)
741 18682bca Iustin Pop
    logging.error(msg)
742 2a10865c Iustin Pop
    return (False, msg)
743 2a10865c Iustin Pop
  return (True, "Migration successfull")
744 2a10865c Iustin Pop
745 2a10865c Iustin Pop
746 3f78eef2 Iustin Pop
def CreateBlockDevice(disk, size, owner, on_primary, info):
747 a8083063 Iustin Pop
  """Creates a block device for an instance.
748 a8083063 Iustin Pop

749 a8083063 Iustin Pop
  Args:
750 c99a3cc0 Manuel Franceschini
   disk: a ganeti.objects.Disk object
751 c99a3cc0 Manuel Franceschini
   size: the size of the physical underlying device
752 c99a3cc0 Manuel Franceschini
   owner: a string with the name of the instance
753 6c8af3d0 Manuel Franceschini
   on_primary: a boolean indicating if it is the primary node or not
754 6c8af3d0 Manuel Franceschini
   info: string that will be sent to the physical device creation
755 a8083063 Iustin Pop

756 a8083063 Iustin Pop
  Returns:
757 a8083063 Iustin Pop
    the new unique_id of the device (this can sometime be
758 a8083063 Iustin Pop
    computed only after creation), or None. On secondary nodes,
759 a8083063 Iustin Pop
    it's not required to return anything.
760 a8083063 Iustin Pop

761 a8083063 Iustin Pop
  """
762 a8083063 Iustin Pop
  clist = []
763 a8083063 Iustin Pop
  if disk.children:
764 a8083063 Iustin Pop
    for child in disk.children:
765 3f78eef2 Iustin Pop
      crdev = _RecursiveAssembleBD(child, owner, on_primary)
766 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
767 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
768 a8083063 Iustin Pop
        # be assembled
769 a8083063 Iustin Pop
        crdev.Open()
770 a8083063 Iustin Pop
      clist.append(crdev)
771 a8083063 Iustin Pop
  try:
772 a8083063 Iustin Pop
    device = bdev.FindDevice(disk.dev_type, disk.physical_id, clist)
773 a8083063 Iustin Pop
    if device is not None:
774 18682bca Iustin Pop
      logging.info("removing existing device %s", disk)
775 a8083063 Iustin Pop
      device.Remove()
776 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
777 a8083063 Iustin Pop
    pass
778 a8083063 Iustin Pop
779 a8083063 Iustin Pop
  device = bdev.Create(disk.dev_type, disk.physical_id,
780 a8083063 Iustin Pop
                       clist, size)
781 a8083063 Iustin Pop
  if device is None:
782 a8083063 Iustin Pop
    raise ValueError("Can't create child device for %s, %s" %
783 a8083063 Iustin Pop
                     (disk, size))
784 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
785 cf5a8306 Iustin Pop
    if not device.Assemble():
786 20a0c9ef Guido Trotter
      errorstring = "Can't assemble device after creation"
787 18682bca Iustin Pop
      logging.error(errorstring)
788 20a0c9ef Guido Trotter
      raise errors.BlockDeviceError("%s, very unusual event - check the node"
789 20a0c9ef Guido Trotter
                                    " daemon logs" % errorstring)
790 e31c43f7 Michael Hanselmann
    device.SetSyncSpeed(constants.SYNC_SPEED)
791 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
792 a8083063 Iustin Pop
      device.Open(force=True)
793 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
794 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
795 a0c3fea1 Michael Hanselmann
796 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
797 a0c3fea1 Michael Hanselmann
798 a8083063 Iustin Pop
  physical_id = device.unique_id
799 a8083063 Iustin Pop
  return physical_id
800 a8083063 Iustin Pop
801 a8083063 Iustin Pop
802 a8083063 Iustin Pop
def RemoveBlockDevice(disk):
803 a8083063 Iustin Pop
  """Remove a block device.
804 a8083063 Iustin Pop

805 a8083063 Iustin Pop
  This is intended to be called recursively.
806 a8083063 Iustin Pop

807 a8083063 Iustin Pop
  """
808 a8083063 Iustin Pop
  try:
809 a8083063 Iustin Pop
    # since we are removing the device, allow a partial match
810 a8083063 Iustin Pop
    # this allows removal of broken mirrors
811 a8083063 Iustin Pop
    rdev = _RecursiveFindBD(disk, allow_partial=True)
812 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
813 a8083063 Iustin Pop
    # probably can't attach
814 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
815 a8083063 Iustin Pop
    rdev = None
816 a8083063 Iustin Pop
  if rdev is not None:
817 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
818 a8083063 Iustin Pop
    result = rdev.Remove()
819 3f78eef2 Iustin Pop
    if result:
820 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
821 a8083063 Iustin Pop
  else:
822 a8083063 Iustin Pop
    result = True
823 a8083063 Iustin Pop
  if disk.children:
824 a8083063 Iustin Pop
    for child in disk.children:
825 a8083063 Iustin Pop
      result = result and RemoveBlockDevice(child)
826 a8083063 Iustin Pop
  return result
827 a8083063 Iustin Pop
828 a8083063 Iustin Pop
829 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
830 a8083063 Iustin Pop
  """Activate a block device for an instance.
831 a8083063 Iustin Pop

832 a8083063 Iustin Pop
  This is run on the primary and secondary nodes for an instance.
833 a8083063 Iustin Pop

834 a8083063 Iustin Pop
  This function is called recursively.
835 a8083063 Iustin Pop

836 a8083063 Iustin Pop
  Args:
837 a8083063 Iustin Pop
    disk: a objects.Disk object
838 a8083063 Iustin Pop
    as_primary: if we should make the block device read/write
839 a8083063 Iustin Pop

840 a8083063 Iustin Pop
  Returns:
841 a8083063 Iustin Pop
    the assembled device or None (in case no device was assembled)
842 a8083063 Iustin Pop

843 a8083063 Iustin Pop
  If the assembly is not successful, an exception is raised.
844 a8083063 Iustin Pop

845 a8083063 Iustin Pop
  """
846 a8083063 Iustin Pop
  children = []
847 a8083063 Iustin Pop
  if disk.children:
848 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
849 fc1dc9d7 Iustin Pop
    if mcn == -1:
850 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
851 fc1dc9d7 Iustin Pop
    else:
852 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
853 a8083063 Iustin Pop
    for chld_disk in disk.children:
854 fc1dc9d7 Iustin Pop
      try:
855 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
856 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
857 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
858 fc1dc9d7 Iustin Pop
          raise
859 fc1dc9d7 Iustin Pop
        cdev = None
860 18682bca Iustin Pop
        logging.debug("Error in child activation: %s", str(err))
861 fc1dc9d7 Iustin Pop
      children.append(cdev)
862 a8083063 Iustin Pop
863 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
864 a8083063 Iustin Pop
    r_dev = bdev.AttachOrAssemble(disk.dev_type, disk.physical_id, children)
865 e31c43f7 Michael Hanselmann
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
866 a8083063 Iustin Pop
    result = r_dev
867 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
868 a8083063 Iustin Pop
      r_dev.Open()
869 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
870 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
871 3f78eef2 Iustin Pop
872 a8083063 Iustin Pop
  else:
873 a8083063 Iustin Pop
    result = True
874 a8083063 Iustin Pop
  return result
875 a8083063 Iustin Pop
876 a8083063 Iustin Pop
877 3f78eef2 Iustin Pop
def AssembleBlockDevice(disk, owner, as_primary):
878 a8083063 Iustin Pop
  """Activate a block device for an instance.
879 a8083063 Iustin Pop

880 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
881 a8083063 Iustin Pop

882 a8083063 Iustin Pop
  Returns:
883 a8083063 Iustin Pop
    a /dev path for primary nodes
884 a8083063 Iustin Pop
    True for secondary nodes
885 a8083063 Iustin Pop

886 a8083063 Iustin Pop
  """
887 3f78eef2 Iustin Pop
  result = _RecursiveAssembleBD(disk, owner, as_primary)
888 a8083063 Iustin Pop
  if isinstance(result, bdev.BlockDev):
889 a8083063 Iustin Pop
    result = result.dev_path
890 a8083063 Iustin Pop
  return result
891 a8083063 Iustin Pop
892 a8083063 Iustin Pop
893 a8083063 Iustin Pop
def ShutdownBlockDevice(disk):
894 a8083063 Iustin Pop
  """Shut down a block device.
895 a8083063 Iustin Pop

896 a8083063 Iustin Pop
  First, if the device is assembled (can `Attach()`), then the device
897 a8083063 Iustin Pop
  is shutdown. Then the children of the device are shutdown.
898 a8083063 Iustin Pop

899 a8083063 Iustin Pop
  This function is called recursively. Note that we don't cache the
900 a8083063 Iustin Pop
  children or such, as oppossed to assemble, shutdown of different
901 a8083063 Iustin Pop
  devices doesn't require that the upper device was active.
902 a8083063 Iustin Pop

903 a8083063 Iustin Pop
  """
904 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
905 a8083063 Iustin Pop
  if r_dev is not None:
906 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
907 a8083063 Iustin Pop
    result = r_dev.Shutdown()
908 3f78eef2 Iustin Pop
    if result:
909 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
910 a8083063 Iustin Pop
  else:
911 a8083063 Iustin Pop
    result = True
912 a8083063 Iustin Pop
  if disk.children:
913 a8083063 Iustin Pop
    for child in disk.children:
914 a8083063 Iustin Pop
      result = result and ShutdownBlockDevice(child)
915 a8083063 Iustin Pop
  return result
916 a8083063 Iustin Pop
917 a8083063 Iustin Pop
918 153d9724 Iustin Pop
def MirrorAddChildren(parent_cdev, new_cdevs):
919 153d9724 Iustin Pop
  """Extend a mirrored block device.
920 a8083063 Iustin Pop

921 a8083063 Iustin Pop
  """
922 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev, allow_partial=True)
923 153d9724 Iustin Pop
  if parent_bdev is None:
924 18682bca Iustin Pop
    logging.error("Can't find parent device")
925 a8083063 Iustin Pop
    return False
926 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
927 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
928 18682bca Iustin Pop
    logging.error("Can't find new device(s) to add: %s:%s",
929 18682bca Iustin Pop
                  new_bdevs, new_cdevs)
930 a8083063 Iustin Pop
    return False
931 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
932 a8083063 Iustin Pop
  return True
933 a8083063 Iustin Pop
934 a8083063 Iustin Pop
935 153d9724 Iustin Pop
def MirrorRemoveChildren(parent_cdev, new_cdevs):
936 153d9724 Iustin Pop
  """Shrink a mirrored block device.
937 a8083063 Iustin Pop

938 a8083063 Iustin Pop
  """
939 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
940 153d9724 Iustin Pop
  if parent_bdev is None:
941 18682bca Iustin Pop
    logging.error("Can't find parent in remove children: %s", parent_cdev)
942 a8083063 Iustin Pop
    return False
943 e739bd57 Iustin Pop
  devs = []
944 e739bd57 Iustin Pop
  for disk in new_cdevs:
945 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
946 e739bd57 Iustin Pop
    if rpath is None:
947 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
948 e739bd57 Iustin Pop
      if bd is None:
949 18682bca Iustin Pop
        logging.error("Can't find dynamic device %s while removing children",
950 18682bca Iustin Pop
                      disk)
951 e739bd57 Iustin Pop
        return False
952 e739bd57 Iustin Pop
      else:
953 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
954 e739bd57 Iustin Pop
    else:
955 e739bd57 Iustin Pop
      devs.append(rpath)
956 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
957 a8083063 Iustin Pop
  return True
958 a8083063 Iustin Pop
959 a8083063 Iustin Pop
960 a8083063 Iustin Pop
def GetMirrorStatus(disks):
961 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
962 a8083063 Iustin Pop

963 a8083063 Iustin Pop
  Args:
964 a8083063 Iustin Pop
    disks: list of `objects.Disk`
965 a8083063 Iustin Pop

966 a8083063 Iustin Pop
  Returns:
967 a8083063 Iustin Pop
    list of (mirror_done, estimated_time) tuples, which
968 a8083063 Iustin Pop
    are the result of bdev.BlockDevice.CombinedSyncStatus()
969 a8083063 Iustin Pop

970 a8083063 Iustin Pop
  """
971 a8083063 Iustin Pop
  stats = []
972 a8083063 Iustin Pop
  for dsk in disks:
973 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
974 a8083063 Iustin Pop
    if rbd is None:
975 3ecf6786 Iustin Pop
      raise errors.BlockDeviceError("Can't find device %s" % str(dsk))
976 a8083063 Iustin Pop
    stats.append(rbd.CombinedSyncStatus())
977 a8083063 Iustin Pop
  return stats
978 a8083063 Iustin Pop
979 a8083063 Iustin Pop
980 a8083063 Iustin Pop
def _RecursiveFindBD(disk, allow_partial=False):
981 a8083063 Iustin Pop
  """Check if a device is activated.
982 a8083063 Iustin Pop

983 a8083063 Iustin Pop
  If so, return informations about the real device.
984 a8083063 Iustin Pop

985 a8083063 Iustin Pop
  Args:
986 a8083063 Iustin Pop
    disk: the objects.Disk instance
987 a8083063 Iustin Pop
    allow_partial: don't abort the find if a child of the
988 a8083063 Iustin Pop
                   device can't be found; this is intended to be
989 a8083063 Iustin Pop
                   used when repairing mirrors
990 a8083063 Iustin Pop

991 a8083063 Iustin Pop
  Returns:
992 a8083063 Iustin Pop
    None if the device can't be found
993 a8083063 Iustin Pop
    otherwise the device instance
994 a8083063 Iustin Pop

995 a8083063 Iustin Pop
  """
996 a8083063 Iustin Pop
  children = []
997 a8083063 Iustin Pop
  if disk.children:
998 a8083063 Iustin Pop
    for chdisk in disk.children:
999 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
1000 a8083063 Iustin Pop
1001 a8083063 Iustin Pop
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children)
1002 a8083063 Iustin Pop
1003 a8083063 Iustin Pop
1004 a8083063 Iustin Pop
def FindBlockDevice(disk):
1005 a8083063 Iustin Pop
  """Check if a device is activated.
1006 a8083063 Iustin Pop

1007 a8083063 Iustin Pop
  If so, return informations about the real device.
1008 a8083063 Iustin Pop

1009 a8083063 Iustin Pop
  Args:
1010 a8083063 Iustin Pop
    disk: the objects.Disk instance
1011 a8083063 Iustin Pop
  Returns:
1012 a8083063 Iustin Pop
    None if the device can't be found
1013 a8083063 Iustin Pop
    (device_path, major, minor, sync_percent, estimated_time, is_degraded)
1014 a8083063 Iustin Pop

1015 a8083063 Iustin Pop
  """
1016 a8083063 Iustin Pop
  rbd = _RecursiveFindBD(disk)
1017 a8083063 Iustin Pop
  if rbd is None:
1018 a8083063 Iustin Pop
    return rbd
1019 0834c866 Iustin Pop
  return (rbd.dev_path, rbd.major, rbd.minor) + rbd.GetSyncStatus()
1020 a8083063 Iustin Pop
1021 a8083063 Iustin Pop
1022 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1023 a8083063 Iustin Pop
  """Write a file to the filesystem.
1024 a8083063 Iustin Pop

1025 a8083063 Iustin Pop
  This allows the master to overwrite(!) a file. It will only perform
1026 a8083063 Iustin Pop
  the operation if the file belongs to a list of configuration files.
1027 a8083063 Iustin Pop

1028 a8083063 Iustin Pop
  """
1029 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
1030 18682bca Iustin Pop
    logging.error("Filename passed to UploadFile is not absolute: '%s'",
1031 18682bca Iustin Pop
                  file_name)
1032 a8083063 Iustin Pop
    return False
1033 a8083063 Iustin Pop
1034 97628462 Iustin Pop
  allowed_files = [
1035 97628462 Iustin Pop
    constants.CLUSTER_CONF_FILE,
1036 97628462 Iustin Pop
    constants.ETC_HOSTS,
1037 97628462 Iustin Pop
    constants.SSH_KNOWN_HOSTS_FILE,
1038 90fae627 Guido Trotter
    constants.VNC_PASSWORD_FILE,
1039 c3f0a12f Iustin Pop
    constants.JOB_QUEUE_SERIAL_FILE,
1040 97628462 Iustin Pop
    ]
1041 880478f8 Iustin Pop
  allowed_files.extend(ssconf.SimpleStore().GetFileList())
1042 880478f8 Iustin Pop
  if file_name not in allowed_files:
1043 18682bca Iustin Pop
    logging.error("Filename passed to UploadFile not in allowed"
1044 18682bca Iustin Pop
                 " upload targets: '%s'", file_name)
1045 a8083063 Iustin Pop
    return False
1046 a8083063 Iustin Pop
1047 41a57aab Michael Hanselmann
  utils.WriteFile(file_name, data=data, mode=mode, uid=uid, gid=gid,
1048 41a57aab Michael Hanselmann
                  atime=atime, mtime=mtime)
1049 a8083063 Iustin Pop
  return True
1050 a8083063 Iustin Pop
1051 386b57af Iustin Pop
1052 a8083063 Iustin Pop
def _ErrnoOrStr(err):
1053 a8083063 Iustin Pop
  """Format an EnvironmentError exception.
1054 a8083063 Iustin Pop

1055 a8083063 Iustin Pop
  If the `err` argument has an errno attribute, it will be looked up
1056 a8083063 Iustin Pop
  and converted into a textual EXXXX description. Otherwise the string
1057 a8083063 Iustin Pop
  representation of the error will be returned.
1058 a8083063 Iustin Pop

1059 a8083063 Iustin Pop
  """
1060 a8083063 Iustin Pop
  if hasattr(err, 'errno'):
1061 a8083063 Iustin Pop
    detail = errno.errorcode[err.errno]
1062 a8083063 Iustin Pop
  else:
1063 a8083063 Iustin Pop
    detail = str(err)
1064 a8083063 Iustin Pop
  return detail
1065 a8083063 Iustin Pop
1066 5d0fe286 Iustin Pop
1067 c26dabd7 Guido Trotter
def _OSOndiskVersion(name, os_dir):
1068 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
1069 a8083063 Iustin Pop

1070 2f8598a5 Alexander Schreiber
  This function will try to read the API version of the os given by
1071 7c3d51d4 Guido Trotter
  the 'name' parameter and residing in the 'os_dir' directory.
1072 7c3d51d4 Guido Trotter

1073 7c3d51d4 Guido Trotter
  Return value will be either an integer denoting the version or None in the
1074 7c3d51d4 Guido Trotter
  case when this is not a valid OS name.
1075 a8083063 Iustin Pop

1076 a8083063 Iustin Pop
  """
1077 a8083063 Iustin Pop
  api_file = os.path.sep.join([os_dir, "ganeti_api_version"])
1078 a8083063 Iustin Pop
1079 a8083063 Iustin Pop
  try:
1080 a8083063 Iustin Pop
    st = os.stat(api_file)
1081 a8083063 Iustin Pop
  except EnvironmentError, err:
1082 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "'ganeti_api_version' file not"
1083 3ecf6786 Iustin Pop
                           " found (%s)" % _ErrnoOrStr(err))
1084 a8083063 Iustin Pop
1085 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1086 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "'ganeti_api_version' file is not"
1087 3ecf6786 Iustin Pop
                           " a regular file")
1088 a8083063 Iustin Pop
1089 a8083063 Iustin Pop
  try:
1090 a8083063 Iustin Pop
    f = open(api_file)
1091 a8083063 Iustin Pop
    try:
1092 a8083063 Iustin Pop
      api_version = f.read(256)
1093 a8083063 Iustin Pop
    finally:
1094 a8083063 Iustin Pop
      f.close()
1095 a8083063 Iustin Pop
  except EnvironmentError, err:
1096 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "error while reading the"
1097 3ecf6786 Iustin Pop
                           " API version (%s)" % _ErrnoOrStr(err))
1098 a8083063 Iustin Pop
1099 a8083063 Iustin Pop
  api_version = api_version.strip()
1100 a8083063 Iustin Pop
  try:
1101 a8083063 Iustin Pop
    api_version = int(api_version)
1102 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
1103 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir,
1104 305a7297 Guido Trotter
                           "API version is not integer (%s)" % str(err))
1105 a8083063 Iustin Pop
1106 a8083063 Iustin Pop
  return api_version
1107 a8083063 Iustin Pop
1108 386b57af Iustin Pop
1109 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
1110 a8083063 Iustin Pop
  """Compute the validity for all OSes.
1111 a8083063 Iustin Pop

1112 8fa42c7c Guido Trotter
  Returns an OS object for each name in all the given top directories
1113 8fa42c7c Guido Trotter
  (if not given defaults to constants.OS_SEARCH_PATH)
1114 a8083063 Iustin Pop

1115 a8083063 Iustin Pop
  Returns:
1116 8fa42c7c Guido Trotter
    list of OS objects
1117 a8083063 Iustin Pop

1118 a8083063 Iustin Pop
  """
1119 7c3d51d4 Guido Trotter
  if top_dirs is None:
1120 7c3d51d4 Guido Trotter
    top_dirs = constants.OS_SEARCH_PATH
1121 a8083063 Iustin Pop
1122 a8083063 Iustin Pop
  result = []
1123 65fe4693 Iustin Pop
  for dir_name in top_dirs:
1124 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
1125 7c3d51d4 Guido Trotter
      try:
1126 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
1127 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
1128 18682bca Iustin Pop
        logging.exception("Can't list the OS directory %s", dir_name)
1129 7c3d51d4 Guido Trotter
        break
1130 7c3d51d4 Guido Trotter
      for name in f_names:
1131 7c3d51d4 Guido Trotter
        try:
1132 65fe4693 Iustin Pop
          os_inst = OSFromDisk(name, base_dir=dir_name)
1133 7c3d51d4 Guido Trotter
          result.append(os_inst)
1134 7c3d51d4 Guido Trotter
        except errors.InvalidOS, err:
1135 8fa42c7c Guido Trotter
          result.append(objects.OS.FromInvalidOS(err))
1136 a8083063 Iustin Pop
1137 a8083063 Iustin Pop
  return result
1138 a8083063 Iustin Pop
1139 a8083063 Iustin Pop
1140 56bcd3f4 Guido Trotter
def OSFromDisk(name, base_dir=None):
1141 a8083063 Iustin Pop
  """Create an OS instance from disk.
1142 a8083063 Iustin Pop

1143 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
1144 a8083063 Iustin Pop
  valid OS name. Otherwise, it will raise an appropriate
1145 a8083063 Iustin Pop
  `errors.InvalidOS` exception, detailing why this is not a valid
1146 a8083063 Iustin Pop
  OS.
1147 a8083063 Iustin Pop

1148 7c3d51d4 Guido Trotter
  Args:
1149 7c3d51d4 Guido Trotter
    os_dir: Directory containing the OS scripts. Defaults to a search
1150 7c3d51d4 Guido Trotter
            in all the OS_SEARCH_PATH directories.
1151 7c3d51d4 Guido Trotter

1152 a8083063 Iustin Pop
  """
1153 7c3d51d4 Guido Trotter
1154 56bcd3f4 Guido Trotter
  if base_dir is None:
1155 57c177af Iustin Pop
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1156 c34c0cfd Iustin Pop
    if os_dir is None:
1157 c34c0cfd Iustin Pop
      raise errors.InvalidOS(name, None, "OS dir not found in search path")
1158 c34c0cfd Iustin Pop
  else:
1159 c34c0cfd Iustin Pop
    os_dir = os.path.sep.join([base_dir, name])
1160 a8083063 Iustin Pop
1161 c26dabd7 Guido Trotter
  api_version = _OSOndiskVersion(name, os_dir)
1162 a8083063 Iustin Pop
1163 a8083063 Iustin Pop
  if api_version != constants.OS_API_VERSION:
1164 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "API version mismatch"
1165 305a7297 Guido Trotter
                           " (found %s want %s)"
1166 3ecf6786 Iustin Pop
                           % (api_version, constants.OS_API_VERSION))
1167 a8083063 Iustin Pop
1168 a8083063 Iustin Pop
  # OS Scripts dictionary, we will populate it with the actual script names
1169 386b57af Iustin Pop
  os_scripts = {'create': '', 'export': '', 'import': '', 'rename': ''}
1170 a8083063 Iustin Pop
1171 a8083063 Iustin Pop
  for script in os_scripts:
1172 a8083063 Iustin Pop
    os_scripts[script] = os.path.sep.join([os_dir, script])
1173 a8083063 Iustin Pop
1174 a8083063 Iustin Pop
    try:
1175 a8083063 Iustin Pop
      st = os.stat(os_scripts[script])
1176 a8083063 Iustin Pop
    except EnvironmentError, err:
1177 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' script missing (%s)" %
1178 3ecf6786 Iustin Pop
                             (script, _ErrnoOrStr(err)))
1179 a8083063 Iustin Pop
1180 a8083063 Iustin Pop
    if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1181 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' script not executable" %
1182 305a7297 Guido Trotter
                             script)
1183 a8083063 Iustin Pop
1184 a8083063 Iustin Pop
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1185 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' is not a regular file" %
1186 305a7297 Guido Trotter
                             script)
1187 a8083063 Iustin Pop
1188 a8083063 Iustin Pop
1189 8fa42c7c Guido Trotter
  return objects.OS(name=name, path=os_dir, status=constants.OS_VALID_STATUS,
1190 a8083063 Iustin Pop
                    create_script=os_scripts['create'],
1191 a8083063 Iustin Pop
                    export_script=os_scripts['export'],
1192 a8083063 Iustin Pop
                    import_script=os_scripts['import'],
1193 386b57af Iustin Pop
                    rename_script=os_scripts['rename'],
1194 a8083063 Iustin Pop
                    api_version=api_version)
1195 a8083063 Iustin Pop
1196 a8083063 Iustin Pop
1197 594609c0 Iustin Pop
def GrowBlockDevice(disk, amount):
1198 594609c0 Iustin Pop
  """Grow a stack of block devices.
1199 594609c0 Iustin Pop

1200 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
1201 594609c0 Iustin Pop
  first one resize.
1202 594609c0 Iustin Pop

1203 594609c0 Iustin Pop
  Args:
1204 594609c0 Iustin Pop
    disk: the disk to be grown
1205 594609c0 Iustin Pop

1206 594609c0 Iustin Pop
  Returns: a tuple of (status, result), with:
1207 594609c0 Iustin Pop
    status: the result (true/false) of the operation
1208 594609c0 Iustin Pop
    result: the error message if the operation failed, otherwise not used
1209 594609c0 Iustin Pop

1210 594609c0 Iustin Pop
  """
1211 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1212 594609c0 Iustin Pop
  if r_dev is None:
1213 594609c0 Iustin Pop
    return False, "Cannot find block device %s" % (disk,)
1214 594609c0 Iustin Pop
1215 594609c0 Iustin Pop
  try:
1216 594609c0 Iustin Pop
    r_dev.Grow(amount)
1217 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
1218 594609c0 Iustin Pop
    return False, str(err)
1219 594609c0 Iustin Pop
1220 594609c0 Iustin Pop
  return True, None
1221 594609c0 Iustin Pop
1222 594609c0 Iustin Pop
1223 a8083063 Iustin Pop
def SnapshotBlockDevice(disk):
1224 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
1225 a8083063 Iustin Pop

1226 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
1227 a8083063 Iustin Pop
  just for the leaf lvm backend device.
1228 a8083063 Iustin Pop

1229 a8083063 Iustin Pop
  Args:
1230 a8083063 Iustin Pop
    disk: the disk to be snapshotted
1231 a8083063 Iustin Pop

1232 a8083063 Iustin Pop
  Returns:
1233 a8083063 Iustin Pop
    a config entry for the actual lvm device snapshotted.
1234 a8083063 Iustin Pop

1235 098c0958 Michael Hanselmann
  """
1236 a8083063 Iustin Pop
  if disk.children:
1237 a8083063 Iustin Pop
    if len(disk.children) == 1:
1238 a8083063 Iustin Pop
      # only one child, let's recurse on it
1239 a8083063 Iustin Pop
      return SnapshotBlockDevice(disk.children[0])
1240 a8083063 Iustin Pop
    else:
1241 a8083063 Iustin Pop
      # more than one child, choose one that matches
1242 a8083063 Iustin Pop
      for child in disk.children:
1243 a8083063 Iustin Pop
        if child.size == disk.size:
1244 a8083063 Iustin Pop
          # return implies breaking the loop
1245 a8083063 Iustin Pop
          return SnapshotBlockDevice(child)
1246 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
1247 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
1248 a8083063 Iustin Pop
    if r_dev is not None:
1249 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
1250 a8083063 Iustin Pop
      return r_dev.Snapshot(disk.size)
1251 a8083063 Iustin Pop
    else:
1252 a8083063 Iustin Pop
      return None
1253 a8083063 Iustin Pop
  else:
1254 3ecf6786 Iustin Pop
    raise errors.ProgrammerError("Cannot snapshot non-lvm block device"
1255 f4bc1f2c Michael Hanselmann
                                 " '%s' of type '%s'" %
1256 3ecf6786 Iustin Pop
                                 (disk.unique_id, disk.dev_type))
1257 a8083063 Iustin Pop
1258 a8083063 Iustin Pop
1259 a8083063 Iustin Pop
def ExportSnapshot(disk, dest_node, instance):
1260 a8083063 Iustin Pop
  """Export a block device snapshot to a remote node.
1261 a8083063 Iustin Pop

1262 a8083063 Iustin Pop
  Args:
1263 a8083063 Iustin Pop
    disk: the snapshot block device
1264 a8083063 Iustin Pop
    dest_node: the node to send the image to
1265 a8083063 Iustin Pop
    instance: instance being exported
1266 a8083063 Iustin Pop

1267 a8083063 Iustin Pop
  Returns:
1268 a8083063 Iustin Pop
    True if successful, False otherwise.
1269 a8083063 Iustin Pop

1270 098c0958 Michael Hanselmann
  """
1271 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1272 a8083063 Iustin Pop
  export_script = inst_os.export_script
1273 a8083063 Iustin Pop
1274 a8083063 Iustin Pop
  logfile = "%s/exp-%s-%s-%s.log" % (constants.LOG_OS_DIR, inst_os.name,
1275 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
1276 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
1277 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
1278 a8083063 Iustin Pop
1279 a8083063 Iustin Pop
  real_os_dev = _RecursiveFindBD(disk)
1280 a8083063 Iustin Pop
  if real_os_dev is None:
1281 a8083063 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
1282 a8083063 Iustin Pop
                                  str(disk))
1283 a8083063 Iustin Pop
  real_os_dev.Open()
1284 a8083063 Iustin Pop
1285 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1286 a8083063 Iustin Pop
  destfile = disk.physical_id[1]
1287 a8083063 Iustin Pop
1288 a8083063 Iustin Pop
  # the target command is built out of three individual commands,
1289 a8083063 Iustin Pop
  # which are joined by pipes; we check each individual command for
1290 a8083063 Iustin Pop
  # valid parameters
1291 a8083063 Iustin Pop
1292 a8083063 Iustin Pop
  expcmd = utils.BuildShellCmd("cd %s; %s -i %s -b %s 2>%s", inst_os.path,
1293 a8083063 Iustin Pop
                               export_script, instance.name,
1294 a8083063 Iustin Pop
                               real_os_dev.dev_path, logfile)
1295 a8083063 Iustin Pop
1296 a8083063 Iustin Pop
  comprcmd = "gzip"
1297 a8083063 Iustin Pop
1298 72f0f7fd Iustin Pop
  destcmd = utils.BuildShellCmd("mkdir -p %s && cat > %s/%s",
1299 00003458 Guido Trotter
                                destdir, destdir, destfile)
1300 c92b310a Michael Hanselmann
  remotecmd = _GetSshRunner().BuildCmd(dest_node, constants.GANETI_RUNAS,
1301 c92b310a Michael Hanselmann
                                       destcmd)
1302 a8083063 Iustin Pop
1303 a8083063 Iustin Pop
  # all commands have been checked, so we're safe to combine them
1304 72f0f7fd Iustin Pop
  command = '|'.join([expcmd, comprcmd, utils.ShellQuoteArgs(remotecmd)])
1305 a8083063 Iustin Pop
1306 a8083063 Iustin Pop
  result = utils.RunCmd(command)
1307 a8083063 Iustin Pop
1308 a8083063 Iustin Pop
  if result.failed:
1309 18682bca Iustin Pop
    logging.error("os snapshot export command '%s' returned error: %s"
1310 18682bca Iustin Pop
                  " output: %s", command, result.fail_reason, result.output)
1311 a8083063 Iustin Pop
    return False
1312 a8083063 Iustin Pop
1313 a8083063 Iustin Pop
  return True
1314 a8083063 Iustin Pop
1315 a8083063 Iustin Pop
1316 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
1317 a8083063 Iustin Pop
  """Write out the export configuration information.
1318 a8083063 Iustin Pop

1319 a8083063 Iustin Pop
  Args:
1320 a8083063 Iustin Pop
    instance: instance configuration
1321 a8083063 Iustin Pop
    snap_disks: snapshot block devices
1322 a8083063 Iustin Pop

1323 a8083063 Iustin Pop
  Returns:
1324 a8083063 Iustin Pop
    False in case of error, True otherwise.
1325 a8083063 Iustin Pop

1326 098c0958 Michael Hanselmann
  """
1327 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1328 a8083063 Iustin Pop
  finaldestdir = os.path.join(constants.EXPORT_DIR, instance.name)
1329 a8083063 Iustin Pop
1330 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1331 a8083063 Iustin Pop
1332 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
1333 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'version', '0')
1334 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
1335 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'source', instance.primary_node)
1336 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'os', instance.os)
1337 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'compression', 'gzip')
1338 a8083063 Iustin Pop
1339 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
1340 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'name', instance.name)
1341 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'memory', '%d' % instance.memory)
1342 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'vcpus', '%d' % instance.vcpus)
1343 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
1344 66f93869 Manuel Franceschini
1345 66f93869 Manuel Franceschini
  nic_count = 0
1346 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
1347 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_mac' %
1348 a8083063 Iustin Pop
               nic_count, '%s' % nic.mac)
1349 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
1350 1cafd236 Guido Trotter
    config.set(constants.INISECT_INS, 'nic%d_bridge' % nic_count, '%s' % nic.bridge)
1351 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
1352 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_count)
1353 a8083063 Iustin Pop
1354 66f93869 Manuel Franceschini
  disk_count = 0
1355 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
1356 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
1357 a8083063 Iustin Pop
               ('%s' % disk.iv_name))
1358 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
1359 a8083063 Iustin Pop
               ('%s' % disk.physical_id[1]))
1360 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
1361 a8083063 Iustin Pop
               ('%d' % disk.size))
1362 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_count)
1363 a8083063 Iustin Pop
1364 a8083063 Iustin Pop
  cff = os.path.join(destdir, constants.EXPORT_CONF_FILE)
1365 a8083063 Iustin Pop
  cfo = open(cff, 'w')
1366 a8083063 Iustin Pop
  try:
1367 a8083063 Iustin Pop
    config.write(cfo)
1368 a8083063 Iustin Pop
  finally:
1369 a8083063 Iustin Pop
    cfo.close()
1370 a8083063 Iustin Pop
1371 a8083063 Iustin Pop
  shutil.rmtree(finaldestdir, True)
1372 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
1373 a8083063 Iustin Pop
1374 a8083063 Iustin Pop
  return True
1375 a8083063 Iustin Pop
1376 a8083063 Iustin Pop
1377 a8083063 Iustin Pop
def ExportInfo(dest):
1378 a8083063 Iustin Pop
  """Get export configuration information.
1379 a8083063 Iustin Pop

1380 a8083063 Iustin Pop
  Args:
1381 a8083063 Iustin Pop
    dest: directory containing the export
1382 a8083063 Iustin Pop

1383 a8083063 Iustin Pop
  Returns:
1384 a8083063 Iustin Pop
    A serializable config file containing the export info.
1385 a8083063 Iustin Pop

1386 a8083063 Iustin Pop
  """
1387 a8083063 Iustin Pop
  cff = os.path.join(dest, constants.EXPORT_CONF_FILE)
1388 a8083063 Iustin Pop
1389 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1390 a8083063 Iustin Pop
  config.read(cff)
1391 a8083063 Iustin Pop
1392 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
1393 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
1394 a8083063 Iustin Pop
    return None
1395 a8083063 Iustin Pop
1396 a8083063 Iustin Pop
  return config
1397 a8083063 Iustin Pop
1398 a8083063 Iustin Pop
1399 a8083063 Iustin Pop
def ImportOSIntoInstance(instance, os_disk, swap_disk, src_node, src_image):
1400 a8083063 Iustin Pop
  """Import an os image into an instance.
1401 a8083063 Iustin Pop

1402 a8083063 Iustin Pop
  Args:
1403 a8083063 Iustin Pop
    instance: the instance object
1404 a8083063 Iustin Pop
    os_disk: the instance-visible name of the os device
1405 a8083063 Iustin Pop
    swap_disk: the instance-visible name of the swap device
1406 a8083063 Iustin Pop
    src_node: node holding the source image
1407 a8083063 Iustin Pop
    src_image: path to the source image on src_node
1408 a8083063 Iustin Pop

1409 a8083063 Iustin Pop
  Returns:
1410 a8083063 Iustin Pop
    False in case of error, True otherwise.
1411 a8083063 Iustin Pop

1412 a8083063 Iustin Pop
  """
1413 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1414 a8083063 Iustin Pop
  import_script = inst_os.import_script
1415 a8083063 Iustin Pop
1416 9716fdce Iustin Pop
  os_device = instance.FindDisk(os_disk)
1417 9716fdce Iustin Pop
  if os_device is None:
1418 18682bca Iustin Pop
    logging.error("Can't find this device-visible name '%s'", os_disk)
1419 a8083063 Iustin Pop
    return False
1420 a8083063 Iustin Pop
1421 9716fdce Iustin Pop
  swap_device = instance.FindDisk(swap_disk)
1422 9716fdce Iustin Pop
  if swap_device is None:
1423 18682bca Iustin Pop
    logging.error("Can't find this device-visible name '%s'", swap_disk)
1424 a8083063 Iustin Pop
    return False
1425 a8083063 Iustin Pop
1426 a8083063 Iustin Pop
  real_os_dev = _RecursiveFindBD(os_device)
1427 a8083063 Iustin Pop
  if real_os_dev is None:
1428 3ecf6786 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
1429 3ecf6786 Iustin Pop
                                  str(os_device))
1430 a8083063 Iustin Pop
  real_os_dev.Open()
1431 a8083063 Iustin Pop
1432 a8083063 Iustin Pop
  real_swap_dev = _RecursiveFindBD(swap_device)
1433 a8083063 Iustin Pop
  if real_swap_dev is None:
1434 3ecf6786 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
1435 3ecf6786 Iustin Pop
                                  str(swap_device))
1436 a8083063 Iustin Pop
  real_swap_dev.Open()
1437 a8083063 Iustin Pop
1438 a8083063 Iustin Pop
  logfile = "%s/import-%s-%s-%s.log" % (constants.LOG_OS_DIR, instance.os,
1439 a8083063 Iustin Pop
                                        instance.name, int(time.time()))
1440 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
1441 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
1442 a8083063 Iustin Pop
1443 00003458 Guido Trotter
  destcmd = utils.BuildShellCmd('cat %s', src_image)
1444 c92b310a Michael Hanselmann
  remotecmd = _GetSshRunner().BuildCmd(src_node, constants.GANETI_RUNAS,
1445 c92b310a Michael Hanselmann
                                       destcmd)
1446 a8083063 Iustin Pop
1447 a8083063 Iustin Pop
  comprcmd = "gunzip"
1448 a8083063 Iustin Pop
  impcmd = utils.BuildShellCmd("(cd %s; %s -i %s -b %s -s %s &>%s)",
1449 a8083063 Iustin Pop
                               inst_os.path, import_script, instance.name,
1450 a8083063 Iustin Pop
                               real_os_dev.dev_path, real_swap_dev.dev_path,
1451 a8083063 Iustin Pop
                               logfile)
1452 a8083063 Iustin Pop
1453 72f0f7fd Iustin Pop
  command = '|'.join([utils.ShellQuoteArgs(remotecmd), comprcmd, impcmd])
1454 a8083063 Iustin Pop
1455 a8083063 Iustin Pop
  result = utils.RunCmd(command)
1456 a8083063 Iustin Pop
1457 a8083063 Iustin Pop
  if result.failed:
1458 18682bca Iustin Pop
    logging.error("os import command '%s' returned error: %s"
1459 18682bca Iustin Pop
                  " output: %s", command, result.fail_reason, result.output)
1460 a8083063 Iustin Pop
    return False
1461 a8083063 Iustin Pop
1462 a8083063 Iustin Pop
  return True
1463 a8083063 Iustin Pop
1464 a8083063 Iustin Pop
1465 a8083063 Iustin Pop
def ListExports():
1466 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
1467 098c0958 Michael Hanselmann

1468 a8083063 Iustin Pop
  """
1469 a8083063 Iustin Pop
  if os.path.isdir(constants.EXPORT_DIR):
1470 eedbda4b Michael Hanselmann
    return utils.ListVisibleFiles(constants.EXPORT_DIR)
1471 a8083063 Iustin Pop
  else:
1472 a8083063 Iustin Pop
    return []
1473 a8083063 Iustin Pop
1474 a8083063 Iustin Pop
1475 a8083063 Iustin Pop
def RemoveExport(export):
1476 a8083063 Iustin Pop
  """Remove an existing export from the node.
1477 a8083063 Iustin Pop

1478 a8083063 Iustin Pop
  Args:
1479 a8083063 Iustin Pop
    export: the name of the export to remove
1480 a8083063 Iustin Pop

1481 a8083063 Iustin Pop
  Returns:
1482 a8083063 Iustin Pop
    False in case of error, True otherwise.
1483 a8083063 Iustin Pop

1484 098c0958 Michael Hanselmann
  """
1485 a8083063 Iustin Pop
  target = os.path.join(constants.EXPORT_DIR, export)
1486 a8083063 Iustin Pop
1487 a8083063 Iustin Pop
  shutil.rmtree(target)
1488 a8083063 Iustin Pop
  # TODO: catch some of the relevant exceptions and provide a pretty
1489 a8083063 Iustin Pop
  # error message if rmtree fails.
1490 a8083063 Iustin Pop
1491 a8083063 Iustin Pop
  return True
1492 a8083063 Iustin Pop
1493 a8083063 Iustin Pop
1494 f3e513ad Iustin Pop
def RenameBlockDevices(devlist):
1495 f3e513ad Iustin Pop
  """Rename a list of block devices.
1496 f3e513ad Iustin Pop

1497 f3e513ad Iustin Pop
  The devlist argument is a list of tuples (disk, new_logical,
1498 f3e513ad Iustin Pop
  new_physical). The return value will be a combined boolean result
1499 f3e513ad Iustin Pop
  (True only if all renames succeeded).
1500 f3e513ad Iustin Pop

1501 f3e513ad Iustin Pop
  """
1502 f3e513ad Iustin Pop
  result = True
1503 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
1504 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
1505 f3e513ad Iustin Pop
    if dev is None:
1506 f3e513ad Iustin Pop
      result = False
1507 f3e513ad Iustin Pop
      continue
1508 f3e513ad Iustin Pop
    try:
1509 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
1510 f3e513ad Iustin Pop
      dev.Rename(unique_id)
1511 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
1512 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
1513 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
1514 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
1515 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
1516 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
1517 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
1518 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
1519 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
1520 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
1521 f3e513ad Iustin Pop
      result = False
1522 f3e513ad Iustin Pop
  return result
1523 f3e513ad Iustin Pop
1524 f3e513ad Iustin Pop
1525 778b75bb Manuel Franceschini
def _TransformFileStorageDir(file_storage_dir):
1526 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
1527 778b75bb Manuel Franceschini

1528 778b75bb Manuel Franceschini
  Checks wheter the given file_storage_dir is within the cluster-wide
1529 778b75bb Manuel Franceschini
  default file_storage_dir stored in SimpleStore. Only paths under that
1530 778b75bb Manuel Franceschini
  directory are allowed.
1531 778b75bb Manuel Franceschini

1532 778b75bb Manuel Franceschini
  Args:
1533 778b75bb Manuel Franceschini
    file_storage_dir: string with path
1534 d61cbe76 Iustin Pop

1535 778b75bb Manuel Franceschini
  Returns:
1536 778b75bb Manuel Franceschini
    normalized file_storage_dir (string) if valid, None otherwise
1537 778b75bb Manuel Franceschini

1538 778b75bb Manuel Franceschini
  """
1539 778b75bb Manuel Franceschini
  file_storage_dir = os.path.normpath(file_storage_dir)
1540 778b75bb Manuel Franceschini
  base_file_storage_dir = ssconf.SimpleStore().GetFileStorageDir()
1541 778b75bb Manuel Franceschini
  if (not os.path.commonprefix([file_storage_dir, base_file_storage_dir]) ==
1542 778b75bb Manuel Franceschini
      base_file_storage_dir):
1543 18682bca Iustin Pop
    logging.error("file storage directory '%s' is not under base file"
1544 18682bca Iustin Pop
                  " storage directory '%s'",
1545 18682bca Iustin Pop
                  file_storage_dir, base_file_storage_dir)
1546 778b75bb Manuel Franceschini
    return None
1547 778b75bb Manuel Franceschini
  return file_storage_dir
1548 778b75bb Manuel Franceschini
1549 778b75bb Manuel Franceschini
1550 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
1551 778b75bb Manuel Franceschini
  """Create file storage directory.
1552 778b75bb Manuel Franceschini

1553 778b75bb Manuel Franceschini
  Args:
1554 778b75bb Manuel Franceschini
    file_storage_dir: string containing the path
1555 778b75bb Manuel Franceschini

1556 778b75bb Manuel Franceschini
  Returns:
1557 778b75bb Manuel Franceschini
    tuple with first element a boolean indicating wheter dir
1558 778b75bb Manuel Franceschini
    creation was successful or not
1559 778b75bb Manuel Franceschini

1560 778b75bb Manuel Franceschini
  """
1561 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
1562 778b75bb Manuel Franceschini
  result = True,
1563 778b75bb Manuel Franceschini
  if not file_storage_dir:
1564 778b75bb Manuel Franceschini
    result = False,
1565 778b75bb Manuel Franceschini
  else:
1566 778b75bb Manuel Franceschini
    if os.path.exists(file_storage_dir):
1567 778b75bb Manuel Franceschini
      if not os.path.isdir(file_storage_dir):
1568 18682bca Iustin Pop
        logging.error("'%s' is not a directory", file_storage_dir)
1569 778b75bb Manuel Franceschini
        result = False,
1570 778b75bb Manuel Franceschini
    else:
1571 778b75bb Manuel Franceschini
      try:
1572 778b75bb Manuel Franceschini
        os.makedirs(file_storage_dir, 0750)
1573 778b75bb Manuel Franceschini
      except OSError, err:
1574 18682bca Iustin Pop
        logging.error("Cannot create file storage directory '%s': %s",
1575 18682bca Iustin Pop
                      file_storage_dir, err)
1576 778b75bb Manuel Franceschini
        result = False,
1577 778b75bb Manuel Franceschini
  return result
1578 778b75bb Manuel Franceschini
1579 778b75bb Manuel Franceschini
1580 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
1581 778b75bb Manuel Franceschini
  """Remove file storage directory.
1582 778b75bb Manuel Franceschini

1583 778b75bb Manuel Franceschini
  Remove it only if it's empty. If not log an error and return.
1584 778b75bb Manuel Franceschini

1585 778b75bb Manuel Franceschini
  Args:
1586 778b75bb Manuel Franceschini
    file_storage_dir: string containing the path
1587 778b75bb Manuel Franceschini

1588 778b75bb Manuel Franceschini
  Returns:
1589 778b75bb Manuel Franceschini
    tuple with first element a boolean indicating wheter dir
1590 778b75bb Manuel Franceschini
    removal was successful or not
1591 778b75bb Manuel Franceschini

1592 778b75bb Manuel Franceschini
  """
1593 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
1594 778b75bb Manuel Franceschini
  result = True,
1595 778b75bb Manuel Franceschini
  if not file_storage_dir:
1596 778b75bb Manuel Franceschini
    result = False,
1597 778b75bb Manuel Franceschini
  else:
1598 778b75bb Manuel Franceschini
    if os.path.exists(file_storage_dir):
1599 778b75bb Manuel Franceschini
      if not os.path.isdir(file_storage_dir):
1600 18682bca Iustin Pop
        logging.error("'%s' is not a directory", file_storage_dir)
1601 778b75bb Manuel Franceschini
        result = False,
1602 778b75bb Manuel Franceschini
      # deletes dir only if empty, otherwise we want to return False
1603 778b75bb Manuel Franceschini
      try:
1604 778b75bb Manuel Franceschini
        os.rmdir(file_storage_dir)
1605 778b75bb Manuel Franceschini
      except OSError, err:
1606 18682bca Iustin Pop
        logging.exception("Cannot remove file storage directory '%s'",
1607 18682bca Iustin Pop
                          file_storage_dir)
1608 778b75bb Manuel Franceschini
        result = False,
1609 778b75bb Manuel Franceschini
  return result
1610 778b75bb Manuel Franceschini
1611 778b75bb Manuel Franceschini
1612 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
1613 778b75bb Manuel Franceschini
  """Rename the file storage directory.
1614 778b75bb Manuel Franceschini

1615 778b75bb Manuel Franceschini
  Args:
1616 778b75bb Manuel Franceschini
    old_file_storage_dir: string containing the old path
1617 778b75bb Manuel Franceschini
    new_file_storage_dir: string containing the new path
1618 778b75bb Manuel Franceschini

1619 778b75bb Manuel Franceschini
  Returns:
1620 778b75bb Manuel Franceschini
    tuple with first element a boolean indicating wheter dir
1621 778b75bb Manuel Franceschini
    rename was successful or not
1622 778b75bb Manuel Franceschini

1623 778b75bb Manuel Franceschini
  """
1624 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
1625 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
1626 778b75bb Manuel Franceschini
  result = True,
1627 778b75bb Manuel Franceschini
  if not old_file_storage_dir or not new_file_storage_dir:
1628 778b75bb Manuel Franceschini
    result = False,
1629 778b75bb Manuel Franceschini
  else:
1630 778b75bb Manuel Franceschini
    if not os.path.exists(new_file_storage_dir):
1631 778b75bb Manuel Franceschini
      if os.path.isdir(old_file_storage_dir):
1632 778b75bb Manuel Franceschini
        try:
1633 778b75bb Manuel Franceschini
          os.rename(old_file_storage_dir, new_file_storage_dir)
1634 778b75bb Manuel Franceschini
        except OSError, err:
1635 18682bca Iustin Pop
          logging.exception("Cannot rename '%s' to '%s'",
1636 18682bca Iustin Pop
                            old_file_storage_dir, new_file_storage_dir)
1637 778b75bb Manuel Franceschini
          result =  False,
1638 778b75bb Manuel Franceschini
      else:
1639 18682bca Iustin Pop
        logging.error("'%s' is not a directory", old_file_storage_dir)
1640 778b75bb Manuel Franceschini
        result = False,
1641 778b75bb Manuel Franceschini
    else:
1642 778b75bb Manuel Franceschini
      if os.path.exists(old_file_storage_dir):
1643 18682bca Iustin Pop
        logging.error("Cannot rename '%s' to '%s'. Both locations exist.",
1644 18682bca Iustin Pop
                      old_file_storage_dir, new_file_storage_dir)
1645 778b75bb Manuel Franceschini
        result = False,
1646 778b75bb Manuel Franceschini
  return result
1647 778b75bb Manuel Franceschini
1648 778b75bb Manuel Franceschini
1649 d61cbe76 Iustin Pop
def CloseBlockDevices(disks):
1650 d61cbe76 Iustin Pop
  """Closes the given block devices.
1651 d61cbe76 Iustin Pop

1652 d61cbe76 Iustin Pop
  This means they will be switched to secondary mode (in case of DRBD).
1653 d61cbe76 Iustin Pop

1654 d61cbe76 Iustin Pop
  """
1655 d61cbe76 Iustin Pop
  bdevs = []
1656 d61cbe76 Iustin Pop
  for cf in disks:
1657 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
1658 d61cbe76 Iustin Pop
    if rd is None:
1659 d61cbe76 Iustin Pop
      return (False, "Can't find device %s" % cf)
1660 d61cbe76 Iustin Pop
    bdevs.append(rd)
1661 d61cbe76 Iustin Pop
1662 d61cbe76 Iustin Pop
  msg = []
1663 d61cbe76 Iustin Pop
  for rd in bdevs:
1664 d61cbe76 Iustin Pop
    try:
1665 d61cbe76 Iustin Pop
      rd.Close()
1666 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
1667 d61cbe76 Iustin Pop
      msg.append(str(err))
1668 d61cbe76 Iustin Pop
  if msg:
1669 d61cbe76 Iustin Pop
    return (False, "Can't make devices secondary: %s" % ",".join(msg))
1670 d61cbe76 Iustin Pop
  else:
1671 d61cbe76 Iustin Pop
    return (True, "All devices secondary")
1672 d61cbe76 Iustin Pop
1673 d61cbe76 Iustin Pop
1674 a8083063 Iustin Pop
class HooksRunner(object):
1675 a8083063 Iustin Pop
  """Hook runner.
1676 a8083063 Iustin Pop

1677 a8083063 Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
1678 a8083063 Iustin Pop
  the master side.
1679 a8083063 Iustin Pop

1680 a8083063 Iustin Pop
  """
1681 a8083063 Iustin Pop
  RE_MASK = re.compile("^[a-zA-Z0-9_-]+$")
1682 a8083063 Iustin Pop
1683 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
1684 a8083063 Iustin Pop
    """Constructor for hooks runner.
1685 a8083063 Iustin Pop

1686 a8083063 Iustin Pop
    Args:
1687 a8083063 Iustin Pop
      - hooks_base_dir: if not None, this overrides the
1688 a8083063 Iustin Pop
        constants.HOOKS_BASE_DIR (useful for unittests)
1689 a8083063 Iustin Pop

1690 a8083063 Iustin Pop
    """
1691 a8083063 Iustin Pop
    if hooks_base_dir is None:
1692 a8083063 Iustin Pop
      hooks_base_dir = constants.HOOKS_BASE_DIR
1693 a8083063 Iustin Pop
    self._BASE_DIR = hooks_base_dir
1694 a8083063 Iustin Pop
1695 a8083063 Iustin Pop
  @staticmethod
1696 a8083063 Iustin Pop
  def ExecHook(script, env):
1697 a8083063 Iustin Pop
    """Exec one hook script.
1698 a8083063 Iustin Pop

1699 a8083063 Iustin Pop
    Args:
1700 a8083063 Iustin Pop
     - script: the full path to the script
1701 a8083063 Iustin Pop
     - env: the environment with which to exec the script
1702 a8083063 Iustin Pop

1703 a8083063 Iustin Pop
    """
1704 a8083063 Iustin Pop
    # exec the process using subprocess and log the output
1705 a8083063 Iustin Pop
    fdstdin = None
1706 a8083063 Iustin Pop
    try:
1707 a8083063 Iustin Pop
      fdstdin = open("/dev/null", "r")
1708 a8083063 Iustin Pop
      child = subprocess.Popen([script], stdin=fdstdin, stdout=subprocess.PIPE,
1709 a8083063 Iustin Pop
                               stderr=subprocess.STDOUT, close_fds=True,
1710 147af04d Iustin Pop
                               shell=False, cwd="/", env=env)
1711 a8083063 Iustin Pop
      output = ""
1712 a8083063 Iustin Pop
      try:
1713 a8083063 Iustin Pop
        output = child.stdout.read(4096)
1714 a8083063 Iustin Pop
        child.stdout.close()
1715 a8083063 Iustin Pop
      except EnvironmentError, err:
1716 a8083063 Iustin Pop
        output += "Hook script error: %s" % str(err)
1717 a8083063 Iustin Pop
1718 a8083063 Iustin Pop
      while True:
1719 a8083063 Iustin Pop
        try:
1720 a8083063 Iustin Pop
          result = child.wait()
1721 a8083063 Iustin Pop
          break
1722 a8083063 Iustin Pop
        except EnvironmentError, err:
1723 a8083063 Iustin Pop
          if err.errno == errno.EINTR:
1724 a8083063 Iustin Pop
            continue
1725 a8083063 Iustin Pop
          raise
1726 a8083063 Iustin Pop
    finally:
1727 a8083063 Iustin Pop
      # try not to leak fds
1728 a8083063 Iustin Pop
      for fd in (fdstdin, ):
1729 a8083063 Iustin Pop
        if fd is not None:
1730 a8083063 Iustin Pop
          try:
1731 a8083063 Iustin Pop
            fd.close()
1732 a8083063 Iustin Pop
          except EnvironmentError, err:
1733 a8083063 Iustin Pop
            # just log the error
1734 18682bca Iustin Pop
            #logging.exception("Error while closing fd %s", fd)
1735 a8083063 Iustin Pop
            pass
1736 a8083063 Iustin Pop
1737 a8083063 Iustin Pop
    return result == 0, output
1738 a8083063 Iustin Pop
1739 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
1740 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
1741 a8083063 Iustin Pop

1742 a8083063 Iustin Pop
    This method will not be usually overriden by child opcodes.
1743 a8083063 Iustin Pop

1744 a8083063 Iustin Pop
    """
1745 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
1746 a8083063 Iustin Pop
      suffix = "pre"
1747 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
1748 a8083063 Iustin Pop
      suffix = "post"
1749 a8083063 Iustin Pop
    else:
1750 3ecf6786 Iustin Pop
      raise errors.ProgrammerError("Unknown hooks phase: '%s'" % phase)
1751 a8083063 Iustin Pop
    rr = []
1752 a8083063 Iustin Pop
1753 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
1754 a8083063 Iustin Pop
    dir_name = "%s/%s" % (self._BASE_DIR, subdir)
1755 a8083063 Iustin Pop
    try:
1756 eedbda4b Michael Hanselmann
      dir_contents = utils.ListVisibleFiles(dir_name)
1757 a8083063 Iustin Pop
    except OSError, err:
1758 a8083063 Iustin Pop
      # must log
1759 a8083063 Iustin Pop
      return rr
1760 a8083063 Iustin Pop
1761 a8083063 Iustin Pop
    # we use the standard python sort order,
1762 a8083063 Iustin Pop
    # so 00name is the recommended naming scheme
1763 a8083063 Iustin Pop
    dir_contents.sort()
1764 a8083063 Iustin Pop
    for relname in dir_contents:
1765 a8083063 Iustin Pop
      fname = os.path.join(dir_name, relname)
1766 a8083063 Iustin Pop
      if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and
1767 a8083063 Iustin Pop
          self.RE_MASK.match(relname) is not None):
1768 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
1769 a8083063 Iustin Pop
        output = ""
1770 a8083063 Iustin Pop
      else:
1771 a8083063 Iustin Pop
        result, output = self.ExecHook(fname, env)
1772 a8083063 Iustin Pop
        if not result:
1773 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
1774 a8083063 Iustin Pop
        else:
1775 a8083063 Iustin Pop
          rrval = constants.HKR_SUCCESS
1776 a8083063 Iustin Pop
      rr.append(("%s/%s" % (subdir, relname), rrval, output))
1777 a8083063 Iustin Pop
1778 a8083063 Iustin Pop
    return rr
1779 3f78eef2 Iustin Pop
1780 3f78eef2 Iustin Pop
1781 8d528b7c Iustin Pop
class IAllocatorRunner(object):
1782 8d528b7c Iustin Pop
  """IAllocator runner.
1783 8d528b7c Iustin Pop

1784 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
1785 8d528b7c Iustin Pop
  the master side.
1786 8d528b7c Iustin Pop

1787 8d528b7c Iustin Pop
  """
1788 8d528b7c Iustin Pop
  def Run(self, name, idata):
1789 8d528b7c Iustin Pop
    """Run an iallocator script.
1790 8d528b7c Iustin Pop

1791 8d528b7c Iustin Pop
    Return value: tuple of:
1792 8d528b7c Iustin Pop
       - run status (one of the IARUN_ constants)
1793 8d528b7c Iustin Pop
       - stdout
1794 8d528b7c Iustin Pop
       - stderr
1795 8d528b7c Iustin Pop
       - fail reason (as from utils.RunResult)
1796 8d528b7c Iustin Pop

1797 8d528b7c Iustin Pop
    """
1798 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
1799 8d528b7c Iustin Pop
                                  os.path.isfile)
1800 8d528b7c Iustin Pop
    if alloc_script is None:
1801 8d528b7c Iustin Pop
      return (constants.IARUN_NOTFOUND, None, None, None)
1802 8d528b7c Iustin Pop
1803 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
1804 8d528b7c Iustin Pop
    try:
1805 8d528b7c Iustin Pop
      os.write(fd, idata)
1806 8d528b7c Iustin Pop
      os.close(fd)
1807 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
1808 8d528b7c Iustin Pop
      if result.failed:
1809 8d528b7c Iustin Pop
        return (constants.IARUN_FAILURE, result.stdout, result.stderr,
1810 8d528b7c Iustin Pop
                result.fail_reason)
1811 8d528b7c Iustin Pop
    finally:
1812 8d528b7c Iustin Pop
      os.unlink(fin_name)
1813 8d528b7c Iustin Pop
1814 8d528b7c Iustin Pop
    return (constants.IARUN_SUCCESS, result.stdout, result.stderr, None)
1815 8d528b7c Iustin Pop
1816 8d528b7c Iustin Pop
1817 3f78eef2 Iustin Pop
class DevCacheManager(object):
1818 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
1819 3f78eef2 Iustin Pop

1820 3f78eef2 Iustin Pop
  """
1821 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
1822 3f78eef2 Iustin Pop
  _ROOT_DIR = constants.BDEV_CACHE_DIR
1823 3f78eef2 Iustin Pop
1824 3f78eef2 Iustin Pop
  @classmethod
1825 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
1826 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
1827 3f78eef2 Iustin Pop

1828 3f78eef2 Iustin Pop
    This replaces slashes with underscores and strips the /dev
1829 3f78eef2 Iustin Pop
    prefix. It then returns the full path to the cache file
1830 3f78eef2 Iustin Pop

1831 3f78eef2 Iustin Pop
    """
1832 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
1833 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
1834 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
1835 3f78eef2 Iustin Pop
    fpath = "%s/bdev_%s" % (cls._ROOT_DIR, dev_path)
1836 3f78eef2 Iustin Pop
    return fpath
1837 3f78eef2 Iustin Pop
1838 3f78eef2 Iustin Pop
  @classmethod
1839 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
1840 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
1841 3f78eef2 Iustin Pop

1842 3f78eef2 Iustin Pop
    """
1843 cf5a8306 Iustin Pop
    if dev_path is None:
1844 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
1845 cf5a8306 Iustin Pop
      return
1846 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
1847 3f78eef2 Iustin Pop
    if on_primary:
1848 3f78eef2 Iustin Pop
      state = "primary"
1849 3f78eef2 Iustin Pop
    else:
1850 3f78eef2 Iustin Pop
      state = "secondary"
1851 3f78eef2 Iustin Pop
    if iv_name is None:
1852 3f78eef2 Iustin Pop
      iv_name = "not_visible"
1853 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
1854 3f78eef2 Iustin Pop
    try:
1855 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
1856 3f78eef2 Iustin Pop
    except EnvironmentError, err:
1857 18682bca Iustin Pop
      logging.exception("Can't update bdev cache for %s", dev_path)
1858 3f78eef2 Iustin Pop
1859 3f78eef2 Iustin Pop
  @classmethod
1860 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
1861 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
1862 3f78eef2 Iustin Pop

1863 3f78eef2 Iustin Pop
    """
1864 cf5a8306 Iustin Pop
    if dev_path is None:
1865 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
1866 cf5a8306 Iustin Pop
      return
1867 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
1868 3f78eef2 Iustin Pop
    try:
1869 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
1870 3f78eef2 Iustin Pop
    except EnvironmentError, err:
1871 18682bca Iustin Pop
      logging.exception("Can't update bdev cache for %s", dev_path)