Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 0006af7d

History | View | Annotate | Download (36.4 kB)

1 a8083063 Iustin Pop
#!/usr/bin/python
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 tempfile
30 a8083063 Iustin Pop
import stat
31 a8083063 Iustin Pop
import errno
32 a8083063 Iustin Pop
import re
33 a8083063 Iustin Pop
import subprocess
34 a8083063 Iustin Pop
35 a8083063 Iustin Pop
from ganeti import logger
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 a8083063 Iustin Pop
def StartMaster():
47 a8083063 Iustin Pop
  """Activate local node as master node.
48 a8083063 Iustin Pop

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

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

67 a8083063 Iustin Pop
  This does two things:
68 880478f8 Iustin Pop
    - run the master stop script
69 a8083063 Iustin Pop
    - remove link to master cron script.
70 a8083063 Iustin Pop

71 a8083063 Iustin Pop
  """
72 880478f8 Iustin Pop
  result = utils.RunCmd([constants.MASTER_SCRIPT, "-d", "stop"])
73 a8083063 Iustin Pop
74 a8083063 Iustin Pop
  if result.failed:
75 a8083063 Iustin Pop
    logger.Error("could not deactivate cluster interface with command %s,"
76 880478f8 Iustin Pop
                 " error: '%s'" % (result.cmd, result.output))
77 a8083063 Iustin Pop
    return False
78 a8083063 Iustin Pop
79 a8083063 Iustin Pop
  return True
80 a8083063 Iustin Pop
81 a8083063 Iustin Pop
82 a8083063 Iustin Pop
def AddNode(dsa, dsapub, rsa, rsapub, ssh, sshpub):
83 a8083063 Iustin Pop
  """ adds the node to the cluster
84 a8083063 Iustin Pop
      - updates the hostkey
85 a8083063 Iustin Pop
      - adds the ssh-key
86 a8083063 Iustin Pop
      - sets the node id
87 a8083063 Iustin Pop
      - sets the node status to installed
88 a8083063 Iustin Pop

89 098c0958 Michael Hanselmann
  """
90 a8083063 Iustin Pop
  f = open("/etc/ssh/ssh_host_rsa_key", 'w')
91 a8083063 Iustin Pop
  f.write(rsa)
92 a8083063 Iustin Pop
  f.close()
93 a8083063 Iustin Pop
94 a8083063 Iustin Pop
  f = open("/etc/ssh/ssh_host_rsa_key.pub", 'w')
95 a8083063 Iustin Pop
  f.write(rsapub)
96 a8083063 Iustin Pop
  f.close()
97 a8083063 Iustin Pop
98 a8083063 Iustin Pop
  f = open("/etc/ssh/ssh_host_dsa_key", 'w')
99 a8083063 Iustin Pop
  f.write(dsa)
100 a8083063 Iustin Pop
  f.close()
101 a8083063 Iustin Pop
102 a8083063 Iustin Pop
  f = open("/etc/ssh/ssh_host_dsa_key.pub", 'w')
103 a8083063 Iustin Pop
  f.write(dsapub)
104 a8083063 Iustin Pop
  f.close()
105 a8083063 Iustin Pop
106 a8083063 Iustin Pop
  if not os.path.isdir("/root/.ssh"):
107 a8083063 Iustin Pop
    os.mkdir("/root/.ssh")
108 a8083063 Iustin Pop
109 a8083063 Iustin Pop
  f = open("/root/.ssh/id_dsa", 'w')
110 a8083063 Iustin Pop
  f.write(ssh)
111 a8083063 Iustin Pop
  f.close()
112 a8083063 Iustin Pop
113 a8083063 Iustin Pop
  f = open("/root/.ssh/id_dsa.pub", 'w')
114 a8083063 Iustin Pop
  f.write(sshpub)
115 a8083063 Iustin Pop
  f.close()
116 a8083063 Iustin Pop
117 a8083063 Iustin Pop
  f = open('/root/.ssh/id_dsa.pub', 'r')
118 a8083063 Iustin Pop
  try:
119 a8083063 Iustin Pop
    utils.AddAuthorizedKey('/root/.ssh/authorized_keys', f.read(8192))
120 a8083063 Iustin Pop
  finally:
121 a8083063 Iustin Pop
    f.close()
122 a8083063 Iustin Pop
123 a8083063 Iustin Pop
  utils.RunCmd(["/etc/init.d/ssh", "restart"])
124 a8083063 Iustin Pop
125 a8083063 Iustin Pop
  utils.RemoveFile("/root/.ssh/known_hosts")
126 a8083063 Iustin Pop
  return True
127 a8083063 Iustin Pop
128 a8083063 Iustin Pop
129 a8083063 Iustin Pop
def LeaveCluster():
130 a8083063 Iustin Pop
  """Cleans up the current node and prepares it to be removed from the cluster.
131 a8083063 Iustin Pop

132 a8083063 Iustin Pop
  """
133 a8083063 Iustin Pop
  if os.path.exists(constants.DATA_DIR):
134 a8083063 Iustin Pop
    for dirpath, dirnames, filenames in os.walk(constants.DATA_DIR):
135 a8083063 Iustin Pop
      if dirpath == constants.DATA_DIR:
136 a8083063 Iustin Pop
        for i in filenames:
137 a8083063 Iustin Pop
          os.unlink(os.path.join(dirpath, i))
138 a8083063 Iustin Pop
139 a8083063 Iustin Pop
  f = open('/root/.ssh/id_dsa.pub', 'r')
140 a8083063 Iustin Pop
  try:
141 a8083063 Iustin Pop
    utils.RemoveAuthorizedKey('/root/.ssh/authorized_keys', f.read(8192))
142 a8083063 Iustin Pop
  finally:
143 a8083063 Iustin Pop
    f.close()
144 a8083063 Iustin Pop
145 a8083063 Iustin Pop
  utils.RemoveFile('/root/.ssh/id_dsa')
146 a8083063 Iustin Pop
  utils.RemoveFile('/root/.ssh/id_dsa.pub')
147 a8083063 Iustin Pop
148 a8083063 Iustin Pop
149 a8083063 Iustin Pop
def GetNodeInfo(vgname):
150 a8083063 Iustin Pop
  """ gives back a hash with different informations
151 a8083063 Iustin Pop
  about the node
152 a8083063 Iustin Pop

153 a8083063 Iustin Pop
  Returns:
154 a8083063 Iustin Pop
    { 'vg_size' : xxx,  'vg_free' : xxx, 'memory_domain0': xxx,
155 a8083063 Iustin Pop
      'memory_free' : xxx, 'memory_total' : xxx }
156 a8083063 Iustin Pop
    where
157 a8083063 Iustin Pop
    vg_size is the size of the configured volume group in MiB
158 a8083063 Iustin Pop
    vg_free is the free size of the volume group in MiB
159 a8083063 Iustin Pop
    memory_dom0 is the memory allocated for domain0 in MiB
160 a8083063 Iustin Pop
    memory_free is the currently available (free) ram in MiB
161 a8083063 Iustin Pop
    memory_total is the total number of ram in MiB
162 a8083063 Iustin Pop

163 098c0958 Michael Hanselmann
  """
164 a8083063 Iustin Pop
  outputarray = {}
165 a8083063 Iustin Pop
  vginfo = _GetVGInfo(vgname)
166 a8083063 Iustin Pop
  outputarray['vg_size'] = vginfo['vg_size']
167 a8083063 Iustin Pop
  outputarray['vg_free'] = vginfo['vg_free']
168 a8083063 Iustin Pop
169 a8083063 Iustin Pop
  hyper = hypervisor.GetHypervisor()
170 a8083063 Iustin Pop
  hyp_info = hyper.GetNodeInfo()
171 a8083063 Iustin Pop
  if hyp_info is not None:
172 a8083063 Iustin Pop
    outputarray.update(hyp_info)
173 a8083063 Iustin Pop
174 a8083063 Iustin Pop
  return outputarray
175 a8083063 Iustin Pop
176 a8083063 Iustin Pop
177 a8083063 Iustin Pop
def VerifyNode(what):
178 a8083063 Iustin Pop
  """Verify the status of the local node.
179 a8083063 Iustin Pop

180 a8083063 Iustin Pop
  Args:
181 a8083063 Iustin Pop
    what - a dictionary of things to check:
182 a8083063 Iustin Pop
      'filelist' : list of files for which to compute checksums
183 a8083063 Iustin Pop
      'nodelist' : list of nodes we should check communication with
184 a8083063 Iustin Pop
      'hypervisor': run the hypervisor-specific verify
185 a8083063 Iustin Pop

186 a8083063 Iustin Pop
  Requested files on local node are checksummed and the result returned.
187 a8083063 Iustin Pop

188 a8083063 Iustin Pop
  The nodelist is traversed, with the following checks being made
189 a8083063 Iustin Pop
  for each node:
190 a8083063 Iustin Pop
  - known_hosts key correct
191 a8083063 Iustin Pop
  - correct resolving of node name (target node returns its own hostname
192 a8083063 Iustin Pop
    by ssh-execution of 'hostname', result compared against name in list.
193 a8083063 Iustin Pop

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

215 a8083063 Iustin Pop
  Returns:
216 a8083063 Iustin Pop
    dictionary of all partions (key) with their size:
217 a8083063 Iustin Pop
    test1: 20.06MiB
218 a8083063 Iustin Pop

219 a8083063 Iustin Pop
  """
220 a8083063 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m",
221 a8083063 Iustin Pop
                         "-oname,size", vg_name])
222 a8083063 Iustin Pop
  if result.failed:
223 a8083063 Iustin Pop
    logger.Error("Failed to list logical volumes, lvs output: %s" %
224 a8083063 Iustin Pop
                 result.output)
225 a8083063 Iustin Pop
    return {}
226 a8083063 Iustin Pop
227 a8083063 Iustin Pop
  lvlist = [line.split() for line in result.output.splitlines()]
228 a8083063 Iustin Pop
  return dict(lvlist)
229 a8083063 Iustin Pop
230 a8083063 Iustin Pop
231 a8083063 Iustin Pop
def ListVolumeGroups():
232 a8083063 Iustin Pop
  """List the volume groups and their size
233 a8083063 Iustin Pop

234 a8083063 Iustin Pop
  Returns:
235 a8083063 Iustin Pop
    Dictionary with keys volume name and values the size of the volume
236 a8083063 Iustin Pop

237 a8083063 Iustin Pop
  """
238 a8083063 Iustin Pop
  return utils.ListVolumeGroups()
239 a8083063 Iustin Pop
240 a8083063 Iustin Pop
241 dcb93971 Michael Hanselmann
def NodeVolumes():
242 dcb93971 Michael Hanselmann
  """List all volumes on this node.
243 dcb93971 Michael Hanselmann

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

273 a8083063 Iustin Pop
  Returns:
274 a8083063 Iustin Pop
    True if all of them exist, false otherwise
275 a8083063 Iustin Pop

276 a8083063 Iustin Pop
  """
277 a8083063 Iustin Pop
  for bridge in bridges_list:
278 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
279 a8083063 Iustin Pop
      return False
280 a8083063 Iustin Pop
281 a8083063 Iustin Pop
  return True
282 a8083063 Iustin Pop
283 a8083063 Iustin Pop
284 a8083063 Iustin Pop
def GetInstanceList():
285 a8083063 Iustin Pop
  """ provides a list of instances
286 a8083063 Iustin Pop

287 a8083063 Iustin Pop
  Returns:
288 a8083063 Iustin Pop
    A list of all running instances on the current node
289 a8083063 Iustin Pop
    - instance1.example.com
290 a8083063 Iustin Pop
    - instance2.example.com
291 a8083063 Iustin Pop

292 098c0958 Michael Hanselmann
  """
293 a8083063 Iustin Pop
  try:
294 a8083063 Iustin Pop
    names = hypervisor.GetHypervisor().ListInstances()
295 a8083063 Iustin Pop
  except errors.HypervisorError, err:
296 a8083063 Iustin Pop
    logger.Error("error enumerating instances: %s" % str(err))
297 a8083063 Iustin Pop
    raise
298 a8083063 Iustin Pop
299 a8083063 Iustin Pop
  return names
300 a8083063 Iustin Pop
301 a8083063 Iustin Pop
302 a8083063 Iustin Pop
def GetInstanceInfo(instance):
303 a8083063 Iustin Pop
  """ gives back the informations about an instance
304 a8083063 Iustin Pop
  as a dictonary
305 a8083063 Iustin Pop

306 a8083063 Iustin Pop
  Args:
307 a8083063 Iustin Pop
    instance: name of the instance (ex. instance1.example.com)
308 a8083063 Iustin Pop

309 a8083063 Iustin Pop
  Returns:
310 a8083063 Iustin Pop
    { 'memory' : 511, 'state' : '-b---', 'time' : 3188.8, }
311 a8083063 Iustin Pop
    where
312 a8083063 Iustin Pop
    memory: memory size of instance (int)
313 a8083063 Iustin Pop
    state: xen state of instance (string)
314 a8083063 Iustin Pop
    time: cpu time of instance (float)
315 a8083063 Iustin Pop

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

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

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

344 098c0958 Michael Hanselmann
  """
345 a8083063 Iustin Pop
  output = {}
346 a8083063 Iustin Pop
347 a8083063 Iustin Pop
  iinfo = hypervisor.GetHypervisor().GetAllInstancesInfo()
348 a8083063 Iustin Pop
  if iinfo:
349 a8083063 Iustin Pop
    for name, id, memory, vcpus, state, times in iinfo:
350 a8083063 Iustin Pop
      output[name] = {
351 a8083063 Iustin Pop
        'memory': memory,
352 a8083063 Iustin Pop
        'vcpus': vcpus,
353 a8083063 Iustin Pop
        'state': state,
354 a8083063 Iustin Pop
        'time': times,
355 a8083063 Iustin Pop
        }
356 a8083063 Iustin Pop
357 a8083063 Iustin Pop
  return output
358 a8083063 Iustin Pop
359 a8083063 Iustin Pop
360 a8083063 Iustin Pop
def AddOSToInstance(instance, os_disk, swap_disk):
361 a8083063 Iustin Pop
  """Add an os to an instance.
362 a8083063 Iustin Pop

363 a8083063 Iustin Pop
  Args:
364 a8083063 Iustin Pop
    instance: the instance object
365 a8083063 Iustin Pop
    os_disk: the instance-visible name of the os device
366 a8083063 Iustin Pop
    swap_disk: the instance-visible name of the swap device
367 a8083063 Iustin Pop

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

423 a8083063 Iustin Pop
  Args:
424 a8083063 Iustin Pop
    vg_name: the volume group
425 a8083063 Iustin Pop

426 a8083063 Iustin Pop
  Returns:
427 a8083063 Iustin Pop
    { 'vg_size' : xxx, 'vg_free' : xxx, 'pv_count' : xxx }
428 a8083063 Iustin Pop
    where
429 a8083063 Iustin Pop
    vg_size is the total size of the volume group in MiB
430 a8083063 Iustin Pop
    vg_free is the free size of the volume group in MiB
431 a8083063 Iustin Pop
    pv_count are the number of physical disks in that vg
432 a8083063 Iustin Pop

433 a8083063 Iustin Pop
  """
434 a8083063 Iustin Pop
  retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings",
435 a8083063 Iustin Pop
                         "--nosuffix", "--units=m", "--separator=:", vg_name])
436 a8083063 Iustin Pop
437 a8083063 Iustin Pop
  if retval.failed:
438 a8083063 Iustin Pop
    errmsg = "volume group %s not present" % vg_name
439 a8083063 Iustin Pop
    logger.Error(errmsg)
440 a8083063 Iustin Pop
    raise errors.LVMError(errmsg)
441 a8083063 Iustin Pop
  valarr = retval.stdout.strip().split(':')
442 a8083063 Iustin Pop
  retdic = {
443 a8083063 Iustin Pop
    "vg_size": int(round(float(valarr[0]), 0)),
444 a8083063 Iustin Pop
    "vg_free": int(round(float(valarr[1]), 0)),
445 a8083063 Iustin Pop
    "pv_count": int(valarr[2]),
446 a8083063 Iustin Pop
    }
447 a8083063 Iustin Pop
  return retdic
448 a8083063 Iustin Pop
449 a8083063 Iustin Pop
450 a8083063 Iustin Pop
def _GatherBlockDevs(instance):
451 a8083063 Iustin Pop
  """Set up an instance's block device(s).
452 a8083063 Iustin Pop

453 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
454 a8083063 Iustin Pop
  devices must be already assembled.
455 a8083063 Iustin Pop

456 a8083063 Iustin Pop
  """
457 a8083063 Iustin Pop
  block_devices = []
458 a8083063 Iustin Pop
  for disk in instance.disks:
459 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
460 a8083063 Iustin Pop
    if device is None:
461 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
462 a8083063 Iustin Pop
                                    str(disk))
463 a8083063 Iustin Pop
    device.Open()
464 a8083063 Iustin Pop
    block_devices.append((disk, device))
465 a8083063 Iustin Pop
  return block_devices
466 a8083063 Iustin Pop
467 a8083063 Iustin Pop
468 a8083063 Iustin Pop
def StartInstance(instance, extra_args):
469 a8083063 Iustin Pop
  """Start an instance.
470 a8083063 Iustin Pop

471 a8083063 Iustin Pop
  Args:
472 a8083063 Iustin Pop
    instance - name of instance to start.
473 a8083063 Iustin Pop

474 098c0958 Michael Hanselmann
  """
475 a8083063 Iustin Pop
  running_instances = GetInstanceList()
476 a8083063 Iustin Pop
477 a8083063 Iustin Pop
  if instance.name in running_instances:
478 a8083063 Iustin Pop
    return True
479 a8083063 Iustin Pop
480 a8083063 Iustin Pop
  block_devices = _GatherBlockDevs(instance)
481 a8083063 Iustin Pop
  hyper = hypervisor.GetHypervisor()
482 a8083063 Iustin Pop
483 a8083063 Iustin Pop
  try:
484 a8083063 Iustin Pop
    hyper.StartInstance(instance, block_devices, extra_args)
485 a8083063 Iustin Pop
  except errors.HypervisorError, err:
486 a8083063 Iustin Pop
    logger.Error("Failed to start instance: %s" % err)
487 a8083063 Iustin Pop
    return False
488 a8083063 Iustin Pop
489 a8083063 Iustin Pop
  return True
490 a8083063 Iustin Pop
491 a8083063 Iustin Pop
492 a8083063 Iustin Pop
def ShutdownInstance(instance):
493 a8083063 Iustin Pop
  """Shut an instance down.
494 a8083063 Iustin Pop

495 a8083063 Iustin Pop
  Args:
496 a8083063 Iustin Pop
    instance - name of instance to shutdown.
497 a8083063 Iustin Pop

498 098c0958 Michael Hanselmann
  """
499 a8083063 Iustin Pop
  running_instances = GetInstanceList()
500 a8083063 Iustin Pop
501 a8083063 Iustin Pop
  if instance.name not in running_instances:
502 a8083063 Iustin Pop
    return True
503 a8083063 Iustin Pop
504 a8083063 Iustin Pop
  hyper = hypervisor.GetHypervisor()
505 a8083063 Iustin Pop
  try:
506 a8083063 Iustin Pop
    hyper.StopInstance(instance)
507 a8083063 Iustin Pop
  except errors.HypervisorError, err:
508 a8083063 Iustin Pop
    logger.Error("Failed to stop instance: %s" % err)
509 a8083063 Iustin Pop
    return False
510 a8083063 Iustin Pop
511 a8083063 Iustin Pop
  # test every 10secs for 2min
512 a8083063 Iustin Pop
  shutdown_ok = False
513 a8083063 Iustin Pop
514 a8083063 Iustin Pop
  time.sleep(1)
515 a8083063 Iustin Pop
  for dummy in range(11):
516 a8083063 Iustin Pop
    if instance.name not in GetInstanceList():
517 a8083063 Iustin Pop
      break
518 a8083063 Iustin Pop
    time.sleep(10)
519 a8083063 Iustin Pop
  else:
520 a8083063 Iustin Pop
    # the shutdown did not succeed
521 a8083063 Iustin Pop
    logger.Error("shutdown of '%s' unsuccessful, using destroy" % instance)
522 a8083063 Iustin Pop
523 a8083063 Iustin Pop
    try:
524 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
525 a8083063 Iustin Pop
    except errors.HypervisorError, err:
526 a8083063 Iustin Pop
      logger.Error("Failed to stop instance: %s" % err)
527 a8083063 Iustin Pop
      return False
528 a8083063 Iustin Pop
529 a8083063 Iustin Pop
    time.sleep(1)
530 a8083063 Iustin Pop
    if instance.name in GetInstanceList():
531 a8083063 Iustin Pop
      logger.Error("could not shutdown instance '%s' even by destroy")
532 a8083063 Iustin Pop
      return False
533 a8083063 Iustin Pop
534 a8083063 Iustin Pop
  return True
535 a8083063 Iustin Pop
536 a8083063 Iustin Pop
537 a8083063 Iustin Pop
def CreateBlockDevice(disk, size, on_primary):
538 a8083063 Iustin Pop
  """Creates a block device for an instance.
539 a8083063 Iustin Pop

540 a8083063 Iustin Pop
  Args:
541 a8083063 Iustin Pop
   bdev: a ganeti.objects.Disk object
542 a8083063 Iustin Pop
   size: the size of the physical underlying devices
543 a8083063 Iustin Pop
   do_open: if the device should be `Assemble()`-d and
544 a8083063 Iustin Pop
            `Open()`-ed after creation
545 a8083063 Iustin Pop

546 a8083063 Iustin Pop
  Returns:
547 a8083063 Iustin Pop
    the new unique_id of the device (this can sometime be
548 a8083063 Iustin Pop
    computed only after creation), or None. On secondary nodes,
549 a8083063 Iustin Pop
    it's not required to return anything.
550 a8083063 Iustin Pop

551 a8083063 Iustin Pop
  """
552 a8083063 Iustin Pop
  clist = []
553 a8083063 Iustin Pop
  if disk.children:
554 a8083063 Iustin Pop
    for child in disk.children:
555 a8083063 Iustin Pop
      crdev = _RecursiveAssembleBD(child, on_primary)
556 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
557 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
558 a8083063 Iustin Pop
        # be assembled
559 a8083063 Iustin Pop
        crdev.Open()
560 a8083063 Iustin Pop
      else:
561 a8083063 Iustin Pop
        crdev.Close()
562 a8083063 Iustin Pop
      clist.append(crdev)
563 a8083063 Iustin Pop
  try:
564 a8083063 Iustin Pop
    device = bdev.FindDevice(disk.dev_type, disk.physical_id, clist)
565 a8083063 Iustin Pop
    if device is not None:
566 a8083063 Iustin Pop
      logger.Info("removing existing device %s" % disk)
567 a8083063 Iustin Pop
      device.Remove()
568 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
569 a8083063 Iustin Pop
    pass
570 a8083063 Iustin Pop
571 a8083063 Iustin Pop
  device = bdev.Create(disk.dev_type, disk.physical_id,
572 a8083063 Iustin Pop
                       clist, size)
573 a8083063 Iustin Pop
  if device is None:
574 a8083063 Iustin Pop
    raise ValueError("Can't create child device for %s, %s" %
575 a8083063 Iustin Pop
                     (disk, size))
576 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
577 a8083063 Iustin Pop
    device.Assemble()
578 a8083063 Iustin Pop
    device.SetSyncSpeed(30*1024)
579 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
580 a8083063 Iustin Pop
      device.Open(force=True)
581 a8083063 Iustin Pop
  physical_id = device.unique_id
582 a8083063 Iustin Pop
  return physical_id
583 a8083063 Iustin Pop
584 a8083063 Iustin Pop
585 a8083063 Iustin Pop
def RemoveBlockDevice(disk):
586 a8083063 Iustin Pop
  """Remove a block device.
587 a8083063 Iustin Pop

588 a8083063 Iustin Pop
  This is intended to be called recursively.
589 a8083063 Iustin Pop

590 a8083063 Iustin Pop
  """
591 a8083063 Iustin Pop
  try:
592 a8083063 Iustin Pop
    # since we are removing the device, allow a partial match
593 a8083063 Iustin Pop
    # this allows removal of broken mirrors
594 a8083063 Iustin Pop
    rdev = _RecursiveFindBD(disk, allow_partial=True)
595 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
596 a8083063 Iustin Pop
    # probably can't attach
597 a8083063 Iustin Pop
    logger.Info("Can't attach to device %s in remove" % disk)
598 a8083063 Iustin Pop
    rdev = None
599 a8083063 Iustin Pop
  if rdev is not None:
600 a8083063 Iustin Pop
    result = rdev.Remove()
601 a8083063 Iustin Pop
  else:
602 a8083063 Iustin Pop
    result = True
603 a8083063 Iustin Pop
  if disk.children:
604 a8083063 Iustin Pop
    for child in disk.children:
605 a8083063 Iustin Pop
      result = result and RemoveBlockDevice(child)
606 a8083063 Iustin Pop
  return result
607 a8083063 Iustin Pop
608 a8083063 Iustin Pop
609 a8083063 Iustin Pop
def _RecursiveAssembleBD(disk, as_primary):
610 a8083063 Iustin Pop
  """Activate a block device for an instance.
611 a8083063 Iustin Pop

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

614 a8083063 Iustin Pop
  This function is called recursively.
615 a8083063 Iustin Pop

616 a8083063 Iustin Pop
  Args:
617 a8083063 Iustin Pop
    disk: a objects.Disk object
618 a8083063 Iustin Pop
    as_primary: if we should make the block device read/write
619 a8083063 Iustin Pop

620 a8083063 Iustin Pop
  Returns:
621 a8083063 Iustin Pop
    the assembled device or None (in case no device was assembled)
622 a8083063 Iustin Pop

623 a8083063 Iustin Pop
  If the assembly is not successful, an exception is raised.
624 a8083063 Iustin Pop

625 a8083063 Iustin Pop
  """
626 a8083063 Iustin Pop
  children = []
627 a8083063 Iustin Pop
  if disk.children:
628 a8083063 Iustin Pop
    for chld_disk in disk.children:
629 a8083063 Iustin Pop
      children.append(_RecursiveAssembleBD(chld_disk, as_primary))
630 a8083063 Iustin Pop
631 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
632 a8083063 Iustin Pop
    r_dev = bdev.AttachOrAssemble(disk.dev_type, disk.physical_id, children)
633 a8083063 Iustin Pop
    r_dev.SetSyncSpeed(30*1024)
634 a8083063 Iustin Pop
    result = r_dev
635 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
636 a8083063 Iustin Pop
      r_dev.Open()
637 a8083063 Iustin Pop
    else:
638 a8083063 Iustin Pop
      r_dev.Close()
639 a8083063 Iustin Pop
  else:
640 a8083063 Iustin Pop
    result = True
641 a8083063 Iustin Pop
  return result
642 a8083063 Iustin Pop
643 a8083063 Iustin Pop
644 a8083063 Iustin Pop
def AssembleBlockDevice(disk, as_primary):
645 a8083063 Iustin Pop
  """Activate a block device for an instance.
646 a8083063 Iustin Pop

647 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
648 a8083063 Iustin Pop

649 a8083063 Iustin Pop
  Returns:
650 a8083063 Iustin Pop
    a /dev path for primary nodes
651 a8083063 Iustin Pop
    True for secondary nodes
652 a8083063 Iustin Pop

653 a8083063 Iustin Pop
  """
654 a8083063 Iustin Pop
  result = _RecursiveAssembleBD(disk, as_primary)
655 a8083063 Iustin Pop
  if isinstance(result, bdev.BlockDev):
656 a8083063 Iustin Pop
    result = result.dev_path
657 a8083063 Iustin Pop
  return result
658 a8083063 Iustin Pop
659 a8083063 Iustin Pop
660 a8083063 Iustin Pop
def ShutdownBlockDevice(disk):
661 a8083063 Iustin Pop
  """Shut down a block device.
662 a8083063 Iustin Pop

663 a8083063 Iustin Pop
  First, if the device is assembled (can `Attach()`), then the device
664 a8083063 Iustin Pop
  is shutdown. Then the children of the device are shutdown.
665 a8083063 Iustin Pop

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

670 a8083063 Iustin Pop
  """
671 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
672 a8083063 Iustin Pop
  if r_dev is not None:
673 a8083063 Iustin Pop
    result = r_dev.Shutdown()
674 a8083063 Iustin Pop
  else:
675 a8083063 Iustin Pop
    result = True
676 a8083063 Iustin Pop
  if disk.children:
677 a8083063 Iustin Pop
    for child in disk.children:
678 a8083063 Iustin Pop
      result = result and ShutdownBlockDevice(child)
679 a8083063 Iustin Pop
  return result
680 a8083063 Iustin Pop
681 a8083063 Iustin Pop
682 a8083063 Iustin Pop
def MirrorAddChild(md_cdev, new_cdev):
683 a8083063 Iustin Pop
  """Extend an MD raid1 array.
684 a8083063 Iustin Pop

685 a8083063 Iustin Pop
  """
686 a8083063 Iustin Pop
  md_bdev = _RecursiveFindBD(md_cdev, allow_partial=True)
687 a8083063 Iustin Pop
  if md_bdev is None:
688 a8083063 Iustin Pop
    logger.Error("Can't find md device")
689 a8083063 Iustin Pop
    return False
690 a8083063 Iustin Pop
  new_bdev = _RecursiveFindBD(new_cdev)
691 a8083063 Iustin Pop
  if new_bdev is None:
692 a8083063 Iustin Pop
    logger.Error("Can't find new device to add")
693 a8083063 Iustin Pop
    return False
694 a8083063 Iustin Pop
  new_bdev.Open()
695 a8083063 Iustin Pop
  md_bdev.AddChild(new_bdev)
696 a8083063 Iustin Pop
  return True
697 a8083063 Iustin Pop
698 a8083063 Iustin Pop
699 a8083063 Iustin Pop
def MirrorRemoveChild(md_cdev, new_cdev):
700 a8083063 Iustin Pop
  """Reduce an MD raid1 array.
701 a8083063 Iustin Pop

702 a8083063 Iustin Pop
  """
703 a8083063 Iustin Pop
  md_bdev = _RecursiveFindBD(md_cdev)
704 a8083063 Iustin Pop
  if md_bdev is None:
705 a8083063 Iustin Pop
    return False
706 a8083063 Iustin Pop
  new_bdev = _RecursiveFindBD(new_cdev)
707 a8083063 Iustin Pop
  if new_bdev is None:
708 a8083063 Iustin Pop
    return False
709 a8083063 Iustin Pop
  new_bdev.Open()
710 a8083063 Iustin Pop
  md_bdev.RemoveChild(new_bdev.dev_path)
711 a8083063 Iustin Pop
  return True
712 a8083063 Iustin Pop
713 a8083063 Iustin Pop
714 a8083063 Iustin Pop
def GetMirrorStatus(disks):
715 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
716 a8083063 Iustin Pop

717 a8083063 Iustin Pop
  Args:
718 a8083063 Iustin Pop
    disks: list of `objects.Disk`
719 a8083063 Iustin Pop

720 a8083063 Iustin Pop
  Returns:
721 a8083063 Iustin Pop
    list of (mirror_done, estimated_time) tuples, which
722 a8083063 Iustin Pop
    are the result of bdev.BlockDevice.CombinedSyncStatus()
723 a8083063 Iustin Pop

724 a8083063 Iustin Pop
  """
725 a8083063 Iustin Pop
  stats = []
726 a8083063 Iustin Pop
  for dsk in disks:
727 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
728 a8083063 Iustin Pop
    if rbd is None:
729 a8083063 Iustin Pop
      raise errors.BlockDeviceError, "Can't find device %s" % str(dsk)
730 a8083063 Iustin Pop
    stats.append(rbd.CombinedSyncStatus())
731 a8083063 Iustin Pop
  return stats
732 a8083063 Iustin Pop
733 a8083063 Iustin Pop
734 a8083063 Iustin Pop
def _RecursiveFindBD(disk, allow_partial=False):
735 a8083063 Iustin Pop
  """Check if a device is activated.
736 a8083063 Iustin Pop

737 a8083063 Iustin Pop
  If so, return informations about the real device.
738 a8083063 Iustin Pop

739 a8083063 Iustin Pop
  Args:
740 a8083063 Iustin Pop
    disk: the objects.Disk instance
741 a8083063 Iustin Pop
    allow_partial: don't abort the find if a child of the
742 a8083063 Iustin Pop
                   device can't be found; this is intended to be
743 a8083063 Iustin Pop
                   used when repairing mirrors
744 a8083063 Iustin Pop

745 a8083063 Iustin Pop
  Returns:
746 a8083063 Iustin Pop
    None if the device can't be found
747 a8083063 Iustin Pop
    otherwise the device instance
748 a8083063 Iustin Pop

749 a8083063 Iustin Pop
  """
750 a8083063 Iustin Pop
  children = []
751 a8083063 Iustin Pop
  if disk.children:
752 a8083063 Iustin Pop
    for chdisk in disk.children:
753 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
754 a8083063 Iustin Pop
755 a8083063 Iustin Pop
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children)
756 a8083063 Iustin Pop
757 a8083063 Iustin Pop
758 a8083063 Iustin Pop
def FindBlockDevice(disk):
759 a8083063 Iustin Pop
  """Check if a device is activated.
760 a8083063 Iustin Pop

761 a8083063 Iustin Pop
  If so, return informations about the real device.
762 a8083063 Iustin Pop

763 a8083063 Iustin Pop
  Args:
764 a8083063 Iustin Pop
    disk: the objects.Disk instance
765 a8083063 Iustin Pop
  Returns:
766 a8083063 Iustin Pop
    None if the device can't be found
767 a8083063 Iustin Pop
    (device_path, major, minor, sync_percent, estimated_time, is_degraded)
768 a8083063 Iustin Pop

769 a8083063 Iustin Pop
  """
770 a8083063 Iustin Pop
  rbd = _RecursiveFindBD(disk)
771 a8083063 Iustin Pop
  if rbd is None:
772 a8083063 Iustin Pop
    return rbd
773 a8083063 Iustin Pop
  sync_p, est_t, is_degr = rbd.GetSyncStatus()
774 a8083063 Iustin Pop
  return rbd.dev_path, rbd.major, rbd.minor, sync_p, est_t, is_degr
775 a8083063 Iustin Pop
776 a8083063 Iustin Pop
777 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
778 a8083063 Iustin Pop
  """Write a file to the filesystem.
779 a8083063 Iustin Pop

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

783 a8083063 Iustin Pop
  """
784 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
785 a8083063 Iustin Pop
    logger.Error("Filename passed to UploadFile is not absolute: '%s'" %
786 a8083063 Iustin Pop
                 file_name)
787 a8083063 Iustin Pop
    return False
788 a8083063 Iustin Pop
789 880478f8 Iustin Pop
  allowed_files = [constants.CLUSTER_CONF_FILE, "/etc/hosts",
790 880478f8 Iustin Pop
                   "/etc/ssh/ssh_known_hosts"]
791 880478f8 Iustin Pop
  allowed_files.extend(ssconf.SimpleStore().GetFileList())
792 880478f8 Iustin Pop
  if file_name not in allowed_files:
793 a8083063 Iustin Pop
    logger.Error("Filename passed to UploadFile not in allowed"
794 a8083063 Iustin Pop
                 " upload targets: '%s'" % file_name)
795 a8083063 Iustin Pop
    return False
796 a8083063 Iustin Pop
797 a8083063 Iustin Pop
  dir_name, small_name = os.path.split(file_name)
798 a8083063 Iustin Pop
  fd, new_name = tempfile.mkstemp('.new', small_name, dir_name)
799 a8083063 Iustin Pop
  # here we need to make sure we remove the temp file, if any error
800 a8083063 Iustin Pop
  # leaves it in place
801 a8083063 Iustin Pop
  try:
802 a8083063 Iustin Pop
    os.chown(new_name, uid, gid)
803 a8083063 Iustin Pop
    os.chmod(new_name, mode)
804 a8083063 Iustin Pop
    os.write(fd, data)
805 a8083063 Iustin Pop
    os.fsync(fd)
806 a8083063 Iustin Pop
    os.utime(new_name, (atime, mtime))
807 a8083063 Iustin Pop
    os.rename(new_name, file_name)
808 a8083063 Iustin Pop
  finally:
809 a8083063 Iustin Pop
    os.close(fd)
810 a8083063 Iustin Pop
    utils.RemoveFile(new_name)
811 a8083063 Iustin Pop
  return True
812 a8083063 Iustin Pop
813 a8083063 Iustin Pop
def _ErrnoOrStr(err):
814 a8083063 Iustin Pop
  """Format an EnvironmentError exception.
815 a8083063 Iustin Pop

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

820 a8083063 Iustin Pop
  """
821 a8083063 Iustin Pop
  if hasattr(err, 'errno'):
822 a8083063 Iustin Pop
    detail = errno.errorcode[err.errno]
823 a8083063 Iustin Pop
  else:
824 a8083063 Iustin Pop
    detail = str(err)
825 a8083063 Iustin Pop
  return detail
826 a8083063 Iustin Pop
827 a8083063 Iustin Pop
828 a8083063 Iustin Pop
def _OSOndiskVersion(name, os_dir=None):
829 a8083063 Iustin Pop
  """Compute and return the api version of a given OS.
830 a8083063 Iustin Pop

831 a8083063 Iustin Pop
  This function will try to read the api version of the os given by
832 a8083063 Iustin Pop
  the 'name' parameter. By default, it wil use the constants.OS_DIR
833 a8083063 Iustin Pop
  as top-level directory for OSes, but this can be overriden by the
834 a8083063 Iustin Pop
  use of the os_dir parameter. Return value will be either an
835 a8083063 Iustin Pop
  integer denoting the version or None in the case when this is not
836 a8083063 Iustin Pop
  a valid OS name.
837 a8083063 Iustin Pop

838 a8083063 Iustin Pop
  """
839 a8083063 Iustin Pop
  if os_dir is None:
840 a8083063 Iustin Pop
    os_dir = os.path.sep.join([constants.OS_DIR, name])
841 a8083063 Iustin Pop
842 a8083063 Iustin Pop
  api_file = os.path.sep.join([os_dir, "ganeti_api_version"])
843 a8083063 Iustin Pop
844 a8083063 Iustin Pop
  try:
845 a8083063 Iustin Pop
    st = os.stat(api_file)
846 a8083063 Iustin Pop
  except EnvironmentError, err:
847 a8083063 Iustin Pop
    raise errors.InvalidOS, (name, "'ganeti_api_version' file not"
848 a8083063 Iustin Pop
                             " found (%s)" % _ErrnoOrStr(err))
849 a8083063 Iustin Pop
850 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
851 a8083063 Iustin Pop
    raise errors.InvalidOS, (name, "'ganeti_api_version' file is not"
852 a8083063 Iustin Pop
                             " a regular file")
853 a8083063 Iustin Pop
854 a8083063 Iustin Pop
  try:
855 a8083063 Iustin Pop
    f = open(api_file)
856 a8083063 Iustin Pop
    try:
857 a8083063 Iustin Pop
      api_version = f.read(256)
858 a8083063 Iustin Pop
    finally:
859 a8083063 Iustin Pop
      f.close()
860 a8083063 Iustin Pop
  except EnvironmentError, err:
861 a8083063 Iustin Pop
    raise errors.InvalidOS, (name, "error while reading the"
862 a8083063 Iustin Pop
                             " API version (%s)" % _ErrnoOrStr(err))
863 a8083063 Iustin Pop
864 a8083063 Iustin Pop
  api_version = api_version.strip()
865 a8083063 Iustin Pop
  try:
866 a8083063 Iustin Pop
    api_version = int(api_version)
867 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
868 a8083063 Iustin Pop
    raise errors.InvalidOS, (name, "API version is not integer (%s)" %
869 a8083063 Iustin Pop
                             str(err))
870 a8083063 Iustin Pop
871 a8083063 Iustin Pop
  return api_version
872 a8083063 Iustin Pop
873 a8083063 Iustin Pop
def DiagnoseOS(top_dir=None):
874 a8083063 Iustin Pop
  """Compute the validity for all OSes.
875 a8083063 Iustin Pop

876 a8083063 Iustin Pop
  For each name in the give top_dir parameter (if not given, defaults
877 a8083063 Iustin Pop
  to constants.OS_DIR), it will return an object. If this is a valid
878 a8083063 Iustin Pop
  os, the object will be an instance of the object.OS class. If not,
879 a8083063 Iustin Pop
  it will be an instance of errors.InvalidOS and this signifies that
880 a8083063 Iustin Pop
  this name does not correspond to a valid OS.
881 a8083063 Iustin Pop

882 a8083063 Iustin Pop
  Returns:
883 a8083063 Iustin Pop
    list of objects
884 a8083063 Iustin Pop

885 a8083063 Iustin Pop
  """
886 a8083063 Iustin Pop
  if top_dir is None:
887 a8083063 Iustin Pop
    top_dir = constants.OS_DIR
888 a8083063 Iustin Pop
889 a8083063 Iustin Pop
  try:
890 a8083063 Iustin Pop
    f_names = os.listdir(top_dir)
891 a8083063 Iustin Pop
  except EnvironmentError, err:
892 a8083063 Iustin Pop
    logger.Error("Can't list the OS directory: %s" % str(err))
893 a8083063 Iustin Pop
    return False
894 a8083063 Iustin Pop
  result = []
895 a8083063 Iustin Pop
  for name in f_names:
896 a8083063 Iustin Pop
    try:
897 a8083063 Iustin Pop
      os_inst = OSFromDisk(name, os.path.sep.join([top_dir, name]))
898 a8083063 Iustin Pop
      result.append(os_inst)
899 a8083063 Iustin Pop
    except errors.InvalidOS, err:
900 a8083063 Iustin Pop
      result.append(err)
901 a8083063 Iustin Pop
902 a8083063 Iustin Pop
  return result
903 a8083063 Iustin Pop
904 a8083063 Iustin Pop
905 a8083063 Iustin Pop
def OSFromDisk(name, os_dir=None):
906 a8083063 Iustin Pop
  """Create an OS instance from disk.
907 a8083063 Iustin Pop

908 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
909 a8083063 Iustin Pop
  valid OS name. Otherwise, it will raise an appropriate
910 a8083063 Iustin Pop
  `errors.InvalidOS` exception, detailing why this is not a valid
911 a8083063 Iustin Pop
  OS.
912 a8083063 Iustin Pop

913 a8083063 Iustin Pop
  """
914 a8083063 Iustin Pop
  if os_dir is None:
915 a8083063 Iustin Pop
    os_dir = os.path.sep.join([constants.OS_DIR, name])
916 a8083063 Iustin Pop
917 a8083063 Iustin Pop
  api_version = _OSOndiskVersion(name, os_dir)
918 a8083063 Iustin Pop
919 a8083063 Iustin Pop
  if api_version != constants.OS_API_VERSION:
920 a8083063 Iustin Pop
    raise errors.InvalidOS, (name, "API version mismatch (found %s want %s)"
921 a8083063 Iustin Pop
                             % (api_version, constants.OS_API_VERSION))
922 a8083063 Iustin Pop
923 a8083063 Iustin Pop
  # OS Scripts dictionary, we will populate it with the actual script names
924 a8083063 Iustin Pop
  os_scripts = {'create': '', 'export': '', 'import': ''}
925 a8083063 Iustin Pop
926 a8083063 Iustin Pop
  for script in os_scripts:
927 a8083063 Iustin Pop
    os_scripts[script] = os.path.sep.join([os_dir, script])
928 a8083063 Iustin Pop
929 a8083063 Iustin Pop
    try:
930 a8083063 Iustin Pop
      st = os.stat(os_scripts[script])
931 a8083063 Iustin Pop
    except EnvironmentError, err:
932 a8083063 Iustin Pop
      raise errors.InvalidOS, (name, "'%s' script missing (%s)" %
933 a8083063 Iustin Pop
                               (script, _ErrnoOrStr(err)))
934 a8083063 Iustin Pop
935 a8083063 Iustin Pop
    if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
936 a8083063 Iustin Pop
      raise errors.InvalidOS, (name, "'%s' script not executable" % script)
937 a8083063 Iustin Pop
938 a8083063 Iustin Pop
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
939 a8083063 Iustin Pop
      raise errors.InvalidOS, (name, "'%s' is not a regular file" % script)
940 a8083063 Iustin Pop
941 a8083063 Iustin Pop
942 a8083063 Iustin Pop
  return objects.OS(name=name, path=os_dir,
943 a8083063 Iustin Pop
                    create_script=os_scripts['create'],
944 a8083063 Iustin Pop
                    export_script=os_scripts['export'],
945 a8083063 Iustin Pop
                    import_script=os_scripts['import'],
946 a8083063 Iustin Pop
                    api_version=api_version)
947 a8083063 Iustin Pop
948 a8083063 Iustin Pop
949 a8083063 Iustin Pop
def SnapshotBlockDevice(disk):
950 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
951 a8083063 Iustin Pop

952 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
953 a8083063 Iustin Pop
  just for the leaf lvm backend device.
954 a8083063 Iustin Pop

955 a8083063 Iustin Pop
  Args:
956 a8083063 Iustin Pop
    disk: the disk to be snapshotted
957 a8083063 Iustin Pop

958 a8083063 Iustin Pop
  Returns:
959 a8083063 Iustin Pop
    a config entry for the actual lvm device snapshotted.
960 a8083063 Iustin Pop

961 098c0958 Michael Hanselmann
  """
962 a8083063 Iustin Pop
  if disk.children:
963 a8083063 Iustin Pop
    if len(disk.children) == 1:
964 a8083063 Iustin Pop
      # only one child, let's recurse on it
965 a8083063 Iustin Pop
      return SnapshotBlockDevice(disk.children[0])
966 a8083063 Iustin Pop
    else:
967 a8083063 Iustin Pop
      # more than one child, choose one that matches
968 a8083063 Iustin Pop
      for child in disk.children:
969 a8083063 Iustin Pop
        if child.size == disk.size:
970 a8083063 Iustin Pop
          # return implies breaking the loop
971 a8083063 Iustin Pop
          return SnapshotBlockDevice(child)
972 a8083063 Iustin Pop
  elif disk.dev_type == "lvm":
973 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
974 a8083063 Iustin Pop
    if r_dev is not None:
975 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
976 a8083063 Iustin Pop
      return r_dev.Snapshot(disk.size)
977 a8083063 Iustin Pop
    else:
978 a8083063 Iustin Pop
      return None
979 a8083063 Iustin Pop
  else:
980 a8083063 Iustin Pop
    raise errors.ProgrammerError, ("Cannot snapshot non-lvm block device"
981 a8083063 Iustin Pop
                                   "'%s' of type '%s'" %
982 a8083063 Iustin Pop
                                   (disk.unique_id, disk.dev_type))
983 a8083063 Iustin Pop
984 a8083063 Iustin Pop
985 a8083063 Iustin Pop
def ExportSnapshot(disk, dest_node, instance):
986 a8083063 Iustin Pop
  """Export a block device snapshot to a remote node.
987 a8083063 Iustin Pop

988 a8083063 Iustin Pop
  Args:
989 a8083063 Iustin Pop
    disk: the snapshot block device
990 a8083063 Iustin Pop
    dest_node: the node to send the image to
991 a8083063 Iustin Pop
    instance: instance being exported
992 a8083063 Iustin Pop

993 a8083063 Iustin Pop
  Returns:
994 a8083063 Iustin Pop
    True if successful, False otherwise.
995 a8083063 Iustin Pop

996 098c0958 Michael Hanselmann
  """
997 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
998 a8083063 Iustin Pop
  export_script = inst_os.export_script
999 a8083063 Iustin Pop
1000 a8083063 Iustin Pop
  logfile = "%s/exp-%s-%s-%s.log" % (constants.LOG_OS_DIR, inst_os.name,
1001 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
1002 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
1003 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
1004 a8083063 Iustin Pop
1005 a8083063 Iustin Pop
  real_os_dev = _RecursiveFindBD(disk)
1006 a8083063 Iustin Pop
  if real_os_dev is None:
1007 a8083063 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
1008 a8083063 Iustin Pop
                                  str(disk))
1009 a8083063 Iustin Pop
  real_os_dev.Open()
1010 a8083063 Iustin Pop
1011 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1012 a8083063 Iustin Pop
  destfile = disk.physical_id[1]
1013 a8083063 Iustin Pop
1014 a8083063 Iustin Pop
  # the target command is built out of three individual commands,
1015 a8083063 Iustin Pop
  # which are joined by pipes; we check each individual command for
1016 a8083063 Iustin Pop
  # valid parameters
1017 a8083063 Iustin Pop
1018 a8083063 Iustin Pop
  expcmd = utils.BuildShellCmd("cd %s; %s -i %s -b %s 2>%s", inst_os.path,
1019 a8083063 Iustin Pop
                               export_script, instance.name,
1020 a8083063 Iustin Pop
                               real_os_dev.dev_path, logfile)
1021 a8083063 Iustin Pop
1022 a8083063 Iustin Pop
  comprcmd = "gzip"
1023 a8083063 Iustin Pop
1024 a8083063 Iustin Pop
  remotecmd = utils.BuildShellCmd("ssh -q -oStrictHostKeyChecking=yes"
1025 a8083063 Iustin Pop
                                  " -oBatchMode=yes -oEscapeChar=none"
1026 a8083063 Iustin Pop
                                  " %s 'mkdir -p %s; cat > %s/%s'",
1027 a8083063 Iustin Pop
                                  dest_node, destdir, destdir, destfile)
1028 a8083063 Iustin Pop
1029 a8083063 Iustin Pop
  # all commands have been checked, so we're safe to combine them
1030 a8083063 Iustin Pop
  command = '|'.join([expcmd, comprcmd, remotecmd])
1031 a8083063 Iustin Pop
1032 a8083063 Iustin Pop
  result = utils.RunCmd(command)
1033 a8083063 Iustin Pop
1034 a8083063 Iustin Pop
  if result.failed:
1035 a8083063 Iustin Pop
    logger.Error("os snapshot export command '%s' returned error: %s"
1036 a8083063 Iustin Pop
                 " output: %s" %
1037 a8083063 Iustin Pop
                 (command, result.fail_reason, result.output))
1038 a8083063 Iustin Pop
    return False
1039 a8083063 Iustin Pop
1040 a8083063 Iustin Pop
  return True
1041 a8083063 Iustin Pop
1042 a8083063 Iustin Pop
1043 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
1044 a8083063 Iustin Pop
  """Write out the export configuration information.
1045 a8083063 Iustin Pop

1046 a8083063 Iustin Pop
  Args:
1047 a8083063 Iustin Pop
    instance: instance configuration
1048 a8083063 Iustin Pop
    snap_disks: snapshot block devices
1049 a8083063 Iustin Pop

1050 a8083063 Iustin Pop
  Returns:
1051 a8083063 Iustin Pop
    False in case of error, True otherwise.
1052 a8083063 Iustin Pop

1053 098c0958 Michael Hanselmann
  """
1054 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1055 a8083063 Iustin Pop
  finaldestdir = os.path.join(constants.EXPORT_DIR, instance.name)
1056 a8083063 Iustin Pop
1057 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1058 a8083063 Iustin Pop
1059 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
1060 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'version', '0')
1061 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
1062 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'source', instance.primary_node)
1063 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'os', instance.os)
1064 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'compression', 'gzip')
1065 a8083063 Iustin Pop
1066 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
1067 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'name', instance.name)
1068 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'memory', '%d' % instance.memory)
1069 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'vcpus', '%d' % instance.vcpus)
1070 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
1071 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
1072 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_mac' %
1073 a8083063 Iustin Pop
               nic_count, '%s' % nic.mac)
1074 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
1075 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
1076 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_count)
1077 a8083063 Iustin Pop
1078 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
1079 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
1080 a8083063 Iustin Pop
               ('%s' % disk.iv_name))
1081 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
1082 a8083063 Iustin Pop
               ('%s' % disk.physical_id[1]))
1083 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
1084 a8083063 Iustin Pop
               ('%d' % disk.size))
1085 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_count)
1086 a8083063 Iustin Pop
1087 a8083063 Iustin Pop
  cff = os.path.join(destdir, constants.EXPORT_CONF_FILE)
1088 a8083063 Iustin Pop
  cfo = open(cff, 'w')
1089 a8083063 Iustin Pop
  try:
1090 a8083063 Iustin Pop
    config.write(cfo)
1091 a8083063 Iustin Pop
  finally:
1092 a8083063 Iustin Pop
    cfo.close()
1093 a8083063 Iustin Pop
1094 a8083063 Iustin Pop
  shutil.rmtree(finaldestdir, True)
1095 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
1096 a8083063 Iustin Pop
1097 a8083063 Iustin Pop
  return True
1098 a8083063 Iustin Pop
1099 a8083063 Iustin Pop
1100 a8083063 Iustin Pop
def ExportInfo(dest):
1101 a8083063 Iustin Pop
  """Get export configuration information.
1102 a8083063 Iustin Pop

1103 a8083063 Iustin Pop
  Args:
1104 a8083063 Iustin Pop
    dest: directory containing the export
1105 a8083063 Iustin Pop

1106 a8083063 Iustin Pop
  Returns:
1107 a8083063 Iustin Pop
    A serializable config file containing the export info.
1108 a8083063 Iustin Pop

1109 a8083063 Iustin Pop
  """
1110 a8083063 Iustin Pop
  cff = os.path.join(dest, constants.EXPORT_CONF_FILE)
1111 a8083063 Iustin Pop
1112 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1113 a8083063 Iustin Pop
  config.read(cff)
1114 a8083063 Iustin Pop
1115 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
1116 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
1117 a8083063 Iustin Pop
    return None
1118 a8083063 Iustin Pop
1119 a8083063 Iustin Pop
  return config
1120 a8083063 Iustin Pop
1121 a8083063 Iustin Pop
1122 a8083063 Iustin Pop
def ImportOSIntoInstance(instance, os_disk, swap_disk, src_node, src_image):
1123 a8083063 Iustin Pop
  """Import an os image into an instance.
1124 a8083063 Iustin Pop

1125 a8083063 Iustin Pop
  Args:
1126 a8083063 Iustin Pop
    instance: the instance object
1127 a8083063 Iustin Pop
    os_disk: the instance-visible name of the os device
1128 a8083063 Iustin Pop
    swap_disk: the instance-visible name of the swap device
1129 a8083063 Iustin Pop
    src_node: node holding the source image
1130 a8083063 Iustin Pop
    src_image: path to the source image on src_node
1131 a8083063 Iustin Pop

1132 a8083063 Iustin Pop
  Returns:
1133 a8083063 Iustin Pop
    False in case of error, True otherwise.
1134 a8083063 Iustin Pop

1135 a8083063 Iustin Pop
  """
1136 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1137 a8083063 Iustin Pop
  import_script = inst_os.import_script
1138 a8083063 Iustin Pop
1139 a8083063 Iustin Pop
  for os_device in instance.disks:
1140 a8083063 Iustin Pop
    if os_device.iv_name == os_disk:
1141 a8083063 Iustin Pop
      break
1142 a8083063 Iustin Pop
  else:
1143 a8083063 Iustin Pop
    logger.Error("Can't find this device-visible name '%s'" % os_disk)
1144 a8083063 Iustin Pop
    return False
1145 a8083063 Iustin Pop
1146 a8083063 Iustin Pop
  for swap_device in instance.disks:
1147 a8083063 Iustin Pop
    if swap_device.iv_name == swap_disk:
1148 a8083063 Iustin Pop
      break
1149 a8083063 Iustin Pop
  else:
1150 a8083063 Iustin Pop
    logger.Error("Can't find this device-visible name '%s'" % swap_disk)
1151 a8083063 Iustin Pop
    return False
1152 a8083063 Iustin Pop
1153 a8083063 Iustin Pop
  real_os_dev = _RecursiveFindBD(os_device)
1154 a8083063 Iustin Pop
  if real_os_dev is None:
1155 a8083063 Iustin Pop
    raise errors.BlockDeviceError, ("Block device '%s' is not set up" %
1156 a8083063 Iustin Pop
                                    str(os_device))
1157 a8083063 Iustin Pop
  real_os_dev.Open()
1158 a8083063 Iustin Pop
1159 a8083063 Iustin Pop
  real_swap_dev = _RecursiveFindBD(swap_device)
1160 a8083063 Iustin Pop
  if real_swap_dev is None:
1161 a8083063 Iustin Pop
    raise errors.BlockDeviceError, ("Block device '%s' is not set up" %
1162 a8083063 Iustin Pop
                                    str(swap_device))
1163 a8083063 Iustin Pop
  real_swap_dev.Open()
1164 a8083063 Iustin Pop
1165 a8083063 Iustin Pop
  logfile = "%s/import-%s-%s-%s.log" % (constants.LOG_OS_DIR, instance.os,
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
  remotecmd = utils.BuildShellCmd("ssh -q -oStrictHostKeyChecking=yes"
1171 a8083063 Iustin Pop
                                  " -oBatchMode=yes -oEscapeChar=none"
1172 a8083063 Iustin Pop
                                  " %s 'cat %s'", src_node, src_image)
1173 a8083063 Iustin Pop
1174 a8083063 Iustin Pop
  comprcmd = "gunzip"
1175 a8083063 Iustin Pop
  impcmd = utils.BuildShellCmd("(cd %s; %s -i %s -b %s -s %s &>%s)",
1176 a8083063 Iustin Pop
                               inst_os.path, import_script, instance.name,
1177 a8083063 Iustin Pop
                               real_os_dev.dev_path, real_swap_dev.dev_path,
1178 a8083063 Iustin Pop
                               logfile)
1179 a8083063 Iustin Pop
1180 a8083063 Iustin Pop
  command = '|'.join([remotecmd, comprcmd, impcmd])
1181 a8083063 Iustin Pop
1182 a8083063 Iustin Pop
  result = utils.RunCmd(command)
1183 a8083063 Iustin Pop
1184 a8083063 Iustin Pop
  if result.failed:
1185 a8083063 Iustin Pop
    logger.Error("os import command '%s' returned error: %s"
1186 a8083063 Iustin Pop
                 " output: %s" %
1187 a8083063 Iustin Pop
                 (command, result.fail_reason, result.output))
1188 a8083063 Iustin Pop
    return False
1189 a8083063 Iustin Pop
1190 a8083063 Iustin Pop
  return True
1191 a8083063 Iustin Pop
1192 a8083063 Iustin Pop
1193 a8083063 Iustin Pop
def ListExports():
1194 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
1195 098c0958 Michael Hanselmann

1196 a8083063 Iustin Pop
  """
1197 a8083063 Iustin Pop
  if os.path.isdir(constants.EXPORT_DIR):
1198 a8083063 Iustin Pop
    return os.listdir(constants.EXPORT_DIR)
1199 a8083063 Iustin Pop
  else:
1200 a8083063 Iustin Pop
    return []
1201 a8083063 Iustin Pop
1202 a8083063 Iustin Pop
1203 a8083063 Iustin Pop
def RemoveExport(export):
1204 a8083063 Iustin Pop
  """Remove an existing export from the node.
1205 a8083063 Iustin Pop

1206 a8083063 Iustin Pop
  Args:
1207 a8083063 Iustin Pop
    export: the name of the export to remove
1208 a8083063 Iustin Pop

1209 a8083063 Iustin Pop
  Returns:
1210 a8083063 Iustin Pop
    False in case of error, True otherwise.
1211 a8083063 Iustin Pop

1212 098c0958 Michael Hanselmann
  """
1213 a8083063 Iustin Pop
  target = os.path.join(constants.EXPORT_DIR, export)
1214 a8083063 Iustin Pop
1215 a8083063 Iustin Pop
  shutil.rmtree(target)
1216 a8083063 Iustin Pop
  # TODO: catch some of the relevant exceptions and provide a pretty
1217 a8083063 Iustin Pop
  # error message if rmtree fails.
1218 a8083063 Iustin Pop
1219 a8083063 Iustin Pop
  return True
1220 a8083063 Iustin Pop
1221 a8083063 Iustin Pop
1222 a8083063 Iustin Pop
class HooksRunner(object):
1223 a8083063 Iustin Pop
  """Hook runner.
1224 a8083063 Iustin Pop

1225 a8083063 Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
1226 a8083063 Iustin Pop
  the master side.
1227 a8083063 Iustin Pop

1228 a8083063 Iustin Pop
  """
1229 a8083063 Iustin Pop
  RE_MASK = re.compile("^[a-zA-Z0-9_-]+$")
1230 a8083063 Iustin Pop
1231 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
1232 a8083063 Iustin Pop
    """Constructor for hooks runner.
1233 a8083063 Iustin Pop

1234 a8083063 Iustin Pop
    Args:
1235 a8083063 Iustin Pop
      - hooks_base_dir: if not None, this overrides the
1236 a8083063 Iustin Pop
        constants.HOOKS_BASE_DIR (useful for unittests)
1237 a8083063 Iustin Pop
      - logs_base_dir: if not None, this overrides the
1238 a8083063 Iustin Pop
        constants.LOG_HOOKS_DIR (useful for unittests)
1239 a8083063 Iustin Pop
      - logging: enable or disable logging of script output
1240 a8083063 Iustin Pop

1241 a8083063 Iustin Pop
    """
1242 a8083063 Iustin Pop
    if hooks_base_dir is None:
1243 a8083063 Iustin Pop
      hooks_base_dir = constants.HOOKS_BASE_DIR
1244 a8083063 Iustin Pop
    self._BASE_DIR = hooks_base_dir
1245 a8083063 Iustin Pop
1246 a8083063 Iustin Pop
  @staticmethod
1247 a8083063 Iustin Pop
  def ExecHook(script, env):
1248 a8083063 Iustin Pop
    """Exec one hook script.
1249 a8083063 Iustin Pop

1250 a8083063 Iustin Pop
    Args:
1251 a8083063 Iustin Pop
     - phase: the phase
1252 a8083063 Iustin Pop
     - script: the full path to the script
1253 a8083063 Iustin Pop
     - env: the environment with which to exec the script
1254 a8083063 Iustin Pop

1255 a8083063 Iustin Pop
    """
1256 a8083063 Iustin Pop
    # exec the process using subprocess and log the output
1257 a8083063 Iustin Pop
    fdstdin = None
1258 a8083063 Iustin Pop
    try:
1259 a8083063 Iustin Pop
      fdstdin = open("/dev/null", "r")
1260 a8083063 Iustin Pop
      child = subprocess.Popen([script], stdin=fdstdin, stdout=subprocess.PIPE,
1261 a8083063 Iustin Pop
                               stderr=subprocess.STDOUT, close_fds=True,
1262 a8083063 Iustin Pop
                               shell=False, cwd="/",env=env)
1263 a8083063 Iustin Pop
      output = ""
1264 a8083063 Iustin Pop
      try:
1265 a8083063 Iustin Pop
        output = child.stdout.read(4096)
1266 a8083063 Iustin Pop
        child.stdout.close()
1267 a8083063 Iustin Pop
      except EnvironmentError, err:
1268 a8083063 Iustin Pop
        output += "Hook script error: %s" % str(err)
1269 a8083063 Iustin Pop
1270 a8083063 Iustin Pop
      while True:
1271 a8083063 Iustin Pop
        try:
1272 a8083063 Iustin Pop
          result = child.wait()
1273 a8083063 Iustin Pop
          break
1274 a8083063 Iustin Pop
        except EnvironmentError, err:
1275 a8083063 Iustin Pop
          if err.errno == errno.EINTR:
1276 a8083063 Iustin Pop
            continue
1277 a8083063 Iustin Pop
          raise
1278 a8083063 Iustin Pop
    finally:
1279 a8083063 Iustin Pop
      # try not to leak fds
1280 a8083063 Iustin Pop
      for fd in (fdstdin, ):
1281 a8083063 Iustin Pop
        if fd is not None:
1282 a8083063 Iustin Pop
          try:
1283 a8083063 Iustin Pop
            fd.close()
1284 a8083063 Iustin Pop
          except EnvironmentError, err:
1285 a8083063 Iustin Pop
            # just log the error
1286 a8083063 Iustin Pop
            #logger.Error("While closing fd %s: %s" % (fd, err))
1287 a8083063 Iustin Pop
            pass
1288 a8083063 Iustin Pop
1289 a8083063 Iustin Pop
    return result == 0, output
1290 a8083063 Iustin Pop
1291 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
1292 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
1293 a8083063 Iustin Pop

1294 a8083063 Iustin Pop
    This method will not be usually overriden by child opcodes.
1295 a8083063 Iustin Pop

1296 a8083063 Iustin Pop
    """
1297 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
1298 a8083063 Iustin Pop
      suffix = "pre"
1299 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
1300 a8083063 Iustin Pop
      suffix = "post"
1301 a8083063 Iustin Pop
    else:
1302 a8083063 Iustin Pop
      raise errors.ProgrammerError, ("Unknown hooks phase: '%s'" % phase)
1303 a8083063 Iustin Pop
    rr = []
1304 a8083063 Iustin Pop
1305 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
1306 a8083063 Iustin Pop
    dir_name = "%s/%s" % (self._BASE_DIR, subdir)
1307 a8083063 Iustin Pop
    try:
1308 a8083063 Iustin Pop
      dir_contents = os.listdir(dir_name)
1309 a8083063 Iustin Pop
    except OSError, err:
1310 a8083063 Iustin Pop
      # must log
1311 a8083063 Iustin Pop
      return rr
1312 a8083063 Iustin Pop
1313 a8083063 Iustin Pop
    # we use the standard python sort order,
1314 a8083063 Iustin Pop
    # so 00name is the recommended naming scheme
1315 a8083063 Iustin Pop
    dir_contents.sort()
1316 a8083063 Iustin Pop
    for relname in dir_contents:
1317 a8083063 Iustin Pop
      fname = os.path.join(dir_name, relname)
1318 a8083063 Iustin Pop
      if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and
1319 a8083063 Iustin Pop
          self.RE_MASK.match(relname) is not None):
1320 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
1321 a8083063 Iustin Pop
        output = ""
1322 a8083063 Iustin Pop
      else:
1323 a8083063 Iustin Pop
        result, output = self.ExecHook(fname, env)
1324 a8083063 Iustin Pop
        if not result:
1325 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
1326 a8083063 Iustin Pop
        else:
1327 a8083063 Iustin Pop
          rrval = constants.HKR_SUCCESS
1328 a8083063 Iustin Pop
      rr.append(("%s/%s" % (subdir, relname), rrval, output))
1329 a8083063 Iustin Pop
1330 a8083063 Iustin Pop
    return rr