Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 41a57aab

History | View | Annotate | Download (44.9 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 a8083063 Iustin Pop
34 a8083063 Iustin Pop
from ganeti import logger
35 a8083063 Iustin Pop
from ganeti import errors
36 a8083063 Iustin Pop
from ganeti import utils
37 a8083063 Iustin Pop
from ganeti import ssh
38 a8083063 Iustin Pop
from ganeti import hypervisor
39 a8083063 Iustin Pop
from ganeti import constants
40 a8083063 Iustin Pop
from ganeti import bdev
41 a8083063 Iustin Pop
from ganeti import objects
42 880478f8 Iustin Pop
from ganeti import ssconf
43 a8083063 Iustin Pop
44 a8083063 Iustin Pop
45 a8083063 Iustin Pop
def StartMaster():
46 a8083063 Iustin Pop
  """Activate local node as master node.
47 a8083063 Iustin Pop

48 a8083063 Iustin Pop
  There are two needed steps for this:
49 880478f8 Iustin Pop
    - run the master script
50 a8083063 Iustin Pop
    - register the cron script
51 a8083063 Iustin Pop

52 a8083063 Iustin Pop
  """
53 880478f8 Iustin Pop
  result = utils.RunCmd([constants.MASTER_SCRIPT, "-d", "start"])
54 a8083063 Iustin Pop
55 a8083063 Iustin Pop
  if result.failed:
56 a8083063 Iustin Pop
    logger.Error("could not activate cluster interface with command %s,"
57 880478f8 Iustin Pop
                 " error: '%s'" % (result.cmd, result.output))
58 a8083063 Iustin Pop
    return False
59 a8083063 Iustin Pop
60 a8083063 Iustin Pop
  return True
61 a8083063 Iustin Pop
62 a8083063 Iustin Pop
63 a8083063 Iustin Pop
def StopMaster():
64 a8083063 Iustin Pop
  """Deactivate this node as master.
65 a8083063 Iustin Pop

66 c9064964 Iustin Pop
  This runs the master stop script.
67 a8083063 Iustin Pop

68 a8083063 Iustin Pop
  """
69 880478f8 Iustin Pop
  result = utils.RunCmd([constants.MASTER_SCRIPT, "-d", "stop"])
70 a8083063 Iustin Pop
71 a8083063 Iustin Pop
  if result.failed:
72 a8083063 Iustin Pop
    logger.Error("could not deactivate cluster interface with command %s,"
73 880478f8 Iustin Pop
                 " error: '%s'" % (result.cmd, result.output))
74 a8083063 Iustin Pop
    return False
75 a8083063 Iustin Pop
76 a8083063 Iustin Pop
  return True
77 a8083063 Iustin Pop
78 a8083063 Iustin Pop
79 9716fdce Iustin Pop
def AddNode(dsa, dsapub, rsa, rsapub, sshkey, sshpub):
80 7900ed01 Iustin Pop
  """Joins this node to the cluster.
81 a8083063 Iustin Pop

82 7900ed01 Iustin Pop
  This does the following:
83 7900ed01 Iustin Pop
      - updates the hostkeys of the machine (rsa and dsa)
84 7900ed01 Iustin Pop
      - adds the ssh private key to the user
85 7900ed01 Iustin Pop
      - adds the ssh public key to the users' authorized_keys file
86 a8083063 Iustin Pop

87 7900ed01 Iustin Pop
  """
88 70d9e3d8 Iustin Pop
  sshd_keys =  [(constants.SSH_HOST_RSA_PRIV, rsa, 0600),
89 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_RSA_PUB, rsapub, 0644),
90 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_DSA_PRIV, dsa, 0600),
91 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_DSA_PUB, dsapub, 0644)]
92 7900ed01 Iustin Pop
  for name, content, mode in sshd_keys:
93 70d9e3d8 Iustin Pop
    utils.WriteFile(name, data=content, mode=mode)
94 a8083063 Iustin Pop
95 70d9e3d8 Iustin Pop
  try:
96 70d9e3d8 Iustin Pop
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS,
97 70d9e3d8 Iustin Pop
                                                    mkdir=True)
98 70d9e3d8 Iustin Pop
  except errors.OpExecError, err:
99 70d9e3d8 Iustin Pop
    logger.Error("Error while processing user ssh files: %s" % err)
100 70d9e3d8 Iustin Pop
    return False
101 a8083063 Iustin Pop
102 70d9e3d8 Iustin Pop
  for name, content in [(priv_key, sshkey), (pub_key, sshpub)]:
103 70d9e3d8 Iustin Pop
    utils.WriteFile(name, data=content, mode=0600)
104 a8083063 Iustin Pop
105 70d9e3d8 Iustin Pop
  utils.AddAuthorizedKey(auth_keys, sshpub)
106 a8083063 Iustin Pop
107 f491c3a8 Michael Hanselmann
  utils.RunCmd([constants.SSH_INITD_SCRIPT, "restart"])
108 a8083063 Iustin Pop
109 a8083063 Iustin Pop
  return True
110 a8083063 Iustin Pop
111 a8083063 Iustin Pop
112 a8083063 Iustin Pop
def LeaveCluster():
113 a8083063 Iustin Pop
  """Cleans up the current node and prepares it to be removed from the cluster.
114 a8083063 Iustin Pop

115 a8083063 Iustin Pop
  """
116 71eca7c3 Iustin Pop
  if os.path.isdir(constants.DATA_DIR):
117 71eca7c3 Iustin Pop
    for rel_name in utils.ListVisibleFiles(constants.DATA_DIR):
118 71eca7c3 Iustin Pop
      full_name = os.path.join(constants.DATA_DIR, rel_name)
119 71eca7c3 Iustin Pop
      if os.path.isfile(full_name) and not os.path.islink(full_name):
120 71eca7c3 Iustin Pop
        utils.RemoveFile(full_name)
121 a8083063 Iustin Pop
122 70d9e3d8 Iustin Pop
  try:
123 70d9e3d8 Iustin Pop
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
124 70d9e3d8 Iustin Pop
  except errors.OpExecError, err:
125 70d9e3d8 Iustin Pop
    logger.Error("Error while processing ssh files: %s" % err)
126 7900ed01 Iustin Pop
    return
127 7900ed01 Iustin Pop
128 70d9e3d8 Iustin Pop
  f = open(pub_key, 'r')
129 a8083063 Iustin Pop
  try:
130 70d9e3d8 Iustin Pop
    utils.RemoveAuthorizedKey(auth_keys, f.read(8192))
131 a8083063 Iustin Pop
  finally:
132 a8083063 Iustin Pop
    f.close()
133 a8083063 Iustin Pop
134 70d9e3d8 Iustin Pop
  utils.RemoveFile(priv_key)
135 70d9e3d8 Iustin Pop
  utils.RemoveFile(pub_key)
136 a8083063 Iustin Pop
137 a8083063 Iustin Pop
138 a8083063 Iustin Pop
def GetNodeInfo(vgname):
139 2f8598a5 Alexander Schreiber
  """Gives back a hash with different informations about the node.
140 a8083063 Iustin Pop

141 a8083063 Iustin Pop
  Returns:
142 a8083063 Iustin Pop
    { 'vg_size' : xxx,  'vg_free' : xxx, 'memory_domain0': xxx,
143 a8083063 Iustin Pop
      'memory_free' : xxx, 'memory_total' : xxx }
144 a8083063 Iustin Pop
    where
145 a8083063 Iustin Pop
    vg_size is the size of the configured volume group in MiB
146 a8083063 Iustin Pop
    vg_free is the free size of the volume group in MiB
147 a8083063 Iustin Pop
    memory_dom0 is the memory allocated for domain0 in MiB
148 a8083063 Iustin Pop
    memory_free is the currently available (free) ram in MiB
149 a8083063 Iustin Pop
    memory_total is the total number of ram in MiB
150 a8083063 Iustin Pop

151 098c0958 Michael Hanselmann
  """
152 a8083063 Iustin Pop
  outputarray = {}
153 a8083063 Iustin Pop
  vginfo = _GetVGInfo(vgname)
154 a8083063 Iustin Pop
  outputarray['vg_size'] = vginfo['vg_size']
155 a8083063 Iustin Pop
  outputarray['vg_free'] = vginfo['vg_free']
156 a8083063 Iustin Pop
157 a8083063 Iustin Pop
  hyper = hypervisor.GetHypervisor()
158 a8083063 Iustin Pop
  hyp_info = hyper.GetNodeInfo()
159 a8083063 Iustin Pop
  if hyp_info is not None:
160 a8083063 Iustin Pop
    outputarray.update(hyp_info)
161 a8083063 Iustin Pop
162 3ef10550 Michael Hanselmann
  f = open("/proc/sys/kernel/random/boot_id", 'r')
163 3ef10550 Michael Hanselmann
  try:
164 3ef10550 Michael Hanselmann
    outputarray["bootid"] = f.read(128).rstrip("\n")
165 3ef10550 Michael Hanselmann
  finally:
166 3ef10550 Michael Hanselmann
    f.close()
167 3ef10550 Michael Hanselmann
168 a8083063 Iustin Pop
  return outputarray
169 a8083063 Iustin Pop
170 a8083063 Iustin Pop
171 a8083063 Iustin Pop
def VerifyNode(what):
172 a8083063 Iustin Pop
  """Verify the status of the local node.
173 a8083063 Iustin Pop

174 a8083063 Iustin Pop
  Args:
175 a8083063 Iustin Pop
    what - a dictionary of things to check:
176 a8083063 Iustin Pop
      'filelist' : list of files for which to compute checksums
177 a8083063 Iustin Pop
      'nodelist' : list of nodes we should check communication with
178 a8083063 Iustin Pop
      'hypervisor': run the hypervisor-specific verify
179 a8083063 Iustin Pop

180 a8083063 Iustin Pop
  Requested files on local node are checksummed and the result returned.
181 a8083063 Iustin Pop

182 a8083063 Iustin Pop
  The nodelist is traversed, with the following checks being made
183 a8083063 Iustin Pop
  for each node:
184 a8083063 Iustin Pop
  - known_hosts key correct
185 a8083063 Iustin Pop
  - correct resolving of node name (target node returns its own hostname
186 a8083063 Iustin Pop
    by ssh-execution of 'hostname', result compared against name in list.
187 a8083063 Iustin Pop

188 a8083063 Iustin Pop
  """
189 a8083063 Iustin Pop
  result = {}
190 a8083063 Iustin Pop
191 a8083063 Iustin Pop
  if 'hypervisor' in what:
192 a8083063 Iustin Pop
    result['hypervisor'] = hypervisor.GetHypervisor().Verify()
193 a8083063 Iustin Pop
194 a8083063 Iustin Pop
  if 'filelist' in what:
195 a8083063 Iustin Pop
    result['filelist'] = utils.FingerprintFiles(what['filelist'])
196 a8083063 Iustin Pop
197 a8083063 Iustin Pop
  if 'nodelist' in what:
198 a8083063 Iustin Pop
    result['nodelist'] = {}
199 a8083063 Iustin Pop
    for node in what['nodelist']:
200 a8083063 Iustin Pop
      success, message = ssh.VerifyNodeHostname(node)
201 a8083063 Iustin Pop
      if not success:
202 a8083063 Iustin Pop
        result['nodelist'][node] = message
203 a8083063 Iustin Pop
  return result
204 a8083063 Iustin Pop
205 a8083063 Iustin Pop
206 a8083063 Iustin Pop
def GetVolumeList(vg_name):
207 a8083063 Iustin Pop
  """Compute list of logical volumes and their size.
208 a8083063 Iustin Pop

209 a8083063 Iustin Pop
  Returns:
210 cb2037a2 Iustin Pop
    dictionary of all partions (key) with their size (in MiB), inactive
211 cb2037a2 Iustin Pop
    and online status:
212 cb2037a2 Iustin Pop
    {'test1': ('20.06', True, True)}
213 a8083063 Iustin Pop

214 a8083063 Iustin Pop
  """
215 cb2037a2 Iustin Pop
  lvs = {}
216 cb2037a2 Iustin Pop
  sep = '|'
217 cb2037a2 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
218 cb2037a2 Iustin Pop
                         "--separator=%s" % sep,
219 cb2037a2 Iustin Pop
                         "-olv_name,lv_size,lv_attr", vg_name])
220 a8083063 Iustin Pop
  if result.failed:
221 a8083063 Iustin Pop
    logger.Error("Failed to list logical volumes, lvs output: %s" %
222 a8083063 Iustin Pop
                 result.output)
223 b63ed789 Iustin Pop
    return result.output
224 cb2037a2 Iustin Pop
225 cb2037a2 Iustin Pop
  for line in result.stdout.splitlines():
226 cb2037a2 Iustin Pop
    line = line.strip().rstrip(sep)
227 cb2037a2 Iustin Pop
    name, size, attr = line.split(sep)
228 cb2037a2 Iustin Pop
    if len(attr) != 6:
229 cb2037a2 Iustin Pop
      attr = '------'
230 cb2037a2 Iustin Pop
    inactive = attr[4] == '-'
231 cb2037a2 Iustin Pop
    online = attr[5] == 'o'
232 cb2037a2 Iustin Pop
    lvs[name] = (size, inactive, online)
233 cb2037a2 Iustin Pop
234 cb2037a2 Iustin Pop
  return lvs
235 a8083063 Iustin Pop
236 a8083063 Iustin Pop
237 a8083063 Iustin Pop
def ListVolumeGroups():
238 2f8598a5 Alexander Schreiber
  """List the volume groups and their size.
239 a8083063 Iustin Pop

240 a8083063 Iustin Pop
  Returns:
241 a8083063 Iustin Pop
    Dictionary with keys volume name and values the size of the volume
242 a8083063 Iustin Pop

243 a8083063 Iustin Pop
  """
244 a8083063 Iustin Pop
  return utils.ListVolumeGroups()
245 a8083063 Iustin Pop
246 a8083063 Iustin Pop
247 dcb93971 Michael Hanselmann
def NodeVolumes():
248 dcb93971 Michael Hanselmann
  """List all volumes on this node.
249 dcb93971 Michael Hanselmann

250 dcb93971 Michael Hanselmann
  """
251 dcb93971 Michael Hanselmann
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
252 dcb93971 Michael Hanselmann
                         "--separator=|",
253 dcb93971 Michael Hanselmann
                         "--options=lv_name,lv_size,devices,vg_name"])
254 dcb93971 Michael Hanselmann
  if result.failed:
255 dcb93971 Michael Hanselmann
    logger.Error("Failed to list logical volumes, lvs output: %s" %
256 dcb93971 Michael Hanselmann
                 result.output)
257 dcb93971 Michael Hanselmann
    return {}
258 dcb93971 Michael Hanselmann
259 dcb93971 Michael Hanselmann
  def parse_dev(dev):
260 dcb93971 Michael Hanselmann
    if '(' in dev:
261 dcb93971 Michael Hanselmann
      return dev.split('(')[0]
262 dcb93971 Michael Hanselmann
    else:
263 dcb93971 Michael Hanselmann
      return dev
264 dcb93971 Michael Hanselmann
265 dcb93971 Michael Hanselmann
  def map_line(line):
266 dcb93971 Michael Hanselmann
    return {
267 dcb93971 Michael Hanselmann
      'name': line[0].strip(),
268 dcb93971 Michael Hanselmann
      'size': line[1].strip(),
269 dcb93971 Michael Hanselmann
      'dev': parse_dev(line[2].strip()),
270 dcb93971 Michael Hanselmann
      'vg': line[3].strip(),
271 dcb93971 Michael Hanselmann
    }
272 dcb93971 Michael Hanselmann
273 f675d4aa Alexander Schreiber
  return [map_line(line.split('|')) for line in result.stdout.splitlines()]
274 dcb93971 Michael Hanselmann
275 dcb93971 Michael Hanselmann
276 a8083063 Iustin Pop
def BridgesExist(bridges_list):
277 2f8598a5 Alexander Schreiber
  """Check if a list of bridges exist on the current node.
278 a8083063 Iustin Pop

279 a8083063 Iustin Pop
  Returns:
280 a8083063 Iustin Pop
    True if all of them exist, false otherwise
281 a8083063 Iustin Pop

282 a8083063 Iustin Pop
  """
283 a8083063 Iustin Pop
  for bridge in bridges_list:
284 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
285 a8083063 Iustin Pop
      return False
286 a8083063 Iustin Pop
287 a8083063 Iustin Pop
  return True
288 a8083063 Iustin Pop
289 a8083063 Iustin Pop
290 a8083063 Iustin Pop
def GetInstanceList():
291 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
292 a8083063 Iustin Pop

293 a8083063 Iustin Pop
  Returns:
294 a8083063 Iustin Pop
    A list of all running instances on the current node
295 a8083063 Iustin Pop
    - instance1.example.com
296 a8083063 Iustin Pop
    - instance2.example.com
297 a8083063 Iustin Pop

298 098c0958 Michael Hanselmann
  """
299 a8083063 Iustin Pop
  try:
300 a8083063 Iustin Pop
    names = hypervisor.GetHypervisor().ListInstances()
301 a8083063 Iustin Pop
  except errors.HypervisorError, err:
302 a8083063 Iustin Pop
    logger.Error("error enumerating instances: %s" % str(err))
303 a8083063 Iustin Pop
    raise
304 a8083063 Iustin Pop
305 a8083063 Iustin Pop
  return names
306 a8083063 Iustin Pop
307 a8083063 Iustin Pop
308 a8083063 Iustin Pop
def GetInstanceInfo(instance):
309 2f8598a5 Alexander Schreiber
  """Gives back the informations about an instance as a dictionary.
310 a8083063 Iustin Pop

311 a8083063 Iustin Pop
  Args:
312 a8083063 Iustin Pop
    instance: name of the instance (ex. instance1.example.com)
313 a8083063 Iustin Pop

314 a8083063 Iustin Pop
  Returns:
315 a8083063 Iustin Pop
    { 'memory' : 511, 'state' : '-b---', 'time' : 3188.8, }
316 a8083063 Iustin Pop
    where
317 a8083063 Iustin Pop
    memory: memory size of instance (int)
318 a8083063 Iustin Pop
    state: xen state of instance (string)
319 a8083063 Iustin Pop
    time: cpu time of instance (float)
320 a8083063 Iustin Pop

321 098c0958 Michael Hanselmann
  """
322 a8083063 Iustin Pop
  output = {}
323 a8083063 Iustin Pop
324 a8083063 Iustin Pop
  iinfo = hypervisor.GetHypervisor().GetInstanceInfo(instance)
325 a8083063 Iustin Pop
  if iinfo is not None:
326 a8083063 Iustin Pop
    output['memory'] = iinfo[2]
327 a8083063 Iustin Pop
    output['state'] = iinfo[4]
328 a8083063 Iustin Pop
    output['time'] = iinfo[5]
329 a8083063 Iustin Pop
330 a8083063 Iustin Pop
  return output
331 a8083063 Iustin Pop
332 a8083063 Iustin Pop
333 a8083063 Iustin Pop
def GetAllInstancesInfo():
334 a8083063 Iustin Pop
  """Gather data about all instances.
335 a8083063 Iustin Pop

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

340 a8083063 Iustin Pop
  Returns: a dictionary of dictionaries, keys being the instance name,
341 a8083063 Iustin Pop
    and with values:
342 a8083063 Iustin Pop
    { 'memory' : 511, 'state' : '-b---', 'time' : 3188.8, }
343 a8083063 Iustin Pop
    where
344 a8083063 Iustin Pop
    memory: memory size of instance (int)
345 a8083063 Iustin Pop
    state: xen state of instance (string)
346 a8083063 Iustin Pop
    time: cpu time of instance (float)
347 a8083063 Iustin Pop
    vcpus: the number of cpus
348 a8083063 Iustin Pop

349 098c0958 Michael Hanselmann
  """
350 a8083063 Iustin Pop
  output = {}
351 a8083063 Iustin Pop
352 a8083063 Iustin Pop
  iinfo = hypervisor.GetHypervisor().GetAllInstancesInfo()
353 a8083063 Iustin Pop
  if iinfo:
354 3ecf6786 Iustin Pop
    for name, inst_id, memory, vcpus, state, times in iinfo:
355 a8083063 Iustin Pop
      output[name] = {
356 a8083063 Iustin Pop
        'memory': memory,
357 a8083063 Iustin Pop
        'vcpus': vcpus,
358 a8083063 Iustin Pop
        'state': state,
359 a8083063 Iustin Pop
        'time': times,
360 a8083063 Iustin Pop
        }
361 a8083063 Iustin Pop
362 a8083063 Iustin Pop
  return output
363 a8083063 Iustin Pop
364 a8083063 Iustin Pop
365 a8083063 Iustin Pop
def AddOSToInstance(instance, os_disk, swap_disk):
366 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
367 a8083063 Iustin Pop

368 a8083063 Iustin Pop
  Args:
369 a8083063 Iustin Pop
    instance: the instance object
370 a8083063 Iustin Pop
    os_disk: the instance-visible name of the os device
371 a8083063 Iustin Pop
    swap_disk: the instance-visible name of the swap device
372 a8083063 Iustin Pop

373 a8083063 Iustin Pop
  """
374 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
375 a8083063 Iustin Pop
376 a8083063 Iustin Pop
  create_script = inst_os.create_script
377 a8083063 Iustin Pop
378 9716fdce Iustin Pop
  os_device = instance.FindDisk(os_disk)
379 9716fdce Iustin Pop
  if os_device is None:
380 a8083063 Iustin Pop
    logger.Error("Can't find this device-visible name '%s'" % os_disk)
381 a8083063 Iustin Pop
    return False
382 a8083063 Iustin Pop
383 9716fdce Iustin Pop
  swap_device = instance.FindDisk(swap_disk)
384 9716fdce Iustin Pop
  if swap_device is None:
385 a8083063 Iustin Pop
    logger.Error("Can't find this device-visible name '%s'" % swap_disk)
386 a8083063 Iustin Pop
    return False
387 a8083063 Iustin Pop
388 a8083063 Iustin Pop
  real_os_dev = _RecursiveFindBD(os_device)
389 a8083063 Iustin Pop
  if real_os_dev is None:
390 a8083063 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
391 a8083063 Iustin Pop
                                  str(os_device))
392 a8083063 Iustin Pop
  real_os_dev.Open()
393 a8083063 Iustin Pop
394 a8083063 Iustin Pop
  real_swap_dev = _RecursiveFindBD(swap_device)
395 a8083063 Iustin Pop
  if real_swap_dev is None:
396 a8083063 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
397 a8083063 Iustin Pop
                                  str(swap_device))
398 a8083063 Iustin Pop
  real_swap_dev.Open()
399 a8083063 Iustin Pop
400 a8083063 Iustin Pop
  logfile = "%s/add-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
401 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
402 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
403 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
404 a8083063 Iustin Pop
405 c20494cd Iustin Pop
  command = utils.BuildShellCmd("cd %s && %s -i %s -b %s -s %s &>%s",
406 a8083063 Iustin Pop
                                inst_os.path, create_script, instance.name,
407 a8083063 Iustin Pop
                                real_os_dev.dev_path, real_swap_dev.dev_path,
408 a8083063 Iustin Pop
                                logfile)
409 decd5f45 Iustin Pop
410 decd5f45 Iustin Pop
  result = utils.RunCmd(command)
411 decd5f45 Iustin Pop
  if result.failed:
412 ff73280e Michael Hanselmann
    logger.Error("os create command '%s' returned error: %s, logfile: %s,"
413 decd5f45 Iustin Pop
                 " output: %s" %
414 ff73280e Michael Hanselmann
                 (command, result.fail_reason, logfile, result.output))
415 decd5f45 Iustin Pop
    return False
416 decd5f45 Iustin Pop
417 decd5f45 Iustin Pop
  return True
418 decd5f45 Iustin Pop
419 decd5f45 Iustin Pop
420 decd5f45 Iustin Pop
def RunRenameInstance(instance, old_name, os_disk, swap_disk):
421 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
422 decd5f45 Iustin Pop

423 decd5f45 Iustin Pop
  Args:
424 decd5f45 Iustin Pop
    instance: the instance object
425 decd5f45 Iustin Pop
    old_name: the old name of the instance
426 decd5f45 Iustin Pop
    os_disk: the instance-visible name of the os device
427 decd5f45 Iustin Pop
    swap_disk: the instance-visible name of the swap device
428 decd5f45 Iustin Pop

429 decd5f45 Iustin Pop
  """
430 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
431 decd5f45 Iustin Pop
432 decd5f45 Iustin Pop
  script = inst_os.rename_script
433 decd5f45 Iustin Pop
434 decd5f45 Iustin Pop
  os_device = instance.FindDisk(os_disk)
435 decd5f45 Iustin Pop
  if os_device is None:
436 decd5f45 Iustin Pop
    logger.Error("Can't find this device-visible name '%s'" % os_disk)
437 decd5f45 Iustin Pop
    return False
438 decd5f45 Iustin Pop
439 decd5f45 Iustin Pop
  swap_device = instance.FindDisk(swap_disk)
440 decd5f45 Iustin Pop
  if swap_device is None:
441 decd5f45 Iustin Pop
    logger.Error("Can't find this device-visible name '%s'" % swap_disk)
442 decd5f45 Iustin Pop
    return False
443 decd5f45 Iustin Pop
444 decd5f45 Iustin Pop
  real_os_dev = _RecursiveFindBD(os_device)
445 decd5f45 Iustin Pop
  if real_os_dev is None:
446 decd5f45 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
447 decd5f45 Iustin Pop
                                  str(os_device))
448 decd5f45 Iustin Pop
  real_os_dev.Open()
449 decd5f45 Iustin Pop
450 decd5f45 Iustin Pop
  real_swap_dev = _RecursiveFindBD(swap_device)
451 decd5f45 Iustin Pop
  if real_swap_dev is None:
452 decd5f45 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
453 decd5f45 Iustin Pop
                                  str(swap_device))
454 decd5f45 Iustin Pop
  real_swap_dev.Open()
455 decd5f45 Iustin Pop
456 decd5f45 Iustin Pop
  logfile = "%s/rename-%s-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
457 decd5f45 Iustin Pop
                                           old_name,
458 decd5f45 Iustin Pop
                                           instance.name, int(time.time()))
459 decd5f45 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
460 decd5f45 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
461 decd5f45 Iustin Pop
462 decd5f45 Iustin Pop
  command = utils.BuildShellCmd("cd %s && %s -o %s -n %s -b %s -s %s &>%s",
463 decd5f45 Iustin Pop
                                inst_os.path, script, old_name, instance.name,
464 decd5f45 Iustin Pop
                                real_os_dev.dev_path, real_swap_dev.dev_path,
465 decd5f45 Iustin Pop
                                logfile)
466 a8083063 Iustin Pop
467 a8083063 Iustin Pop
  result = utils.RunCmd(command)
468 a8083063 Iustin Pop
469 a8083063 Iustin Pop
  if result.failed:
470 a8083063 Iustin Pop
    logger.Error("os create command '%s' returned error: %s"
471 a8083063 Iustin Pop
                 " output: %s" %
472 a8083063 Iustin Pop
                 (command, result.fail_reason, result.output))
473 a8083063 Iustin Pop
    return False
474 a8083063 Iustin Pop
475 a8083063 Iustin Pop
  return True
476 a8083063 Iustin Pop
477 a8083063 Iustin Pop
478 a8083063 Iustin Pop
def _GetVGInfo(vg_name):
479 a8083063 Iustin Pop
  """Get informations about the volume group.
480 a8083063 Iustin Pop

481 a8083063 Iustin Pop
  Args:
482 a8083063 Iustin Pop
    vg_name: the volume group
483 a8083063 Iustin Pop

484 a8083063 Iustin Pop
  Returns:
485 a8083063 Iustin Pop
    { 'vg_size' : xxx, 'vg_free' : xxx, 'pv_count' : xxx }
486 a8083063 Iustin Pop
    where
487 a8083063 Iustin Pop
    vg_size is the total size of the volume group in MiB
488 a8083063 Iustin Pop
    vg_free is the free size of the volume group in MiB
489 a8083063 Iustin Pop
    pv_count are the number of physical disks in that vg
490 a8083063 Iustin Pop

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

494 a8083063 Iustin Pop
  """
495 f4d377e7 Iustin Pop
  retdic = dict.fromkeys(["vg_size", "vg_free", "pv_count"])
496 f4d377e7 Iustin Pop
497 a8083063 Iustin Pop
  retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings",
498 a8083063 Iustin Pop
                         "--nosuffix", "--units=m", "--separator=:", vg_name])
499 a8083063 Iustin Pop
500 a8083063 Iustin Pop
  if retval.failed:
501 a8083063 Iustin Pop
    errmsg = "volume group %s not present" % vg_name
502 a8083063 Iustin Pop
    logger.Error(errmsg)
503 f4d377e7 Iustin Pop
    return retdic
504 d87ae7d2 Iustin Pop
  valarr = retval.stdout.strip().rstrip(':').split(':')
505 f4d377e7 Iustin Pop
  if len(valarr) == 3:
506 f4d377e7 Iustin Pop
    try:
507 f4d377e7 Iustin Pop
      retdic = {
508 f4d377e7 Iustin Pop
        "vg_size": int(round(float(valarr[0]), 0)),
509 f4d377e7 Iustin Pop
        "vg_free": int(round(float(valarr[1]), 0)),
510 f4d377e7 Iustin Pop
        "pv_count": int(valarr[2]),
511 f4d377e7 Iustin Pop
        }
512 f4d377e7 Iustin Pop
    except ValueError, err:
513 f4d377e7 Iustin Pop
      logger.Error("Fail to parse vgs output: %s" % str(err))
514 f4d377e7 Iustin Pop
  else:
515 f4d377e7 Iustin Pop
    logger.Error("vgs output has the wrong number of fields (expected"
516 f4d377e7 Iustin Pop
                 " three): %s" % str(valarr))
517 a8083063 Iustin Pop
  return retdic
518 a8083063 Iustin Pop
519 a8083063 Iustin Pop
520 a8083063 Iustin Pop
def _GatherBlockDevs(instance):
521 a8083063 Iustin Pop
  """Set up an instance's block device(s).
522 a8083063 Iustin Pop

523 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
524 a8083063 Iustin Pop
  devices must be already assembled.
525 a8083063 Iustin Pop

526 a8083063 Iustin Pop
  """
527 a8083063 Iustin Pop
  block_devices = []
528 a8083063 Iustin Pop
  for disk in instance.disks:
529 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
530 a8083063 Iustin Pop
    if device is None:
531 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
532 a8083063 Iustin Pop
                                    str(disk))
533 a8083063 Iustin Pop
    device.Open()
534 a8083063 Iustin Pop
    block_devices.append((disk, device))
535 a8083063 Iustin Pop
  return block_devices
536 a8083063 Iustin Pop
537 a8083063 Iustin Pop
538 a8083063 Iustin Pop
def StartInstance(instance, extra_args):
539 a8083063 Iustin Pop
  """Start an instance.
540 a8083063 Iustin Pop

541 a8083063 Iustin Pop
  Args:
542 a8083063 Iustin Pop
    instance - name of instance to start.
543 a8083063 Iustin Pop

544 098c0958 Michael Hanselmann
  """
545 a8083063 Iustin Pop
  running_instances = GetInstanceList()
546 a8083063 Iustin Pop
547 a8083063 Iustin Pop
  if instance.name in running_instances:
548 a8083063 Iustin Pop
    return True
549 a8083063 Iustin Pop
550 a8083063 Iustin Pop
  block_devices = _GatherBlockDevs(instance)
551 a8083063 Iustin Pop
  hyper = hypervisor.GetHypervisor()
552 a8083063 Iustin Pop
553 a8083063 Iustin Pop
  try:
554 a8083063 Iustin Pop
    hyper.StartInstance(instance, block_devices, extra_args)
555 a8083063 Iustin Pop
  except errors.HypervisorError, err:
556 a8083063 Iustin Pop
    logger.Error("Failed to start instance: %s" % err)
557 a8083063 Iustin Pop
    return False
558 a8083063 Iustin Pop
559 a8083063 Iustin Pop
  return True
560 a8083063 Iustin Pop
561 a8083063 Iustin Pop
562 a8083063 Iustin Pop
def ShutdownInstance(instance):
563 a8083063 Iustin Pop
  """Shut an instance down.
564 a8083063 Iustin Pop

565 a8083063 Iustin Pop
  Args:
566 a8083063 Iustin Pop
    instance - name of instance to shutdown.
567 a8083063 Iustin Pop

568 098c0958 Michael Hanselmann
  """
569 a8083063 Iustin Pop
  running_instances = GetInstanceList()
570 a8083063 Iustin Pop
571 a8083063 Iustin Pop
  if instance.name not in running_instances:
572 a8083063 Iustin Pop
    return True
573 a8083063 Iustin Pop
574 a8083063 Iustin Pop
  hyper = hypervisor.GetHypervisor()
575 a8083063 Iustin Pop
  try:
576 a8083063 Iustin Pop
    hyper.StopInstance(instance)
577 a8083063 Iustin Pop
  except errors.HypervisorError, err:
578 a8083063 Iustin Pop
    logger.Error("Failed to stop instance: %s" % err)
579 a8083063 Iustin Pop
    return False
580 a8083063 Iustin Pop
581 a8083063 Iustin Pop
  # test every 10secs for 2min
582 a8083063 Iustin Pop
  shutdown_ok = False
583 a8083063 Iustin Pop
584 a8083063 Iustin Pop
  time.sleep(1)
585 a8083063 Iustin Pop
  for dummy in range(11):
586 a8083063 Iustin Pop
    if instance.name not in GetInstanceList():
587 a8083063 Iustin Pop
      break
588 a8083063 Iustin Pop
    time.sleep(10)
589 a8083063 Iustin Pop
  else:
590 a8083063 Iustin Pop
    # the shutdown did not succeed
591 a8083063 Iustin Pop
    logger.Error("shutdown of '%s' unsuccessful, using destroy" % instance)
592 a8083063 Iustin Pop
593 a8083063 Iustin Pop
    try:
594 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
595 a8083063 Iustin Pop
    except errors.HypervisorError, err:
596 a8083063 Iustin Pop
      logger.Error("Failed to stop instance: %s" % err)
597 a8083063 Iustin Pop
      return False
598 a8083063 Iustin Pop
599 a8083063 Iustin Pop
    time.sleep(1)
600 a8083063 Iustin Pop
    if instance.name in GetInstanceList():
601 a8083063 Iustin Pop
      logger.Error("could not shutdown instance '%s' even by destroy")
602 a8083063 Iustin Pop
      return False
603 a8083063 Iustin Pop
604 a8083063 Iustin Pop
  return True
605 a8083063 Iustin Pop
606 a8083063 Iustin Pop
607 007a2f3e Alexander Schreiber
def RebootInstance(instance, reboot_type, extra_args):
608 007a2f3e Alexander Schreiber
  """Reboot an instance.
609 007a2f3e Alexander Schreiber

610 007a2f3e Alexander Schreiber
  Args:
611 007a2f3e Alexander Schreiber
    instance    - name of instance to reboot
612 007a2f3e Alexander Schreiber
    reboot_type - how to reboot [soft,hard,full]
613 007a2f3e Alexander Schreiber

614 007a2f3e Alexander Schreiber
  """
615 007a2f3e Alexander Schreiber
  running_instances = GetInstanceList()
616 007a2f3e Alexander Schreiber
617 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
618 007a2f3e Alexander Schreiber
    logger.Error("Cannot reboot instance that is not running")
619 007a2f3e Alexander Schreiber
    return False
620 007a2f3e Alexander Schreiber
621 007a2f3e Alexander Schreiber
  hyper = hypervisor.GetHypervisor()
622 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
623 007a2f3e Alexander Schreiber
    try:
624 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
625 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
626 007a2f3e Alexander Schreiber
      logger.Error("Failed to soft reboot instance: %s" % err)
627 007a2f3e Alexander Schreiber
      return False
628 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
629 007a2f3e Alexander Schreiber
    try:
630 007a2f3e Alexander Schreiber
      ShutdownInstance(instance)
631 007a2f3e Alexander Schreiber
      StartInstance(instance, extra_args)
632 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
633 007a2f3e Alexander Schreiber
      logger.Error("Failed to hard reboot instance: %s" % err)
634 007a2f3e Alexander Schreiber
      return False
635 007a2f3e Alexander Schreiber
  else:
636 007a2f3e Alexander Schreiber
    raise errors.ParameterError("reboot_type invalid")
637 007a2f3e Alexander Schreiber
638 007a2f3e Alexander Schreiber
639 007a2f3e Alexander Schreiber
  return True
640 007a2f3e Alexander Schreiber
641 007a2f3e Alexander Schreiber
642 3f78eef2 Iustin Pop
def CreateBlockDevice(disk, size, owner, on_primary, info):
643 a8083063 Iustin Pop
  """Creates a block device for an instance.
644 a8083063 Iustin Pop

645 a8083063 Iustin Pop
  Args:
646 c99a3cc0 Manuel Franceschini
   disk: a ganeti.objects.Disk object
647 c99a3cc0 Manuel Franceschini
   size: the size of the physical underlying device
648 c99a3cc0 Manuel Franceschini
   owner: a string with the name of the instance
649 6c8af3d0 Manuel Franceschini
   on_primary: a boolean indicating if it is the primary node or not
650 6c8af3d0 Manuel Franceschini
   info: string that will be sent to the physical device creation
651 a8083063 Iustin Pop

652 a8083063 Iustin Pop
  Returns:
653 a8083063 Iustin Pop
    the new unique_id of the device (this can sometime be
654 a8083063 Iustin Pop
    computed only after creation), or None. On secondary nodes,
655 a8083063 Iustin Pop
    it's not required to return anything.
656 a8083063 Iustin Pop

657 a8083063 Iustin Pop
  """
658 a8083063 Iustin Pop
  clist = []
659 a8083063 Iustin Pop
  if disk.children:
660 a8083063 Iustin Pop
    for child in disk.children:
661 3f78eef2 Iustin Pop
      crdev = _RecursiveAssembleBD(child, owner, on_primary)
662 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
663 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
664 a8083063 Iustin Pop
        # be assembled
665 a8083063 Iustin Pop
        crdev.Open()
666 a8083063 Iustin Pop
      clist.append(crdev)
667 a8083063 Iustin Pop
  try:
668 a8083063 Iustin Pop
    device = bdev.FindDevice(disk.dev_type, disk.physical_id, clist)
669 a8083063 Iustin Pop
    if device is not None:
670 a8083063 Iustin Pop
      logger.Info("removing existing device %s" % disk)
671 a8083063 Iustin Pop
      device.Remove()
672 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
673 a8083063 Iustin Pop
    pass
674 a8083063 Iustin Pop
675 a8083063 Iustin Pop
  device = bdev.Create(disk.dev_type, disk.physical_id,
676 a8083063 Iustin Pop
                       clist, size)
677 a8083063 Iustin Pop
  if device is None:
678 a8083063 Iustin Pop
    raise ValueError("Can't create child device for %s, %s" %
679 a8083063 Iustin Pop
                     (disk, size))
680 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
681 cf5a8306 Iustin Pop
    if not device.Assemble():
682 20a0c9ef Guido Trotter
      errorstring = "Can't assemble device after creation"
683 20a0c9ef Guido Trotter
      logger.Error(errorstring)
684 20a0c9ef Guido Trotter
      raise errors.BlockDeviceError("%s, very unusual event - check the node"
685 20a0c9ef Guido Trotter
                                    " daemon logs" % errorstring)
686 e31c43f7 Michael Hanselmann
    device.SetSyncSpeed(constants.SYNC_SPEED)
687 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
688 a8083063 Iustin Pop
      device.Open(force=True)
689 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
690 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
691 a0c3fea1 Michael Hanselmann
692 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
693 a0c3fea1 Michael Hanselmann
694 a8083063 Iustin Pop
  physical_id = device.unique_id
695 a8083063 Iustin Pop
  return physical_id
696 a8083063 Iustin Pop
697 a8083063 Iustin Pop
698 a8083063 Iustin Pop
def RemoveBlockDevice(disk):
699 a8083063 Iustin Pop
  """Remove a block device.
700 a8083063 Iustin Pop

701 a8083063 Iustin Pop
  This is intended to be called recursively.
702 a8083063 Iustin Pop

703 a8083063 Iustin Pop
  """
704 a8083063 Iustin Pop
  try:
705 a8083063 Iustin Pop
    # since we are removing the device, allow a partial match
706 a8083063 Iustin Pop
    # this allows removal of broken mirrors
707 a8083063 Iustin Pop
    rdev = _RecursiveFindBD(disk, allow_partial=True)
708 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
709 a8083063 Iustin Pop
    # probably can't attach
710 a8083063 Iustin Pop
    logger.Info("Can't attach to device %s in remove" % disk)
711 a8083063 Iustin Pop
    rdev = None
712 a8083063 Iustin Pop
  if rdev is not None:
713 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
714 a8083063 Iustin Pop
    result = rdev.Remove()
715 3f78eef2 Iustin Pop
    if result:
716 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
717 a8083063 Iustin Pop
  else:
718 a8083063 Iustin Pop
    result = True
719 a8083063 Iustin Pop
  if disk.children:
720 a8083063 Iustin Pop
    for child in disk.children:
721 a8083063 Iustin Pop
      result = result and RemoveBlockDevice(child)
722 a8083063 Iustin Pop
  return result
723 a8083063 Iustin Pop
724 a8083063 Iustin Pop
725 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
726 a8083063 Iustin Pop
  """Activate a block device for an instance.
727 a8083063 Iustin Pop

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

730 a8083063 Iustin Pop
  This function is called recursively.
731 a8083063 Iustin Pop

732 a8083063 Iustin Pop
  Args:
733 a8083063 Iustin Pop
    disk: a objects.Disk object
734 a8083063 Iustin Pop
    as_primary: if we should make the block device read/write
735 a8083063 Iustin Pop

736 a8083063 Iustin Pop
  Returns:
737 a8083063 Iustin Pop
    the assembled device or None (in case no device was assembled)
738 a8083063 Iustin Pop

739 a8083063 Iustin Pop
  If the assembly is not successful, an exception is raised.
740 a8083063 Iustin Pop

741 a8083063 Iustin Pop
  """
742 a8083063 Iustin Pop
  children = []
743 a8083063 Iustin Pop
  if disk.children:
744 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
745 fc1dc9d7 Iustin Pop
    if mcn == -1:
746 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
747 fc1dc9d7 Iustin Pop
    else:
748 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
749 a8083063 Iustin Pop
    for chld_disk in disk.children:
750 fc1dc9d7 Iustin Pop
      try:
751 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
752 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
753 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
754 fc1dc9d7 Iustin Pop
          raise
755 fc1dc9d7 Iustin Pop
        cdev = None
756 fc1dc9d7 Iustin Pop
        logger.Debug("Error in child activation: %s" % str(err))
757 fc1dc9d7 Iustin Pop
      children.append(cdev)
758 a8083063 Iustin Pop
759 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
760 a8083063 Iustin Pop
    r_dev = bdev.AttachOrAssemble(disk.dev_type, disk.physical_id, children)
761 e31c43f7 Michael Hanselmann
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
762 a8083063 Iustin Pop
    result = r_dev
763 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
764 a8083063 Iustin Pop
      r_dev.Open()
765 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
766 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
767 3f78eef2 Iustin Pop
768 a8083063 Iustin Pop
  else:
769 a8083063 Iustin Pop
    result = True
770 a8083063 Iustin Pop
  return result
771 a8083063 Iustin Pop
772 a8083063 Iustin Pop
773 3f78eef2 Iustin Pop
def AssembleBlockDevice(disk, owner, as_primary):
774 a8083063 Iustin Pop
  """Activate a block device for an instance.
775 a8083063 Iustin Pop

776 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
777 a8083063 Iustin Pop

778 a8083063 Iustin Pop
  Returns:
779 a8083063 Iustin Pop
    a /dev path for primary nodes
780 a8083063 Iustin Pop
    True for secondary nodes
781 a8083063 Iustin Pop

782 a8083063 Iustin Pop
  """
783 3f78eef2 Iustin Pop
  result = _RecursiveAssembleBD(disk, owner, as_primary)
784 a8083063 Iustin Pop
  if isinstance(result, bdev.BlockDev):
785 a8083063 Iustin Pop
    result = result.dev_path
786 a8083063 Iustin Pop
  return result
787 a8083063 Iustin Pop
788 a8083063 Iustin Pop
789 a8083063 Iustin Pop
def ShutdownBlockDevice(disk):
790 a8083063 Iustin Pop
  """Shut down a block device.
791 a8083063 Iustin Pop

792 a8083063 Iustin Pop
  First, if the device is assembled (can `Attach()`), then the device
793 a8083063 Iustin Pop
  is shutdown. Then the children of the device are shutdown.
794 a8083063 Iustin Pop

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

799 a8083063 Iustin Pop
  """
800 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
801 a8083063 Iustin Pop
  if r_dev is not None:
802 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
803 a8083063 Iustin Pop
    result = r_dev.Shutdown()
804 3f78eef2 Iustin Pop
    if result:
805 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
806 a8083063 Iustin Pop
  else:
807 a8083063 Iustin Pop
    result = True
808 a8083063 Iustin Pop
  if disk.children:
809 a8083063 Iustin Pop
    for child in disk.children:
810 a8083063 Iustin Pop
      result = result and ShutdownBlockDevice(child)
811 a8083063 Iustin Pop
  return result
812 a8083063 Iustin Pop
813 a8083063 Iustin Pop
814 153d9724 Iustin Pop
def MirrorAddChildren(parent_cdev, new_cdevs):
815 153d9724 Iustin Pop
  """Extend a mirrored block device.
816 a8083063 Iustin Pop

817 a8083063 Iustin Pop
  """
818 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev, allow_partial=True)
819 153d9724 Iustin Pop
  if parent_bdev is None:
820 153d9724 Iustin Pop
    logger.Error("Can't find parent device")
821 a8083063 Iustin Pop
    return False
822 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
823 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
824 a9e0c397 Iustin Pop
    logger.Error("Can't find new device(s) to add: %s:%s" %
825 a9e0c397 Iustin Pop
                 (new_bdevs, new_cdevs))
826 a8083063 Iustin Pop
    return False
827 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
828 a8083063 Iustin Pop
  return True
829 a8083063 Iustin Pop
830 a8083063 Iustin Pop
831 153d9724 Iustin Pop
def MirrorRemoveChildren(parent_cdev, new_cdevs):
832 153d9724 Iustin Pop
  """Shrink a mirrored block device.
833 a8083063 Iustin Pop

834 a8083063 Iustin Pop
  """
835 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
836 153d9724 Iustin Pop
  if parent_bdev is None:
837 a9e0c397 Iustin Pop
    logger.Error("Can't find parent in remove children: %s" % parent_cdev)
838 a8083063 Iustin Pop
    return False
839 e739bd57 Iustin Pop
  devs = []
840 e739bd57 Iustin Pop
  for disk in new_cdevs:
841 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
842 e739bd57 Iustin Pop
    if rpath is None:
843 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
844 e739bd57 Iustin Pop
      if bd is None:
845 e739bd57 Iustin Pop
        logger.Error("Can't find dynamic device %s while removing children" %
846 e739bd57 Iustin Pop
                     disk)
847 e739bd57 Iustin Pop
        return False
848 e739bd57 Iustin Pop
      else:
849 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
850 e739bd57 Iustin Pop
    else:
851 e739bd57 Iustin Pop
      devs.append(rpath)
852 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
853 a8083063 Iustin Pop
  return True
854 a8083063 Iustin Pop
855 a8083063 Iustin Pop
856 a8083063 Iustin Pop
def GetMirrorStatus(disks):
857 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
858 a8083063 Iustin Pop

859 a8083063 Iustin Pop
  Args:
860 a8083063 Iustin Pop
    disks: list of `objects.Disk`
861 a8083063 Iustin Pop

862 a8083063 Iustin Pop
  Returns:
863 a8083063 Iustin Pop
    list of (mirror_done, estimated_time) tuples, which
864 a8083063 Iustin Pop
    are the result of bdev.BlockDevice.CombinedSyncStatus()
865 a8083063 Iustin Pop

866 a8083063 Iustin Pop
  """
867 a8083063 Iustin Pop
  stats = []
868 a8083063 Iustin Pop
  for dsk in disks:
869 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
870 a8083063 Iustin Pop
    if rbd is None:
871 3ecf6786 Iustin Pop
      raise errors.BlockDeviceError("Can't find device %s" % str(dsk))
872 a8083063 Iustin Pop
    stats.append(rbd.CombinedSyncStatus())
873 a8083063 Iustin Pop
  return stats
874 a8083063 Iustin Pop
875 a8083063 Iustin Pop
876 a8083063 Iustin Pop
def _RecursiveFindBD(disk, allow_partial=False):
877 a8083063 Iustin Pop
  """Check if a device is activated.
878 a8083063 Iustin Pop

879 a8083063 Iustin Pop
  If so, return informations about the real device.
880 a8083063 Iustin Pop

881 a8083063 Iustin Pop
  Args:
882 a8083063 Iustin Pop
    disk: the objects.Disk instance
883 a8083063 Iustin Pop
    allow_partial: don't abort the find if a child of the
884 a8083063 Iustin Pop
                   device can't be found; this is intended to be
885 a8083063 Iustin Pop
                   used when repairing mirrors
886 a8083063 Iustin Pop

887 a8083063 Iustin Pop
  Returns:
888 a8083063 Iustin Pop
    None if the device can't be found
889 a8083063 Iustin Pop
    otherwise the device instance
890 a8083063 Iustin Pop

891 a8083063 Iustin Pop
  """
892 a8083063 Iustin Pop
  children = []
893 a8083063 Iustin Pop
  if disk.children:
894 a8083063 Iustin Pop
    for chdisk in disk.children:
895 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
896 a8083063 Iustin Pop
897 a8083063 Iustin Pop
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children)
898 a8083063 Iustin Pop
899 a8083063 Iustin Pop
900 a8083063 Iustin Pop
def FindBlockDevice(disk):
901 a8083063 Iustin Pop
  """Check if a device is activated.
902 a8083063 Iustin Pop

903 a8083063 Iustin Pop
  If so, return informations about the real device.
904 a8083063 Iustin Pop

905 a8083063 Iustin Pop
  Args:
906 a8083063 Iustin Pop
    disk: the objects.Disk instance
907 a8083063 Iustin Pop
  Returns:
908 a8083063 Iustin Pop
    None if the device can't be found
909 a8083063 Iustin Pop
    (device_path, major, minor, sync_percent, estimated_time, is_degraded)
910 a8083063 Iustin Pop

911 a8083063 Iustin Pop
  """
912 a8083063 Iustin Pop
  rbd = _RecursiveFindBD(disk)
913 a8083063 Iustin Pop
  if rbd is None:
914 a8083063 Iustin Pop
    return rbd
915 0834c866 Iustin Pop
  return (rbd.dev_path, rbd.major, rbd.minor) + rbd.GetSyncStatus()
916 a8083063 Iustin Pop
917 a8083063 Iustin Pop
918 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
919 a8083063 Iustin Pop
  """Write a file to the filesystem.
920 a8083063 Iustin Pop

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

924 a8083063 Iustin Pop
  """
925 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
926 a8083063 Iustin Pop
    logger.Error("Filename passed to UploadFile is not absolute: '%s'" %
927 a8083063 Iustin Pop
                 file_name)
928 a8083063 Iustin Pop
    return False
929 a8083063 Iustin Pop
930 97628462 Iustin Pop
  allowed_files = [
931 97628462 Iustin Pop
    constants.CLUSTER_CONF_FILE,
932 97628462 Iustin Pop
    constants.ETC_HOSTS,
933 97628462 Iustin Pop
    constants.SSH_KNOWN_HOSTS_FILE,
934 97628462 Iustin Pop
    ]
935 880478f8 Iustin Pop
  allowed_files.extend(ssconf.SimpleStore().GetFileList())
936 880478f8 Iustin Pop
  if file_name not in allowed_files:
937 a8083063 Iustin Pop
    logger.Error("Filename passed to UploadFile not in allowed"
938 a8083063 Iustin Pop
                 " upload targets: '%s'" % file_name)
939 a8083063 Iustin Pop
    return False
940 a8083063 Iustin Pop
941 41a57aab Michael Hanselmann
  utils.WriteFile(file_name, data=data, mode=mode, uid=uid, gid=gid,
942 41a57aab Michael Hanselmann
                  atime=atime, mtime=mtime)
943 a8083063 Iustin Pop
  return True
944 a8083063 Iustin Pop
945 386b57af Iustin Pop
946 a8083063 Iustin Pop
def _ErrnoOrStr(err):
947 a8083063 Iustin Pop
  """Format an EnvironmentError exception.
948 a8083063 Iustin Pop

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

953 a8083063 Iustin Pop
  """
954 a8083063 Iustin Pop
  if hasattr(err, 'errno'):
955 a8083063 Iustin Pop
    detail = errno.errorcode[err.errno]
956 a8083063 Iustin Pop
  else:
957 a8083063 Iustin Pop
    detail = str(err)
958 a8083063 Iustin Pop
  return detail
959 a8083063 Iustin Pop
960 5d0fe286 Iustin Pop
961 56bcd3f4 Guido Trotter
def _OSSearch(name, search_path=None):
962 56bcd3f4 Guido Trotter
  """Search for OSes with the given name in the search_path.
963 56bcd3f4 Guido Trotter

964 56bcd3f4 Guido Trotter
  Args:
965 56bcd3f4 Guido Trotter
    name: The name of the OS to look for
966 56bcd3f4 Guido Trotter
    search_path: List of dirs to search (defaults to constants.OS_SEARCH_PATH)
967 305a7297 Guido Trotter

968 56bcd3f4 Guido Trotter
  Returns:
969 56bcd3f4 Guido Trotter
    The base_dir the OS resides in
970 56bcd3f4 Guido Trotter

971 56bcd3f4 Guido Trotter
  """
972 56bcd3f4 Guido Trotter
  if search_path is None:
973 56bcd3f4 Guido Trotter
    search_path = constants.OS_SEARCH_PATH
974 56bcd3f4 Guido Trotter
975 65fe4693 Iustin Pop
  for dir_name in search_path:
976 65fe4693 Iustin Pop
    t_os_dir = os.path.sep.join([dir_name, name])
977 56bcd3f4 Guido Trotter
    if os.path.isdir(t_os_dir):
978 65fe4693 Iustin Pop
      return dir_name
979 56bcd3f4 Guido Trotter
980 56bcd3f4 Guido Trotter
  return None
981 a8083063 Iustin Pop
982 5d0fe286 Iustin Pop
983 c26dabd7 Guido Trotter
def _OSOndiskVersion(name, os_dir):
984 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
985 a8083063 Iustin Pop

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

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

992 a8083063 Iustin Pop
  """
993 a8083063 Iustin Pop
  api_file = os.path.sep.join([os_dir, "ganeti_api_version"])
994 a8083063 Iustin Pop
995 a8083063 Iustin Pop
  try:
996 a8083063 Iustin Pop
    st = os.stat(api_file)
997 a8083063 Iustin Pop
  except EnvironmentError, err:
998 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "'ganeti_api_version' file not"
999 3ecf6786 Iustin Pop
                           " found (%s)" % _ErrnoOrStr(err))
1000 a8083063 Iustin Pop
1001 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1002 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "'ganeti_api_version' file is not"
1003 3ecf6786 Iustin Pop
                           " a regular file")
1004 a8083063 Iustin Pop
1005 a8083063 Iustin Pop
  try:
1006 a8083063 Iustin Pop
    f = open(api_file)
1007 a8083063 Iustin Pop
    try:
1008 a8083063 Iustin Pop
      api_version = f.read(256)
1009 a8083063 Iustin Pop
    finally:
1010 a8083063 Iustin Pop
      f.close()
1011 a8083063 Iustin Pop
  except EnvironmentError, err:
1012 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "error while reading the"
1013 3ecf6786 Iustin Pop
                           " API version (%s)" % _ErrnoOrStr(err))
1014 a8083063 Iustin Pop
1015 a8083063 Iustin Pop
  api_version = api_version.strip()
1016 a8083063 Iustin Pop
  try:
1017 a8083063 Iustin Pop
    api_version = int(api_version)
1018 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
1019 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir,
1020 305a7297 Guido Trotter
                           "API version is not integer (%s)" % str(err))
1021 a8083063 Iustin Pop
1022 a8083063 Iustin Pop
  return api_version
1023 a8083063 Iustin Pop
1024 386b57af Iustin Pop
1025 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
1026 a8083063 Iustin Pop
  """Compute the validity for all OSes.
1027 a8083063 Iustin Pop

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

1031 a8083063 Iustin Pop
  Returns:
1032 8fa42c7c Guido Trotter
    list of OS objects
1033 a8083063 Iustin Pop

1034 a8083063 Iustin Pop
  """
1035 7c3d51d4 Guido Trotter
  if top_dirs is None:
1036 7c3d51d4 Guido Trotter
    top_dirs = constants.OS_SEARCH_PATH
1037 a8083063 Iustin Pop
1038 a8083063 Iustin Pop
  result = []
1039 65fe4693 Iustin Pop
  for dir_name in top_dirs:
1040 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
1041 7c3d51d4 Guido Trotter
      try:
1042 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
1043 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
1044 65fe4693 Iustin Pop
        logger.Error("Can't list the OS directory %s: %s" %
1045 65fe4693 Iustin Pop
                     (dir_name, str(err)))
1046 7c3d51d4 Guido Trotter
        break
1047 7c3d51d4 Guido Trotter
      for name in f_names:
1048 7c3d51d4 Guido Trotter
        try:
1049 65fe4693 Iustin Pop
          os_inst = OSFromDisk(name, base_dir=dir_name)
1050 7c3d51d4 Guido Trotter
          result.append(os_inst)
1051 7c3d51d4 Guido Trotter
        except errors.InvalidOS, err:
1052 8fa42c7c Guido Trotter
          result.append(objects.OS.FromInvalidOS(err))
1053 a8083063 Iustin Pop
1054 a8083063 Iustin Pop
  return result
1055 a8083063 Iustin Pop
1056 a8083063 Iustin Pop
1057 56bcd3f4 Guido Trotter
def OSFromDisk(name, base_dir=None):
1058 a8083063 Iustin Pop
  """Create an OS instance from disk.
1059 a8083063 Iustin Pop

1060 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
1061 a8083063 Iustin Pop
  valid OS name. Otherwise, it will raise an appropriate
1062 a8083063 Iustin Pop
  `errors.InvalidOS` exception, detailing why this is not a valid
1063 a8083063 Iustin Pop
  OS.
1064 a8083063 Iustin Pop

1065 7c3d51d4 Guido Trotter
  Args:
1066 7c3d51d4 Guido Trotter
    os_dir: Directory containing the OS scripts. Defaults to a search
1067 7c3d51d4 Guido Trotter
            in all the OS_SEARCH_PATH directories.
1068 7c3d51d4 Guido Trotter

1069 a8083063 Iustin Pop
  """
1070 7c3d51d4 Guido Trotter
1071 56bcd3f4 Guido Trotter
  if base_dir is None:
1072 56bcd3f4 Guido Trotter
    base_dir = _OSSearch(name)
1073 7c3d51d4 Guido Trotter
1074 56bcd3f4 Guido Trotter
  if base_dir is None:
1075 305a7297 Guido Trotter
    raise errors.InvalidOS(name, None, "OS dir not found in search path")
1076 a8083063 Iustin Pop
1077 56bcd3f4 Guido Trotter
  os_dir = os.path.sep.join([base_dir, name])
1078 c26dabd7 Guido Trotter
  api_version = _OSOndiskVersion(name, os_dir)
1079 a8083063 Iustin Pop
1080 a8083063 Iustin Pop
  if api_version != constants.OS_API_VERSION:
1081 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "API version mismatch"
1082 305a7297 Guido Trotter
                           " (found %s want %s)"
1083 3ecf6786 Iustin Pop
                           % (api_version, constants.OS_API_VERSION))
1084 a8083063 Iustin Pop
1085 a8083063 Iustin Pop
  # OS Scripts dictionary, we will populate it with the actual script names
1086 386b57af Iustin Pop
  os_scripts = {'create': '', 'export': '', 'import': '', 'rename': ''}
1087 a8083063 Iustin Pop
1088 a8083063 Iustin Pop
  for script in os_scripts:
1089 a8083063 Iustin Pop
    os_scripts[script] = os.path.sep.join([os_dir, script])
1090 a8083063 Iustin Pop
1091 a8083063 Iustin Pop
    try:
1092 a8083063 Iustin Pop
      st = os.stat(os_scripts[script])
1093 a8083063 Iustin Pop
    except EnvironmentError, err:
1094 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' script missing (%s)" %
1095 3ecf6786 Iustin Pop
                             (script, _ErrnoOrStr(err)))
1096 a8083063 Iustin Pop
1097 a8083063 Iustin Pop
    if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1098 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' script not executable" %
1099 305a7297 Guido Trotter
                             script)
1100 a8083063 Iustin Pop
1101 a8083063 Iustin Pop
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1102 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' is not a regular file" %
1103 305a7297 Guido Trotter
                             script)
1104 a8083063 Iustin Pop
1105 a8083063 Iustin Pop
1106 8fa42c7c Guido Trotter
  return objects.OS(name=name, path=os_dir, status=constants.OS_VALID_STATUS,
1107 a8083063 Iustin Pop
                    create_script=os_scripts['create'],
1108 a8083063 Iustin Pop
                    export_script=os_scripts['export'],
1109 a8083063 Iustin Pop
                    import_script=os_scripts['import'],
1110 386b57af Iustin Pop
                    rename_script=os_scripts['rename'],
1111 a8083063 Iustin Pop
                    api_version=api_version)
1112 a8083063 Iustin Pop
1113 a8083063 Iustin Pop
1114 a8083063 Iustin Pop
def SnapshotBlockDevice(disk):
1115 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
1116 a8083063 Iustin Pop

1117 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
1118 a8083063 Iustin Pop
  just for the leaf lvm backend device.
1119 a8083063 Iustin Pop

1120 a8083063 Iustin Pop
  Args:
1121 a8083063 Iustin Pop
    disk: the disk to be snapshotted
1122 a8083063 Iustin Pop

1123 a8083063 Iustin Pop
  Returns:
1124 a8083063 Iustin Pop
    a config entry for the actual lvm device snapshotted.
1125 a8083063 Iustin Pop

1126 098c0958 Michael Hanselmann
  """
1127 a8083063 Iustin Pop
  if disk.children:
1128 a8083063 Iustin Pop
    if len(disk.children) == 1:
1129 a8083063 Iustin Pop
      # only one child, let's recurse on it
1130 a8083063 Iustin Pop
      return SnapshotBlockDevice(disk.children[0])
1131 a8083063 Iustin Pop
    else:
1132 a8083063 Iustin Pop
      # more than one child, choose one that matches
1133 a8083063 Iustin Pop
      for child in disk.children:
1134 a8083063 Iustin Pop
        if child.size == disk.size:
1135 a8083063 Iustin Pop
          # return implies breaking the loop
1136 a8083063 Iustin Pop
          return SnapshotBlockDevice(child)
1137 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
1138 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
1139 a8083063 Iustin Pop
    if r_dev is not None:
1140 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
1141 a8083063 Iustin Pop
      return r_dev.Snapshot(disk.size)
1142 a8083063 Iustin Pop
    else:
1143 a8083063 Iustin Pop
      return None
1144 a8083063 Iustin Pop
  else:
1145 3ecf6786 Iustin Pop
    raise errors.ProgrammerError("Cannot snapshot non-lvm block device"
1146 f4bc1f2c Michael Hanselmann
                                 " '%s' of type '%s'" %
1147 3ecf6786 Iustin Pop
                                 (disk.unique_id, disk.dev_type))
1148 a8083063 Iustin Pop
1149 a8083063 Iustin Pop
1150 a8083063 Iustin Pop
def ExportSnapshot(disk, dest_node, instance):
1151 a8083063 Iustin Pop
  """Export a block device snapshot to a remote node.
1152 a8083063 Iustin Pop

1153 a8083063 Iustin Pop
  Args:
1154 a8083063 Iustin Pop
    disk: the snapshot block device
1155 a8083063 Iustin Pop
    dest_node: the node to send the image to
1156 a8083063 Iustin Pop
    instance: instance being exported
1157 a8083063 Iustin Pop

1158 a8083063 Iustin Pop
  Returns:
1159 a8083063 Iustin Pop
    True if successful, False otherwise.
1160 a8083063 Iustin Pop

1161 098c0958 Michael Hanselmann
  """
1162 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1163 a8083063 Iustin Pop
  export_script = inst_os.export_script
1164 a8083063 Iustin Pop
1165 a8083063 Iustin Pop
  logfile = "%s/exp-%s-%s-%s.log" % (constants.LOG_OS_DIR, inst_os.name,
1166 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
1167 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
1168 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
1169 a8083063 Iustin Pop
1170 a8083063 Iustin Pop
  real_os_dev = _RecursiveFindBD(disk)
1171 a8083063 Iustin Pop
  if real_os_dev is None:
1172 a8083063 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
1173 a8083063 Iustin Pop
                                  str(disk))
1174 a8083063 Iustin Pop
  real_os_dev.Open()
1175 a8083063 Iustin Pop
1176 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1177 a8083063 Iustin Pop
  destfile = disk.physical_id[1]
1178 a8083063 Iustin Pop
1179 a8083063 Iustin Pop
  # the target command is built out of three individual commands,
1180 a8083063 Iustin Pop
  # which are joined by pipes; we check each individual command for
1181 a8083063 Iustin Pop
  # valid parameters
1182 a8083063 Iustin Pop
1183 a8083063 Iustin Pop
  expcmd = utils.BuildShellCmd("cd %s; %s -i %s -b %s 2>%s", inst_os.path,
1184 a8083063 Iustin Pop
                               export_script, instance.name,
1185 a8083063 Iustin Pop
                               real_os_dev.dev_path, logfile)
1186 a8083063 Iustin Pop
1187 a8083063 Iustin Pop
  comprcmd = "gzip"
1188 a8083063 Iustin Pop
1189 72f0f7fd Iustin Pop
  destcmd = utils.BuildShellCmd("mkdir -p %s && cat > %s/%s",
1190 00003458 Guido Trotter
                                destdir, destdir, destfile)
1191 7900ed01 Iustin Pop
  remotecmd = ssh.BuildSSHCmd(dest_node, constants.GANETI_RUNAS, destcmd)
1192 72f0f7fd Iustin Pop
1193 72f0f7fd Iustin Pop
1194 a8083063 Iustin Pop
1195 a8083063 Iustin Pop
  # all commands have been checked, so we're safe to combine them
1196 72f0f7fd Iustin Pop
  command = '|'.join([expcmd, comprcmd, utils.ShellQuoteArgs(remotecmd)])
1197 a8083063 Iustin Pop
1198 a8083063 Iustin Pop
  result = utils.RunCmd(command)
1199 a8083063 Iustin Pop
1200 a8083063 Iustin Pop
  if result.failed:
1201 a8083063 Iustin Pop
    logger.Error("os snapshot export command '%s' returned error: %s"
1202 a8083063 Iustin Pop
                 " output: %s" %
1203 a8083063 Iustin Pop
                 (command, result.fail_reason, result.output))
1204 a8083063 Iustin Pop
    return False
1205 a8083063 Iustin Pop
1206 a8083063 Iustin Pop
  return True
1207 a8083063 Iustin Pop
1208 a8083063 Iustin Pop
1209 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
1210 a8083063 Iustin Pop
  """Write out the export configuration information.
1211 a8083063 Iustin Pop

1212 a8083063 Iustin Pop
  Args:
1213 a8083063 Iustin Pop
    instance: instance configuration
1214 a8083063 Iustin Pop
    snap_disks: snapshot block devices
1215 a8083063 Iustin Pop

1216 a8083063 Iustin Pop
  Returns:
1217 a8083063 Iustin Pop
    False in case of error, True otherwise.
1218 a8083063 Iustin Pop

1219 098c0958 Michael Hanselmann
  """
1220 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1221 a8083063 Iustin Pop
  finaldestdir = os.path.join(constants.EXPORT_DIR, instance.name)
1222 a8083063 Iustin Pop
1223 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1224 a8083063 Iustin Pop
1225 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
1226 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'version', '0')
1227 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
1228 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'source', instance.primary_node)
1229 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'os', instance.os)
1230 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'compression', 'gzip')
1231 a8083063 Iustin Pop
1232 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
1233 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'name', instance.name)
1234 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'memory', '%d' % instance.memory)
1235 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'vcpus', '%d' % instance.vcpus)
1236 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
1237 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
1238 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_mac' %
1239 a8083063 Iustin Pop
               nic_count, '%s' % nic.mac)
1240 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
1241 1cafd236 Guido Trotter
    config.set(constants.INISECT_INS, 'nic%d_bridge' % nic_count, '%s' % nic.bridge)
1242 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
1243 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_count)
1244 a8083063 Iustin Pop
1245 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
1246 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
1247 a8083063 Iustin Pop
               ('%s' % disk.iv_name))
1248 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
1249 a8083063 Iustin Pop
               ('%s' % disk.physical_id[1]))
1250 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
1251 a8083063 Iustin Pop
               ('%d' % disk.size))
1252 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_count)
1253 a8083063 Iustin Pop
1254 a8083063 Iustin Pop
  cff = os.path.join(destdir, constants.EXPORT_CONF_FILE)
1255 a8083063 Iustin Pop
  cfo = open(cff, 'w')
1256 a8083063 Iustin Pop
  try:
1257 a8083063 Iustin Pop
    config.write(cfo)
1258 a8083063 Iustin Pop
  finally:
1259 a8083063 Iustin Pop
    cfo.close()
1260 a8083063 Iustin Pop
1261 a8083063 Iustin Pop
  shutil.rmtree(finaldestdir, True)
1262 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
1263 a8083063 Iustin Pop
1264 a8083063 Iustin Pop
  return True
1265 a8083063 Iustin Pop
1266 a8083063 Iustin Pop
1267 a8083063 Iustin Pop
def ExportInfo(dest):
1268 a8083063 Iustin Pop
  """Get export configuration information.
1269 a8083063 Iustin Pop

1270 a8083063 Iustin Pop
  Args:
1271 a8083063 Iustin Pop
    dest: directory containing the export
1272 a8083063 Iustin Pop

1273 a8083063 Iustin Pop
  Returns:
1274 a8083063 Iustin Pop
    A serializable config file containing the export info.
1275 a8083063 Iustin Pop

1276 a8083063 Iustin Pop
  """
1277 a8083063 Iustin Pop
  cff = os.path.join(dest, constants.EXPORT_CONF_FILE)
1278 a8083063 Iustin Pop
1279 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1280 a8083063 Iustin Pop
  config.read(cff)
1281 a8083063 Iustin Pop
1282 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
1283 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
1284 a8083063 Iustin Pop
    return None
1285 a8083063 Iustin Pop
1286 a8083063 Iustin Pop
  return config
1287 a8083063 Iustin Pop
1288 a8083063 Iustin Pop
1289 a8083063 Iustin Pop
def ImportOSIntoInstance(instance, os_disk, swap_disk, src_node, src_image):
1290 a8083063 Iustin Pop
  """Import an os image into an instance.
1291 a8083063 Iustin Pop

1292 a8083063 Iustin Pop
  Args:
1293 a8083063 Iustin Pop
    instance: the instance object
1294 a8083063 Iustin Pop
    os_disk: the instance-visible name of the os device
1295 a8083063 Iustin Pop
    swap_disk: the instance-visible name of the swap device
1296 a8083063 Iustin Pop
    src_node: node holding the source image
1297 a8083063 Iustin Pop
    src_image: path to the source image on src_node
1298 a8083063 Iustin Pop

1299 a8083063 Iustin Pop
  Returns:
1300 a8083063 Iustin Pop
    False in case of error, True otherwise.
1301 a8083063 Iustin Pop

1302 a8083063 Iustin Pop
  """
1303 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1304 a8083063 Iustin Pop
  import_script = inst_os.import_script
1305 a8083063 Iustin Pop
1306 9716fdce Iustin Pop
  os_device = instance.FindDisk(os_disk)
1307 9716fdce Iustin Pop
  if os_device is None:
1308 a8083063 Iustin Pop
    logger.Error("Can't find this device-visible name '%s'" % os_disk)
1309 a8083063 Iustin Pop
    return False
1310 a8083063 Iustin Pop
1311 9716fdce Iustin Pop
  swap_device = instance.FindDisk(swap_disk)
1312 9716fdce Iustin Pop
  if swap_device is None:
1313 a8083063 Iustin Pop
    logger.Error("Can't find this device-visible name '%s'" % swap_disk)
1314 a8083063 Iustin Pop
    return False
1315 a8083063 Iustin Pop
1316 a8083063 Iustin Pop
  real_os_dev = _RecursiveFindBD(os_device)
1317 a8083063 Iustin Pop
  if real_os_dev is None:
1318 3ecf6786 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
1319 3ecf6786 Iustin Pop
                                  str(os_device))
1320 a8083063 Iustin Pop
  real_os_dev.Open()
1321 a8083063 Iustin Pop
1322 a8083063 Iustin Pop
  real_swap_dev = _RecursiveFindBD(swap_device)
1323 a8083063 Iustin Pop
  if real_swap_dev is None:
1324 3ecf6786 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
1325 3ecf6786 Iustin Pop
                                  str(swap_device))
1326 a8083063 Iustin Pop
  real_swap_dev.Open()
1327 a8083063 Iustin Pop
1328 a8083063 Iustin Pop
  logfile = "%s/import-%s-%s-%s.log" % (constants.LOG_OS_DIR, instance.os,
1329 a8083063 Iustin Pop
                                        instance.name, int(time.time()))
1330 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
1331 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
1332 a8083063 Iustin Pop
1333 00003458 Guido Trotter
  destcmd = utils.BuildShellCmd('cat %s', src_image)
1334 7900ed01 Iustin Pop
  remotecmd = ssh.BuildSSHCmd(src_node, constants.GANETI_RUNAS, destcmd)
1335 a8083063 Iustin Pop
1336 a8083063 Iustin Pop
  comprcmd = "gunzip"
1337 a8083063 Iustin Pop
  impcmd = utils.BuildShellCmd("(cd %s; %s -i %s -b %s -s %s &>%s)",
1338 a8083063 Iustin Pop
                               inst_os.path, import_script, instance.name,
1339 a8083063 Iustin Pop
                               real_os_dev.dev_path, real_swap_dev.dev_path,
1340 a8083063 Iustin Pop
                               logfile)
1341 a8083063 Iustin Pop
1342 72f0f7fd Iustin Pop
  command = '|'.join([utils.ShellQuoteArgs(remotecmd), comprcmd, impcmd])
1343 a8083063 Iustin Pop
1344 a8083063 Iustin Pop
  result = utils.RunCmd(command)
1345 a8083063 Iustin Pop
1346 a8083063 Iustin Pop
  if result.failed:
1347 a8083063 Iustin Pop
    logger.Error("os import command '%s' returned error: %s"
1348 a8083063 Iustin Pop
                 " output: %s" %
1349 a8083063 Iustin Pop
                 (command, result.fail_reason, result.output))
1350 a8083063 Iustin Pop
    return False
1351 a8083063 Iustin Pop
1352 a8083063 Iustin Pop
  return True
1353 a8083063 Iustin Pop
1354 a8083063 Iustin Pop
1355 a8083063 Iustin Pop
def ListExports():
1356 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
1357 098c0958 Michael Hanselmann

1358 a8083063 Iustin Pop
  """
1359 a8083063 Iustin Pop
  if os.path.isdir(constants.EXPORT_DIR):
1360 eedbda4b Michael Hanselmann
    return utils.ListVisibleFiles(constants.EXPORT_DIR)
1361 a8083063 Iustin Pop
  else:
1362 a8083063 Iustin Pop
    return []
1363 a8083063 Iustin Pop
1364 a8083063 Iustin Pop
1365 a8083063 Iustin Pop
def RemoveExport(export):
1366 a8083063 Iustin Pop
  """Remove an existing export from the node.
1367 a8083063 Iustin Pop

1368 a8083063 Iustin Pop
  Args:
1369 a8083063 Iustin Pop
    export: the name of the export to remove
1370 a8083063 Iustin Pop

1371 a8083063 Iustin Pop
  Returns:
1372 a8083063 Iustin Pop
    False in case of error, True otherwise.
1373 a8083063 Iustin Pop

1374 098c0958 Michael Hanselmann
  """
1375 a8083063 Iustin Pop
  target = os.path.join(constants.EXPORT_DIR, export)
1376 a8083063 Iustin Pop
1377 a8083063 Iustin Pop
  shutil.rmtree(target)
1378 a8083063 Iustin Pop
  # TODO: catch some of the relevant exceptions and provide a pretty
1379 a8083063 Iustin Pop
  # error message if rmtree fails.
1380 a8083063 Iustin Pop
1381 a8083063 Iustin Pop
  return True
1382 a8083063 Iustin Pop
1383 a8083063 Iustin Pop
1384 f3e513ad Iustin Pop
def RenameBlockDevices(devlist):
1385 f3e513ad Iustin Pop
  """Rename a list of block devices.
1386 f3e513ad Iustin Pop

1387 f3e513ad Iustin Pop
  The devlist argument is a list of tuples (disk, new_logical,
1388 f3e513ad Iustin Pop
  new_physical). The return value will be a combined boolean result
1389 f3e513ad Iustin Pop
  (True only if all renames succeeded).
1390 f3e513ad Iustin Pop

1391 f3e513ad Iustin Pop
  """
1392 f3e513ad Iustin Pop
  result = True
1393 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
1394 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
1395 f3e513ad Iustin Pop
    if dev is None:
1396 f3e513ad Iustin Pop
      result = False
1397 f3e513ad Iustin Pop
      continue
1398 f3e513ad Iustin Pop
    try:
1399 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
1400 f3e513ad Iustin Pop
      dev.Rename(unique_id)
1401 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
1402 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
1403 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
1404 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
1405 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
1406 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
1407 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
1408 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
1409 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
1410 f3e513ad Iustin Pop
      logger.Error("Can't rename device '%s' to '%s': %s" %
1411 f3e513ad Iustin Pop
                   (dev, unique_id, err))
1412 f3e513ad Iustin Pop
      result = False
1413 f3e513ad Iustin Pop
  return result
1414 f3e513ad Iustin Pop
1415 f3e513ad Iustin Pop
1416 a8083063 Iustin Pop
class HooksRunner(object):
1417 a8083063 Iustin Pop
  """Hook runner.
1418 a8083063 Iustin Pop

1419 a8083063 Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
1420 a8083063 Iustin Pop
  the master side.
1421 a8083063 Iustin Pop

1422 a8083063 Iustin Pop
  """
1423 a8083063 Iustin Pop
  RE_MASK = re.compile("^[a-zA-Z0-9_-]+$")
1424 a8083063 Iustin Pop
1425 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
1426 a8083063 Iustin Pop
    """Constructor for hooks runner.
1427 a8083063 Iustin Pop

1428 a8083063 Iustin Pop
    Args:
1429 a8083063 Iustin Pop
      - hooks_base_dir: if not None, this overrides the
1430 a8083063 Iustin Pop
        constants.HOOKS_BASE_DIR (useful for unittests)
1431 a8083063 Iustin Pop
      - logs_base_dir: if not None, this overrides the
1432 a8083063 Iustin Pop
        constants.LOG_HOOKS_DIR (useful for unittests)
1433 a8083063 Iustin Pop
      - logging: enable or disable logging of script output
1434 a8083063 Iustin Pop

1435 a8083063 Iustin Pop
    """
1436 a8083063 Iustin Pop
    if hooks_base_dir is None:
1437 a8083063 Iustin Pop
      hooks_base_dir = constants.HOOKS_BASE_DIR
1438 a8083063 Iustin Pop
    self._BASE_DIR = hooks_base_dir
1439 a8083063 Iustin Pop
1440 a8083063 Iustin Pop
  @staticmethod
1441 a8083063 Iustin Pop
  def ExecHook(script, env):
1442 a8083063 Iustin Pop
    """Exec one hook script.
1443 a8083063 Iustin Pop

1444 a8083063 Iustin Pop
    Args:
1445 a8083063 Iustin Pop
     - phase: the phase
1446 a8083063 Iustin Pop
     - script: the full path to the script
1447 a8083063 Iustin Pop
     - env: the environment with which to exec the script
1448 a8083063 Iustin Pop

1449 a8083063 Iustin Pop
    """
1450 a8083063 Iustin Pop
    # exec the process using subprocess and log the output
1451 a8083063 Iustin Pop
    fdstdin = None
1452 a8083063 Iustin Pop
    try:
1453 a8083063 Iustin Pop
      fdstdin = open("/dev/null", "r")
1454 a8083063 Iustin Pop
      child = subprocess.Popen([script], stdin=fdstdin, stdout=subprocess.PIPE,
1455 a8083063 Iustin Pop
                               stderr=subprocess.STDOUT, close_fds=True,
1456 147af04d Iustin Pop
                               shell=False, cwd="/", env=env)
1457 a8083063 Iustin Pop
      output = ""
1458 a8083063 Iustin Pop
      try:
1459 a8083063 Iustin Pop
        output = child.stdout.read(4096)
1460 a8083063 Iustin Pop
        child.stdout.close()
1461 a8083063 Iustin Pop
      except EnvironmentError, err:
1462 a8083063 Iustin Pop
        output += "Hook script error: %s" % str(err)
1463 a8083063 Iustin Pop
1464 a8083063 Iustin Pop
      while True:
1465 a8083063 Iustin Pop
        try:
1466 a8083063 Iustin Pop
          result = child.wait()
1467 a8083063 Iustin Pop
          break
1468 a8083063 Iustin Pop
        except EnvironmentError, err:
1469 a8083063 Iustin Pop
          if err.errno == errno.EINTR:
1470 a8083063 Iustin Pop
            continue
1471 a8083063 Iustin Pop
          raise
1472 a8083063 Iustin Pop
    finally:
1473 a8083063 Iustin Pop
      # try not to leak fds
1474 a8083063 Iustin Pop
      for fd in (fdstdin, ):
1475 a8083063 Iustin Pop
        if fd is not None:
1476 a8083063 Iustin Pop
          try:
1477 a8083063 Iustin Pop
            fd.close()
1478 a8083063 Iustin Pop
          except EnvironmentError, err:
1479 a8083063 Iustin Pop
            # just log the error
1480 a8083063 Iustin Pop
            #logger.Error("While closing fd %s: %s" % (fd, err))
1481 a8083063 Iustin Pop
            pass
1482 a8083063 Iustin Pop
1483 a8083063 Iustin Pop
    return result == 0, output
1484 a8083063 Iustin Pop
1485 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
1486 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
1487 a8083063 Iustin Pop

1488 a8083063 Iustin Pop
    This method will not be usually overriden by child opcodes.
1489 a8083063 Iustin Pop

1490 a8083063 Iustin Pop
    """
1491 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
1492 a8083063 Iustin Pop
      suffix = "pre"
1493 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
1494 a8083063 Iustin Pop
      suffix = "post"
1495 a8083063 Iustin Pop
    else:
1496 3ecf6786 Iustin Pop
      raise errors.ProgrammerError("Unknown hooks phase: '%s'" % phase)
1497 a8083063 Iustin Pop
    rr = []
1498 a8083063 Iustin Pop
1499 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
1500 a8083063 Iustin Pop
    dir_name = "%s/%s" % (self._BASE_DIR, subdir)
1501 a8083063 Iustin Pop
    try:
1502 eedbda4b Michael Hanselmann
      dir_contents = utils.ListVisibleFiles(dir_name)
1503 a8083063 Iustin Pop
    except OSError, err:
1504 a8083063 Iustin Pop
      # must log
1505 a8083063 Iustin Pop
      return rr
1506 a8083063 Iustin Pop
1507 a8083063 Iustin Pop
    # we use the standard python sort order,
1508 a8083063 Iustin Pop
    # so 00name is the recommended naming scheme
1509 a8083063 Iustin Pop
    dir_contents.sort()
1510 a8083063 Iustin Pop
    for relname in dir_contents:
1511 a8083063 Iustin Pop
      fname = os.path.join(dir_name, relname)
1512 a8083063 Iustin Pop
      if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and
1513 a8083063 Iustin Pop
          self.RE_MASK.match(relname) is not None):
1514 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
1515 a8083063 Iustin Pop
        output = ""
1516 a8083063 Iustin Pop
      else:
1517 a8083063 Iustin Pop
        result, output = self.ExecHook(fname, env)
1518 a8083063 Iustin Pop
        if not result:
1519 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
1520 a8083063 Iustin Pop
        else:
1521 a8083063 Iustin Pop
          rrval = constants.HKR_SUCCESS
1522 a8083063 Iustin Pop
      rr.append(("%s/%s" % (subdir, relname), rrval, output))
1523 a8083063 Iustin Pop
1524 a8083063 Iustin Pop
    return rr
1525 3f78eef2 Iustin Pop
1526 3f78eef2 Iustin Pop
1527 3f78eef2 Iustin Pop
class DevCacheManager(object):
1528 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
1529 3f78eef2 Iustin Pop

1530 3f78eef2 Iustin Pop
  """
1531 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
1532 3f78eef2 Iustin Pop
  _ROOT_DIR = constants.BDEV_CACHE_DIR
1533 3f78eef2 Iustin Pop
1534 3f78eef2 Iustin Pop
  @classmethod
1535 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
1536 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
1537 3f78eef2 Iustin Pop

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

1541 3f78eef2 Iustin Pop
    """
1542 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
1543 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
1544 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
1545 3f78eef2 Iustin Pop
    fpath = "%s/bdev_%s" % (cls._ROOT_DIR, dev_path)
1546 3f78eef2 Iustin Pop
    return fpath
1547 3f78eef2 Iustin Pop
1548 3f78eef2 Iustin Pop
  @classmethod
1549 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
1550 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
1551 3f78eef2 Iustin Pop

1552 3f78eef2 Iustin Pop
    """
1553 cf5a8306 Iustin Pop
    if dev_path is None:
1554 cf5a8306 Iustin Pop
      logger.Error("DevCacheManager.UpdateCache got a None dev_path")
1555 cf5a8306 Iustin Pop
      return
1556 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
1557 3f78eef2 Iustin Pop
    if on_primary:
1558 3f78eef2 Iustin Pop
      state = "primary"
1559 3f78eef2 Iustin Pop
    else:
1560 3f78eef2 Iustin Pop
      state = "secondary"
1561 3f78eef2 Iustin Pop
    if iv_name is None:
1562 3f78eef2 Iustin Pop
      iv_name = "not_visible"
1563 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
1564 3f78eef2 Iustin Pop
    try:
1565 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
1566 3f78eef2 Iustin Pop
    except EnvironmentError, err:
1567 3f78eef2 Iustin Pop
      logger.Error("Can't update bdev cache for %s, error %s" %
1568 3f78eef2 Iustin Pop
                   (dev_path, str(err)))
1569 3f78eef2 Iustin Pop
1570 3f78eef2 Iustin Pop
  @classmethod
1571 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
1572 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
1573 3f78eef2 Iustin Pop

1574 3f78eef2 Iustin Pop
    """
1575 cf5a8306 Iustin Pop
    if dev_path is None:
1576 cf5a8306 Iustin Pop
      logger.Error("DevCacheManager.RemoveCache got a None dev_path")
1577 cf5a8306 Iustin Pop
      return
1578 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
1579 3f78eef2 Iustin Pop
    try:
1580 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
1581 3f78eef2 Iustin Pop
    except EnvironmentError, err:
1582 3f78eef2 Iustin Pop
      logger.Error("Can't update bdev cache for %s, error %s" %
1583 3f78eef2 Iustin Pop
                   (dev_path, str(err)))