Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ d9f311d7

History | View | Annotate | Download (52 kB)

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

53 a8083063 Iustin Pop
  There are two needed steps for this:
54 880478f8 Iustin Pop
    - run the master script
55 a8083063 Iustin Pop
    - register the cron script
56 a8083063 Iustin Pop

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

71 c9064964 Iustin Pop
  This runs the master stop script.
72 a8083063 Iustin Pop

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

87 7900ed01 Iustin Pop
  This does the following:
88 7900ed01 Iustin Pop
      - updates the hostkeys of the machine (rsa and dsa)
89 7900ed01 Iustin Pop
      - adds the ssh private key to the user
90 7900ed01 Iustin Pop
      - adds the ssh public key to the users' authorized_keys file
91 a8083063 Iustin Pop

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

120 a8083063 Iustin Pop
  """
121 71eca7c3 Iustin Pop
  if os.path.isdir(constants.DATA_DIR):
122 71eca7c3 Iustin Pop
    for rel_name in utils.ListVisibleFiles(constants.DATA_DIR):
123 71eca7c3 Iustin Pop
      full_name = os.path.join(constants.DATA_DIR, rel_name)
124 71eca7c3 Iustin Pop
      if os.path.isfile(full_name) and not os.path.islink(full_name):
125 71eca7c3 Iustin Pop
        utils.RemoveFile(full_name)
126 a8083063 Iustin Pop
127 70d9e3d8 Iustin Pop
  try:
128 70d9e3d8 Iustin Pop
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
129 18682bca Iustin Pop
  except errors.OpExecError:
130 18682bca Iustin Pop
    logging.exception("Error while processing ssh files")
131 7900ed01 Iustin Pop
    return
132 7900ed01 Iustin Pop
133 70d9e3d8 Iustin Pop
  f = open(pub_key, 'r')
134 a8083063 Iustin Pop
  try:
135 70d9e3d8 Iustin Pop
    utils.RemoveAuthorizedKey(auth_keys, f.read(8192))
136 a8083063 Iustin Pop
  finally:
137 a8083063 Iustin Pop
    f.close()
138 a8083063 Iustin Pop
139 70d9e3d8 Iustin Pop
  utils.RemoveFile(priv_key)
140 70d9e3d8 Iustin Pop
  utils.RemoveFile(pub_key)
141 a8083063 Iustin Pop
142 6d8b6238 Guido Trotter
  # Return a reassuring string to the caller, and quit
143 6d8b6238 Guido Trotter
  raise errors.QuitGanetiException(False, 'Shutdown scheduled')
144 6d8b6238 Guido Trotter
145 a8083063 Iustin Pop
146 a8083063 Iustin Pop
def GetNodeInfo(vgname):
147 2f8598a5 Alexander Schreiber
  """Gives back a hash with different informations about the node.
148 a8083063 Iustin Pop

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

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

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

188 a8083063 Iustin Pop
  Requested files on local node are checksummed and the result returned.
189 a8083063 Iustin Pop

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

196 a8083063 Iustin Pop
  """
197 a8083063 Iustin Pop
  result = {}
198 a8083063 Iustin Pop
199 a8083063 Iustin Pop
  if 'hypervisor' in what:
200 a8083063 Iustin Pop
    result['hypervisor'] = hypervisor.GetHypervisor().Verify()
201 a8083063 Iustin Pop
202 a8083063 Iustin Pop
  if 'filelist' in what:
203 a8083063 Iustin Pop
    result['filelist'] = utils.FingerprintFiles(what['filelist'])
204 a8083063 Iustin Pop
205 a8083063 Iustin Pop
  if 'nodelist' in what:
206 a8083063 Iustin Pop
    result['nodelist'] = {}
207 b544cfe0 Iustin Pop
    random.shuffle(what['nodelist'])
208 a8083063 Iustin Pop
    for node in what['nodelist']:
209 c92b310a Michael Hanselmann
      success, message = _GetSshRunner().VerifyNodeHostname(node)
210 a8083063 Iustin Pop
      if not success:
211 a8083063 Iustin Pop
        result['nodelist'][node] = message
212 9d4bfc96 Iustin Pop
  if 'node-net-test' in what:
213 9d4bfc96 Iustin Pop
    result['node-net-test'] = {}
214 9d4bfc96 Iustin Pop
    my_name = utils.HostInfo().name
215 9d4bfc96 Iustin Pop
    my_pip = my_sip = None
216 9d4bfc96 Iustin Pop
    for name, pip, sip in what['node-net-test']:
217 9d4bfc96 Iustin Pop
      if name == my_name:
218 9d4bfc96 Iustin Pop
        my_pip = pip
219 9d4bfc96 Iustin Pop
        my_sip = sip
220 9d4bfc96 Iustin Pop
        break
221 9d4bfc96 Iustin Pop
    if not my_pip:
222 9d4bfc96 Iustin Pop
      result['node-net-test'][my_name] = ("Can't find my own"
223 9d4bfc96 Iustin Pop
                                          " primary/secondary IP"
224 9d4bfc96 Iustin Pop
                                          " in the node list")
225 9d4bfc96 Iustin Pop
    else:
226 9d4bfc96 Iustin Pop
      port = ssconf.SimpleStore().GetNodeDaemonPort()
227 9d4bfc96 Iustin Pop
      for name, pip, sip in what['node-net-test']:
228 9d4bfc96 Iustin Pop
        fail = []
229 9d4bfc96 Iustin Pop
        if not utils.TcpPing(pip, port, source=my_pip):
230 9d4bfc96 Iustin Pop
          fail.append("primary")
231 9d4bfc96 Iustin Pop
        if sip != pip:
232 9d4bfc96 Iustin Pop
          if not utils.TcpPing(sip, port, source=my_sip):
233 9d4bfc96 Iustin Pop
            fail.append("secondary")
234 9d4bfc96 Iustin Pop
        if fail:
235 9d4bfc96 Iustin Pop
          result['node-net-test'][name] = ("failure using the %s"
236 9d4bfc96 Iustin Pop
                                           " interface(s)" %
237 9d4bfc96 Iustin Pop
                                           " and ".join(fail))
238 9d4bfc96 Iustin Pop
239 a8083063 Iustin Pop
  return result
240 a8083063 Iustin Pop
241 a8083063 Iustin Pop
242 a8083063 Iustin Pop
def GetVolumeList(vg_name):
243 a8083063 Iustin Pop
  """Compute list of logical volumes and their size.
244 a8083063 Iustin Pop

245 a8083063 Iustin Pop
  Returns:
246 cb2037a2 Iustin Pop
    dictionary of all partions (key) with their size (in MiB), inactive
247 cb2037a2 Iustin Pop
    and online status:
248 cb2037a2 Iustin Pop
    {'test1': ('20.06', True, True)}
249 a8083063 Iustin Pop

250 a8083063 Iustin Pop
  """
251 cb2037a2 Iustin Pop
  lvs = {}
252 cb2037a2 Iustin Pop
  sep = '|'
253 cb2037a2 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
254 cb2037a2 Iustin Pop
                         "--separator=%s" % sep,
255 cb2037a2 Iustin Pop
                         "-olv_name,lv_size,lv_attr", vg_name])
256 a8083063 Iustin Pop
  if result.failed:
257 18682bca Iustin Pop
    logging.error("Failed to list logical volumes, lvs output: %s",
258 18682bca Iustin Pop
                  result.output)
259 b63ed789 Iustin Pop
    return result.output
260 cb2037a2 Iustin Pop
261 df4c2628 Iustin Pop
  valid_line_re = re.compile("^ *([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
262 cb2037a2 Iustin Pop
  for line in result.stdout.splitlines():
263 df4c2628 Iustin Pop
    line = line.strip()
264 df4c2628 Iustin Pop
    match = valid_line_re.match(line)
265 df4c2628 Iustin Pop
    if not match:
266 18682bca Iustin Pop
      logging.error("Invalid line returned from lvs output: '%s'", line)
267 df4c2628 Iustin Pop
      continue
268 df4c2628 Iustin Pop
    name, size, attr = match.groups()
269 cb2037a2 Iustin Pop
    inactive = attr[4] == '-'
270 cb2037a2 Iustin Pop
    online = attr[5] == 'o'
271 cb2037a2 Iustin Pop
    lvs[name] = (size, inactive, online)
272 cb2037a2 Iustin Pop
273 cb2037a2 Iustin Pop
  return lvs
274 a8083063 Iustin Pop
275 a8083063 Iustin Pop
276 a8083063 Iustin Pop
def ListVolumeGroups():
277 2f8598a5 Alexander Schreiber
  """List the volume groups and their size.
278 a8083063 Iustin Pop

279 a8083063 Iustin Pop
  Returns:
280 a8083063 Iustin Pop
    Dictionary with keys volume name and values the size of the volume
281 a8083063 Iustin Pop

282 a8083063 Iustin Pop
  """
283 a8083063 Iustin Pop
  return utils.ListVolumeGroups()
284 a8083063 Iustin Pop
285 a8083063 Iustin Pop
286 dcb93971 Michael Hanselmann
def NodeVolumes():
287 dcb93971 Michael Hanselmann
  """List all volumes on this node.
288 dcb93971 Michael Hanselmann

289 dcb93971 Michael Hanselmann
  """
290 dcb93971 Michael Hanselmann
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
291 dcb93971 Michael Hanselmann
                         "--separator=|",
292 dcb93971 Michael Hanselmann
                         "--options=lv_name,lv_size,devices,vg_name"])
293 dcb93971 Michael Hanselmann
  if result.failed:
294 18682bca Iustin Pop
    logging.error("Failed to list logical volumes, lvs output: %s",
295 18682bca Iustin Pop
                  result.output)
296 dcb93971 Michael Hanselmann
    return {}
297 dcb93971 Michael Hanselmann
298 dcb93971 Michael Hanselmann
  def parse_dev(dev):
299 dcb93971 Michael Hanselmann
    if '(' in dev:
300 dcb93971 Michael Hanselmann
      return dev.split('(')[0]
301 dcb93971 Michael Hanselmann
    else:
302 dcb93971 Michael Hanselmann
      return dev
303 dcb93971 Michael Hanselmann
304 dcb93971 Michael Hanselmann
  def map_line(line):
305 dcb93971 Michael Hanselmann
    return {
306 dcb93971 Michael Hanselmann
      'name': line[0].strip(),
307 dcb93971 Michael Hanselmann
      'size': line[1].strip(),
308 dcb93971 Michael Hanselmann
      'dev': parse_dev(line[2].strip()),
309 dcb93971 Michael Hanselmann
      'vg': line[3].strip(),
310 dcb93971 Michael Hanselmann
    }
311 dcb93971 Michael Hanselmann
312 a17a7623 Iustin Pop
  return [map_line(line.split('|')) for line in result.stdout.splitlines()
313 a17a7623 Iustin Pop
          if line.count('|') >= 3]
314 dcb93971 Michael Hanselmann
315 dcb93971 Michael Hanselmann
316 a8083063 Iustin Pop
def BridgesExist(bridges_list):
317 2f8598a5 Alexander Schreiber
  """Check if a list of bridges exist on the current node.
318 a8083063 Iustin Pop

319 a8083063 Iustin Pop
  Returns:
320 a8083063 Iustin Pop
    True if all of them exist, false otherwise
321 a8083063 Iustin Pop

322 a8083063 Iustin Pop
  """
323 a8083063 Iustin Pop
  for bridge in bridges_list:
324 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
325 a8083063 Iustin Pop
      return False
326 a8083063 Iustin Pop
327 a8083063 Iustin Pop
  return True
328 a8083063 Iustin Pop
329 a8083063 Iustin Pop
330 a8083063 Iustin Pop
def GetInstanceList():
331 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
332 a8083063 Iustin Pop

333 a8083063 Iustin Pop
  Returns:
334 a8083063 Iustin Pop
    A list of all running instances on the current node
335 a8083063 Iustin Pop
    - instance1.example.com
336 a8083063 Iustin Pop
    - instance2.example.com
337 a8083063 Iustin Pop

338 098c0958 Michael Hanselmann
  """
339 a8083063 Iustin Pop
  try:
340 a8083063 Iustin Pop
    names = hypervisor.GetHypervisor().ListInstances()
341 a8083063 Iustin Pop
  except errors.HypervisorError, err:
342 18682bca Iustin Pop
    logging.exception("Error enumerating instances")
343 a8083063 Iustin Pop
    raise
344 a8083063 Iustin Pop
345 a8083063 Iustin Pop
  return names
346 a8083063 Iustin Pop
347 a8083063 Iustin Pop
348 a8083063 Iustin Pop
def GetInstanceInfo(instance):
349 2f8598a5 Alexander Schreiber
  """Gives back the informations about an instance as a dictionary.
350 a8083063 Iustin Pop

351 a8083063 Iustin Pop
  Args:
352 a8083063 Iustin Pop
    instance: name of the instance (ex. instance1.example.com)
353 a8083063 Iustin Pop

354 a8083063 Iustin Pop
  Returns:
355 a8083063 Iustin Pop
    { 'memory' : 511, 'state' : '-b---', 'time' : 3188.8, }
356 a8083063 Iustin Pop
    where
357 a8083063 Iustin Pop
    memory: memory size of instance (int)
358 a8083063 Iustin Pop
    state: xen state of instance (string)
359 a8083063 Iustin Pop
    time: cpu time of instance (float)
360 a8083063 Iustin Pop

361 098c0958 Michael Hanselmann
  """
362 a8083063 Iustin Pop
  output = {}
363 a8083063 Iustin Pop
364 a8083063 Iustin Pop
  iinfo = hypervisor.GetHypervisor().GetInstanceInfo(instance)
365 a8083063 Iustin Pop
  if iinfo is not None:
366 a8083063 Iustin Pop
    output['memory'] = iinfo[2]
367 a8083063 Iustin Pop
    output['state'] = iinfo[4]
368 a8083063 Iustin Pop
    output['time'] = iinfo[5]
369 a8083063 Iustin Pop
370 a8083063 Iustin Pop
  return output
371 a8083063 Iustin Pop
372 a8083063 Iustin Pop
373 a8083063 Iustin Pop
def GetAllInstancesInfo():
374 a8083063 Iustin Pop
  """Gather data about all instances.
375 a8083063 Iustin Pop

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

380 a8083063 Iustin Pop
  Returns: a dictionary of dictionaries, keys being the instance name,
381 a8083063 Iustin Pop
    and with values:
382 a8083063 Iustin Pop
    { 'memory' : 511, 'state' : '-b---', 'time' : 3188.8, }
383 a8083063 Iustin Pop
    where
384 a8083063 Iustin Pop
    memory: memory size of instance (int)
385 a8083063 Iustin Pop
    state: xen state of instance (string)
386 a8083063 Iustin Pop
    time: cpu time of instance (float)
387 a8083063 Iustin Pop
    vcpus: the number of cpus
388 a8083063 Iustin Pop

389 098c0958 Michael Hanselmann
  """
390 a8083063 Iustin Pop
  output = {}
391 a8083063 Iustin Pop
392 a8083063 Iustin Pop
  iinfo = hypervisor.GetHypervisor().GetAllInstancesInfo()
393 a8083063 Iustin Pop
  if iinfo:
394 3ecf6786 Iustin Pop
    for name, inst_id, memory, vcpus, state, times in iinfo:
395 a8083063 Iustin Pop
      output[name] = {
396 a8083063 Iustin Pop
        'memory': memory,
397 a8083063 Iustin Pop
        'vcpus': vcpus,
398 a8083063 Iustin Pop
        'state': state,
399 a8083063 Iustin Pop
        'time': times,
400 a8083063 Iustin Pop
        }
401 a8083063 Iustin Pop
402 a8083063 Iustin Pop
  return output
403 a8083063 Iustin Pop
404 a8083063 Iustin Pop
405 a8083063 Iustin Pop
def AddOSToInstance(instance, os_disk, swap_disk):
406 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
407 a8083063 Iustin Pop

408 a8083063 Iustin Pop
  Args:
409 a8083063 Iustin Pop
    instance: the instance object
410 a8083063 Iustin Pop
    os_disk: the instance-visible name of the os device
411 a8083063 Iustin Pop
    swap_disk: the instance-visible name of the swap device
412 a8083063 Iustin Pop

413 a8083063 Iustin Pop
  """
414 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
415 a8083063 Iustin Pop
416 a8083063 Iustin Pop
  create_script = inst_os.create_script
417 a8083063 Iustin Pop
418 9716fdce Iustin Pop
  os_device = instance.FindDisk(os_disk)
419 9716fdce Iustin Pop
  if os_device is None:
420 18682bca Iustin Pop
    logging.error("Can't find this device-visible name '%s'", os_disk)
421 a8083063 Iustin Pop
    return False
422 a8083063 Iustin Pop
423 9716fdce Iustin Pop
  swap_device = instance.FindDisk(swap_disk)
424 9716fdce Iustin Pop
  if swap_device is None:
425 18682bca Iustin Pop
    logging.error("Can't find this device-visible name '%s'", swap_disk)
426 a8083063 Iustin Pop
    return False
427 a8083063 Iustin Pop
428 a8083063 Iustin Pop
  real_os_dev = _RecursiveFindBD(os_device)
429 a8083063 Iustin Pop
  if real_os_dev is None:
430 a8083063 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
431 a8083063 Iustin Pop
                                  str(os_device))
432 a8083063 Iustin Pop
  real_os_dev.Open()
433 a8083063 Iustin Pop
434 a8083063 Iustin Pop
  real_swap_dev = _RecursiveFindBD(swap_device)
435 a8083063 Iustin Pop
  if real_swap_dev is None:
436 a8083063 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
437 a8083063 Iustin Pop
                                  str(swap_device))
438 a8083063 Iustin Pop
  real_swap_dev.Open()
439 a8083063 Iustin Pop
440 a8083063 Iustin Pop
  logfile = "%s/add-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
441 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
442 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
443 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
444 a8083063 Iustin Pop
445 c20494cd Iustin Pop
  command = utils.BuildShellCmd("cd %s && %s -i %s -b %s -s %s &>%s",
446 a8083063 Iustin Pop
                                inst_os.path, create_script, instance.name,
447 a8083063 Iustin Pop
                                real_os_dev.dev_path, real_swap_dev.dev_path,
448 a8083063 Iustin Pop
                                logfile)
449 decd5f45 Iustin Pop
450 decd5f45 Iustin Pop
  result = utils.RunCmd(command)
451 decd5f45 Iustin Pop
  if result.failed:
452 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
453 18682bca Iustin Pop
                  " output: %s", command, result.fail_reason, logfile,
454 18682bca Iustin Pop
                  result.output)
455 decd5f45 Iustin Pop
    return False
456 decd5f45 Iustin Pop
457 decd5f45 Iustin Pop
  return True
458 decd5f45 Iustin Pop
459 decd5f45 Iustin Pop
460 decd5f45 Iustin Pop
def RunRenameInstance(instance, old_name, os_disk, swap_disk):
461 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
462 decd5f45 Iustin Pop

463 decd5f45 Iustin Pop
  Args:
464 decd5f45 Iustin Pop
    instance: the instance object
465 decd5f45 Iustin Pop
    old_name: the old name of the instance
466 decd5f45 Iustin Pop
    os_disk: the instance-visible name of the os device
467 decd5f45 Iustin Pop
    swap_disk: the instance-visible name of the swap device
468 decd5f45 Iustin Pop

469 decd5f45 Iustin Pop
  """
470 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
471 decd5f45 Iustin Pop
472 decd5f45 Iustin Pop
  script = inst_os.rename_script
473 decd5f45 Iustin Pop
474 decd5f45 Iustin Pop
  os_device = instance.FindDisk(os_disk)
475 decd5f45 Iustin Pop
  if os_device is None:
476 18682bca Iustin Pop
    logging.error("Can't find this device-visible name '%s'", os_disk)
477 decd5f45 Iustin Pop
    return False
478 decd5f45 Iustin Pop
479 decd5f45 Iustin Pop
  swap_device = instance.FindDisk(swap_disk)
480 decd5f45 Iustin Pop
  if swap_device is None:
481 18682bca Iustin Pop
    logging.error("Can't find this device-visible name '%s'", swap_disk)
482 decd5f45 Iustin Pop
    return False
483 decd5f45 Iustin Pop
484 decd5f45 Iustin Pop
  real_os_dev = _RecursiveFindBD(os_device)
485 decd5f45 Iustin Pop
  if real_os_dev is None:
486 decd5f45 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
487 decd5f45 Iustin Pop
                                  str(os_device))
488 decd5f45 Iustin Pop
  real_os_dev.Open()
489 decd5f45 Iustin Pop
490 decd5f45 Iustin Pop
  real_swap_dev = _RecursiveFindBD(swap_device)
491 decd5f45 Iustin Pop
  if real_swap_dev is None:
492 decd5f45 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
493 decd5f45 Iustin Pop
                                  str(swap_device))
494 decd5f45 Iustin Pop
  real_swap_dev.Open()
495 decd5f45 Iustin Pop
496 decd5f45 Iustin Pop
  logfile = "%s/rename-%s-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
497 decd5f45 Iustin Pop
                                           old_name,
498 decd5f45 Iustin Pop
                                           instance.name, int(time.time()))
499 decd5f45 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
500 decd5f45 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
501 decd5f45 Iustin Pop
502 decd5f45 Iustin Pop
  command = utils.BuildShellCmd("cd %s && %s -o %s -n %s -b %s -s %s &>%s",
503 decd5f45 Iustin Pop
                                inst_os.path, script, old_name, instance.name,
504 decd5f45 Iustin Pop
                                real_os_dev.dev_path, real_swap_dev.dev_path,
505 decd5f45 Iustin Pop
                                logfile)
506 a8083063 Iustin Pop
507 a8083063 Iustin Pop
  result = utils.RunCmd(command)
508 a8083063 Iustin Pop
509 a8083063 Iustin Pop
  if result.failed:
510 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
511 18682bca Iustin Pop
                  command, result.fail_reason, result.output)
512 a8083063 Iustin Pop
    return False
513 a8083063 Iustin Pop
514 a8083063 Iustin Pop
  return True
515 a8083063 Iustin Pop
516 a8083063 Iustin Pop
517 a8083063 Iustin Pop
def _GetVGInfo(vg_name):
518 a8083063 Iustin Pop
  """Get informations about the volume group.
519 a8083063 Iustin Pop

520 a8083063 Iustin Pop
  Args:
521 a8083063 Iustin Pop
    vg_name: the volume group
522 a8083063 Iustin Pop

523 a8083063 Iustin Pop
  Returns:
524 a8083063 Iustin Pop
    { 'vg_size' : xxx, 'vg_free' : xxx, 'pv_count' : xxx }
525 a8083063 Iustin Pop
    where
526 a8083063 Iustin Pop
    vg_size is the total size of the volume group in MiB
527 a8083063 Iustin Pop
    vg_free is the free size of the volume group in MiB
528 a8083063 Iustin Pop
    pv_count are the number of physical disks in that vg
529 a8083063 Iustin Pop

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

533 a8083063 Iustin Pop
  """
534 f4d377e7 Iustin Pop
  retdic = dict.fromkeys(["vg_size", "vg_free", "pv_count"])
535 f4d377e7 Iustin Pop
536 a8083063 Iustin Pop
  retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings",
537 a8083063 Iustin Pop
                         "--nosuffix", "--units=m", "--separator=:", vg_name])
538 a8083063 Iustin Pop
539 a8083063 Iustin Pop
  if retval.failed:
540 18682bca Iustin Pop
    logging.error("volume group %s not present", vg_name)
541 f4d377e7 Iustin Pop
    return retdic
542 d87ae7d2 Iustin Pop
  valarr = retval.stdout.strip().rstrip(':').split(':')
543 f4d377e7 Iustin Pop
  if len(valarr) == 3:
544 f4d377e7 Iustin Pop
    try:
545 f4d377e7 Iustin Pop
      retdic = {
546 f4d377e7 Iustin Pop
        "vg_size": int(round(float(valarr[0]), 0)),
547 f4d377e7 Iustin Pop
        "vg_free": int(round(float(valarr[1]), 0)),
548 f4d377e7 Iustin Pop
        "pv_count": int(valarr[2]),
549 f4d377e7 Iustin Pop
        }
550 f4d377e7 Iustin Pop
    except ValueError, err:
551 18682bca Iustin Pop
      logging.exception("Fail to parse vgs output")
552 f4d377e7 Iustin Pop
  else:
553 18682bca Iustin Pop
    logging.error("vgs output has the wrong number of fields (expected"
554 18682bca Iustin Pop
                  " three): %s", str(valarr))
555 a8083063 Iustin Pop
  return retdic
556 a8083063 Iustin Pop
557 a8083063 Iustin Pop
558 a8083063 Iustin Pop
def _GatherBlockDevs(instance):
559 a8083063 Iustin Pop
  """Set up an instance's block device(s).
560 a8083063 Iustin Pop

561 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
562 a8083063 Iustin Pop
  devices must be already assembled.
563 a8083063 Iustin Pop

564 a8083063 Iustin Pop
  """
565 a8083063 Iustin Pop
  block_devices = []
566 a8083063 Iustin Pop
  for disk in instance.disks:
567 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
568 a8083063 Iustin Pop
    if device is None:
569 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
570 a8083063 Iustin Pop
                                    str(disk))
571 a8083063 Iustin Pop
    device.Open()
572 a8083063 Iustin Pop
    block_devices.append((disk, device))
573 a8083063 Iustin Pop
  return block_devices
574 a8083063 Iustin Pop
575 a8083063 Iustin Pop
576 a8083063 Iustin Pop
def StartInstance(instance, extra_args):
577 a8083063 Iustin Pop
  """Start an instance.
578 a8083063 Iustin Pop

579 a8083063 Iustin Pop
  Args:
580 a8083063 Iustin Pop
    instance - name of instance to start.
581 a8083063 Iustin Pop

582 098c0958 Michael Hanselmann
  """
583 a8083063 Iustin Pop
  running_instances = GetInstanceList()
584 a8083063 Iustin Pop
585 a8083063 Iustin Pop
  if instance.name in running_instances:
586 a8083063 Iustin Pop
    return True
587 a8083063 Iustin Pop
588 a8083063 Iustin Pop
  block_devices = _GatherBlockDevs(instance)
589 a8083063 Iustin Pop
  hyper = hypervisor.GetHypervisor()
590 a8083063 Iustin Pop
591 a8083063 Iustin Pop
  try:
592 a8083063 Iustin Pop
    hyper.StartInstance(instance, block_devices, extra_args)
593 a8083063 Iustin Pop
  except errors.HypervisorError, err:
594 18682bca Iustin Pop
    logging.exception("Failed to start instance")
595 a8083063 Iustin Pop
    return False
596 a8083063 Iustin Pop
597 a8083063 Iustin Pop
  return True
598 a8083063 Iustin Pop
599 a8083063 Iustin Pop
600 a8083063 Iustin Pop
def ShutdownInstance(instance):
601 a8083063 Iustin Pop
  """Shut an instance down.
602 a8083063 Iustin Pop

603 a8083063 Iustin Pop
  Args:
604 a8083063 Iustin Pop
    instance - name of instance to shutdown.
605 a8083063 Iustin Pop

606 098c0958 Michael Hanselmann
  """
607 a8083063 Iustin Pop
  running_instances = GetInstanceList()
608 a8083063 Iustin Pop
609 a8083063 Iustin Pop
  if instance.name not in running_instances:
610 a8083063 Iustin Pop
    return True
611 a8083063 Iustin Pop
612 a8083063 Iustin Pop
  hyper = hypervisor.GetHypervisor()
613 a8083063 Iustin Pop
  try:
614 a8083063 Iustin Pop
    hyper.StopInstance(instance)
615 a8083063 Iustin Pop
  except errors.HypervisorError, err:
616 18682bca Iustin Pop
    logging.error("Failed to stop instance")
617 a8083063 Iustin Pop
    return False
618 a8083063 Iustin Pop
619 a8083063 Iustin Pop
  # test every 10secs for 2min
620 a8083063 Iustin Pop
  shutdown_ok = False
621 a8083063 Iustin Pop
622 a8083063 Iustin Pop
  time.sleep(1)
623 a8083063 Iustin Pop
  for dummy in range(11):
624 a8083063 Iustin Pop
    if instance.name not in GetInstanceList():
625 a8083063 Iustin Pop
      break
626 a8083063 Iustin Pop
    time.sleep(10)
627 a8083063 Iustin Pop
  else:
628 a8083063 Iustin Pop
    # the shutdown did not succeed
629 18682bca Iustin Pop
    logging.error("shutdown of '%s' unsuccessful, using destroy", instance)
630 a8083063 Iustin Pop
631 a8083063 Iustin Pop
    try:
632 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
633 a8083063 Iustin Pop
    except errors.HypervisorError, err:
634 18682bca Iustin Pop
      logging.exception("Failed to stop instance")
635 a8083063 Iustin Pop
      return False
636 a8083063 Iustin Pop
637 a8083063 Iustin Pop
    time.sleep(1)
638 a8083063 Iustin Pop
    if instance.name in GetInstanceList():
639 18682bca Iustin Pop
      logging.error("could not shutdown instance '%s' even by destroy",
640 18682bca Iustin Pop
                    instance.name)
641 a8083063 Iustin Pop
      return False
642 a8083063 Iustin Pop
643 a8083063 Iustin Pop
  return True
644 a8083063 Iustin Pop
645 a8083063 Iustin Pop
646 007a2f3e Alexander Schreiber
def RebootInstance(instance, reboot_type, extra_args):
647 007a2f3e Alexander Schreiber
  """Reboot an instance.
648 007a2f3e Alexander Schreiber

649 007a2f3e Alexander Schreiber
  Args:
650 007a2f3e Alexander Schreiber
    instance    - name of instance to reboot
651 007a2f3e Alexander Schreiber
    reboot_type - how to reboot [soft,hard,full]
652 007a2f3e Alexander Schreiber

653 007a2f3e Alexander Schreiber
  """
654 007a2f3e Alexander Schreiber
  running_instances = GetInstanceList()
655 007a2f3e Alexander Schreiber
656 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
657 18682bca Iustin Pop
    logging.error("Cannot reboot instance that is not running")
658 007a2f3e Alexander Schreiber
    return False
659 007a2f3e Alexander Schreiber
660 007a2f3e Alexander Schreiber
  hyper = hypervisor.GetHypervisor()
661 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
662 007a2f3e Alexander Schreiber
    try:
663 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
664 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
665 18682bca Iustin Pop
      logging.exception("Failed to soft reboot instance")
666 007a2f3e Alexander Schreiber
      return False
667 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
668 007a2f3e Alexander Schreiber
    try:
669 007a2f3e Alexander Schreiber
      ShutdownInstance(instance)
670 007a2f3e Alexander Schreiber
      StartInstance(instance, extra_args)
671 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
672 18682bca Iustin Pop
      logging.exception("Failed to hard reboot instance")
673 007a2f3e Alexander Schreiber
      return False
674 007a2f3e Alexander Schreiber
  else:
675 007a2f3e Alexander Schreiber
    raise errors.ParameterError("reboot_type invalid")
676 007a2f3e Alexander Schreiber
677 007a2f3e Alexander Schreiber
678 007a2f3e Alexander Schreiber
  return True
679 007a2f3e Alexander Schreiber
680 007a2f3e Alexander Schreiber
681 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
682 2a10865c Iustin Pop
  """Migrates an instance to another node.
683 2a10865c Iustin Pop

684 2a10865c Iustin Pop
  """
685 2a10865c Iustin Pop
  hyper = hypervisor.GetHypervisor()
686 2a10865c Iustin Pop
687 2a10865c Iustin Pop
  try:
688 2a10865c Iustin Pop
    hyper.MigrateInstance(instance, target, live)
689 2a10865c Iustin Pop
  except errors.HypervisorError, err:
690 2a10865c Iustin Pop
    msg = "Failed to migrate instance: %s" % str(err)
691 18682bca Iustin Pop
    logging.error(msg)
692 2a10865c Iustin Pop
    return (False, msg)
693 2a10865c Iustin Pop
  return (True, "Migration successfull")
694 2a10865c Iustin Pop
695 2a10865c Iustin Pop
696 3f78eef2 Iustin Pop
def CreateBlockDevice(disk, size, owner, on_primary, info):
697 a8083063 Iustin Pop
  """Creates a block device for an instance.
698 a8083063 Iustin Pop

699 a8083063 Iustin Pop
  Args:
700 c99a3cc0 Manuel Franceschini
   disk: a ganeti.objects.Disk object
701 c99a3cc0 Manuel Franceschini
   size: the size of the physical underlying device
702 c99a3cc0 Manuel Franceschini
   owner: a string with the name of the instance
703 6c8af3d0 Manuel Franceschini
   on_primary: a boolean indicating if it is the primary node or not
704 6c8af3d0 Manuel Franceschini
   info: string that will be sent to the physical device creation
705 a8083063 Iustin Pop

706 a8083063 Iustin Pop
  Returns:
707 a8083063 Iustin Pop
    the new unique_id of the device (this can sometime be
708 a8083063 Iustin Pop
    computed only after creation), or None. On secondary nodes,
709 a8083063 Iustin Pop
    it's not required to return anything.
710 a8083063 Iustin Pop

711 a8083063 Iustin Pop
  """
712 a8083063 Iustin Pop
  clist = []
713 a8083063 Iustin Pop
  if disk.children:
714 a8083063 Iustin Pop
    for child in disk.children:
715 3f78eef2 Iustin Pop
      crdev = _RecursiveAssembleBD(child, owner, on_primary)
716 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
717 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
718 a8083063 Iustin Pop
        # be assembled
719 a8083063 Iustin Pop
        crdev.Open()
720 a8083063 Iustin Pop
      clist.append(crdev)
721 a8083063 Iustin Pop
  try:
722 a8083063 Iustin Pop
    device = bdev.FindDevice(disk.dev_type, disk.physical_id, clist)
723 a8083063 Iustin Pop
    if device is not None:
724 18682bca Iustin Pop
      logging.info("removing existing device %s", disk)
725 a8083063 Iustin Pop
      device.Remove()
726 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
727 a8083063 Iustin Pop
    pass
728 a8083063 Iustin Pop
729 a8083063 Iustin Pop
  device = bdev.Create(disk.dev_type, disk.physical_id,
730 a8083063 Iustin Pop
                       clist, size)
731 a8083063 Iustin Pop
  if device is None:
732 a8083063 Iustin Pop
    raise ValueError("Can't create child device for %s, %s" %
733 a8083063 Iustin Pop
                     (disk, size))
734 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
735 cf5a8306 Iustin Pop
    if not device.Assemble():
736 20a0c9ef Guido Trotter
      errorstring = "Can't assemble device after creation"
737 18682bca Iustin Pop
      logging.error(errorstring)
738 20a0c9ef Guido Trotter
      raise errors.BlockDeviceError("%s, very unusual event - check the node"
739 20a0c9ef Guido Trotter
                                    " daemon logs" % errorstring)
740 e31c43f7 Michael Hanselmann
    device.SetSyncSpeed(constants.SYNC_SPEED)
741 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
742 a8083063 Iustin Pop
      device.Open(force=True)
743 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
744 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
745 a0c3fea1 Michael Hanselmann
746 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
747 a0c3fea1 Michael Hanselmann
748 a8083063 Iustin Pop
  physical_id = device.unique_id
749 a8083063 Iustin Pop
  return physical_id
750 a8083063 Iustin Pop
751 a8083063 Iustin Pop
752 a8083063 Iustin Pop
def RemoveBlockDevice(disk):
753 a8083063 Iustin Pop
  """Remove a block device.
754 a8083063 Iustin Pop

755 a8083063 Iustin Pop
  This is intended to be called recursively.
756 a8083063 Iustin Pop

757 a8083063 Iustin Pop
  """
758 a8083063 Iustin Pop
  try:
759 a8083063 Iustin Pop
    # since we are removing the device, allow a partial match
760 a8083063 Iustin Pop
    # this allows removal of broken mirrors
761 a8083063 Iustin Pop
    rdev = _RecursiveFindBD(disk, allow_partial=True)
762 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
763 a8083063 Iustin Pop
    # probably can't attach
764 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
765 a8083063 Iustin Pop
    rdev = None
766 a8083063 Iustin Pop
  if rdev is not None:
767 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
768 a8083063 Iustin Pop
    result = rdev.Remove()
769 3f78eef2 Iustin Pop
    if result:
770 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
771 a8083063 Iustin Pop
  else:
772 a8083063 Iustin Pop
    result = True
773 a8083063 Iustin Pop
  if disk.children:
774 a8083063 Iustin Pop
    for child in disk.children:
775 a8083063 Iustin Pop
      result = result and RemoveBlockDevice(child)
776 a8083063 Iustin Pop
  return result
777 a8083063 Iustin Pop
778 a8083063 Iustin Pop
779 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
780 a8083063 Iustin Pop
  """Activate a block device for an instance.
781 a8083063 Iustin Pop

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

784 a8083063 Iustin Pop
  This function is called recursively.
785 a8083063 Iustin Pop

786 a8083063 Iustin Pop
  Args:
787 a8083063 Iustin Pop
    disk: a objects.Disk object
788 a8083063 Iustin Pop
    as_primary: if we should make the block device read/write
789 a8083063 Iustin Pop

790 a8083063 Iustin Pop
  Returns:
791 a8083063 Iustin Pop
    the assembled device or None (in case no device was assembled)
792 a8083063 Iustin Pop

793 a8083063 Iustin Pop
  If the assembly is not successful, an exception is raised.
794 a8083063 Iustin Pop

795 a8083063 Iustin Pop
  """
796 a8083063 Iustin Pop
  children = []
797 a8083063 Iustin Pop
  if disk.children:
798 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
799 fc1dc9d7 Iustin Pop
    if mcn == -1:
800 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
801 fc1dc9d7 Iustin Pop
    else:
802 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
803 a8083063 Iustin Pop
    for chld_disk in disk.children:
804 fc1dc9d7 Iustin Pop
      try:
805 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
806 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
807 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
808 fc1dc9d7 Iustin Pop
          raise
809 fc1dc9d7 Iustin Pop
        cdev = None
810 18682bca Iustin Pop
        logging.debug("Error in child activation: %s", str(err))
811 fc1dc9d7 Iustin Pop
      children.append(cdev)
812 a8083063 Iustin Pop
813 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
814 a8083063 Iustin Pop
    r_dev = bdev.AttachOrAssemble(disk.dev_type, disk.physical_id, children)
815 e31c43f7 Michael Hanselmann
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
816 a8083063 Iustin Pop
    result = r_dev
817 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
818 a8083063 Iustin Pop
      r_dev.Open()
819 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
820 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
821 3f78eef2 Iustin Pop
822 a8083063 Iustin Pop
  else:
823 a8083063 Iustin Pop
    result = True
824 a8083063 Iustin Pop
  return result
825 a8083063 Iustin Pop
826 a8083063 Iustin Pop
827 3f78eef2 Iustin Pop
def AssembleBlockDevice(disk, owner, as_primary):
828 a8083063 Iustin Pop
  """Activate a block device for an instance.
829 a8083063 Iustin Pop

830 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
831 a8083063 Iustin Pop

832 a8083063 Iustin Pop
  Returns:
833 a8083063 Iustin Pop
    a /dev path for primary nodes
834 a8083063 Iustin Pop
    True for secondary nodes
835 a8083063 Iustin Pop

836 a8083063 Iustin Pop
  """
837 3f78eef2 Iustin Pop
  result = _RecursiveAssembleBD(disk, owner, as_primary)
838 a8083063 Iustin Pop
  if isinstance(result, bdev.BlockDev):
839 a8083063 Iustin Pop
    result = result.dev_path
840 a8083063 Iustin Pop
  return result
841 a8083063 Iustin Pop
842 a8083063 Iustin Pop
843 a8083063 Iustin Pop
def ShutdownBlockDevice(disk):
844 a8083063 Iustin Pop
  """Shut down a block device.
845 a8083063 Iustin Pop

846 a8083063 Iustin Pop
  First, if the device is assembled (can `Attach()`), then the device
847 a8083063 Iustin Pop
  is shutdown. Then the children of the device are shutdown.
848 a8083063 Iustin Pop

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

853 a8083063 Iustin Pop
  """
854 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
855 a8083063 Iustin Pop
  if r_dev is not None:
856 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
857 a8083063 Iustin Pop
    result = r_dev.Shutdown()
858 3f78eef2 Iustin Pop
    if result:
859 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
860 a8083063 Iustin Pop
  else:
861 a8083063 Iustin Pop
    result = True
862 a8083063 Iustin Pop
  if disk.children:
863 a8083063 Iustin Pop
    for child in disk.children:
864 a8083063 Iustin Pop
      result = result and ShutdownBlockDevice(child)
865 a8083063 Iustin Pop
  return result
866 a8083063 Iustin Pop
867 a8083063 Iustin Pop
868 153d9724 Iustin Pop
def MirrorAddChildren(parent_cdev, new_cdevs):
869 153d9724 Iustin Pop
  """Extend a mirrored block device.
870 a8083063 Iustin Pop

871 a8083063 Iustin Pop
  """
872 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev, allow_partial=True)
873 153d9724 Iustin Pop
  if parent_bdev is None:
874 18682bca Iustin Pop
    logging.error("Can't find parent device")
875 a8083063 Iustin Pop
    return False
876 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
877 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
878 18682bca Iustin Pop
    logging.error("Can't find new device(s) to add: %s:%s",
879 18682bca Iustin Pop
                  new_bdevs, new_cdevs)
880 a8083063 Iustin Pop
    return False
881 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
882 a8083063 Iustin Pop
  return True
883 a8083063 Iustin Pop
884 a8083063 Iustin Pop
885 153d9724 Iustin Pop
def MirrorRemoveChildren(parent_cdev, new_cdevs):
886 153d9724 Iustin Pop
  """Shrink a mirrored block device.
887 a8083063 Iustin Pop

888 a8083063 Iustin Pop
  """
889 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
890 153d9724 Iustin Pop
  if parent_bdev is None:
891 18682bca Iustin Pop
    logging.error("Can't find parent in remove children: %s", parent_cdev)
892 a8083063 Iustin Pop
    return False
893 e739bd57 Iustin Pop
  devs = []
894 e739bd57 Iustin Pop
  for disk in new_cdevs:
895 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
896 e739bd57 Iustin Pop
    if rpath is None:
897 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
898 e739bd57 Iustin Pop
      if bd is None:
899 18682bca Iustin Pop
        logging.error("Can't find dynamic device %s while removing children",
900 18682bca Iustin Pop
                      disk)
901 e739bd57 Iustin Pop
        return False
902 e739bd57 Iustin Pop
      else:
903 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
904 e739bd57 Iustin Pop
    else:
905 e739bd57 Iustin Pop
      devs.append(rpath)
906 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
907 a8083063 Iustin Pop
  return True
908 a8083063 Iustin Pop
909 a8083063 Iustin Pop
910 a8083063 Iustin Pop
def GetMirrorStatus(disks):
911 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
912 a8083063 Iustin Pop

913 a8083063 Iustin Pop
  Args:
914 a8083063 Iustin Pop
    disks: list of `objects.Disk`
915 a8083063 Iustin Pop

916 a8083063 Iustin Pop
  Returns:
917 a8083063 Iustin Pop
    list of (mirror_done, estimated_time) tuples, which
918 a8083063 Iustin Pop
    are the result of bdev.BlockDevice.CombinedSyncStatus()
919 a8083063 Iustin Pop

920 a8083063 Iustin Pop
  """
921 a8083063 Iustin Pop
  stats = []
922 a8083063 Iustin Pop
  for dsk in disks:
923 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
924 a8083063 Iustin Pop
    if rbd is None:
925 3ecf6786 Iustin Pop
      raise errors.BlockDeviceError("Can't find device %s" % str(dsk))
926 a8083063 Iustin Pop
    stats.append(rbd.CombinedSyncStatus())
927 a8083063 Iustin Pop
  return stats
928 a8083063 Iustin Pop
929 a8083063 Iustin Pop
930 a8083063 Iustin Pop
def _RecursiveFindBD(disk, allow_partial=False):
931 a8083063 Iustin Pop
  """Check if a device is activated.
932 a8083063 Iustin Pop

933 a8083063 Iustin Pop
  If so, return informations about the real device.
934 a8083063 Iustin Pop

935 a8083063 Iustin Pop
  Args:
936 a8083063 Iustin Pop
    disk: the objects.Disk instance
937 a8083063 Iustin Pop
    allow_partial: don't abort the find if a child of the
938 a8083063 Iustin Pop
                   device can't be found; this is intended to be
939 a8083063 Iustin Pop
                   used when repairing mirrors
940 a8083063 Iustin Pop

941 a8083063 Iustin Pop
  Returns:
942 a8083063 Iustin Pop
    None if the device can't be found
943 a8083063 Iustin Pop
    otherwise the device instance
944 a8083063 Iustin Pop

945 a8083063 Iustin Pop
  """
946 a8083063 Iustin Pop
  children = []
947 a8083063 Iustin Pop
  if disk.children:
948 a8083063 Iustin Pop
    for chdisk in disk.children:
949 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
950 a8083063 Iustin Pop
951 a8083063 Iustin Pop
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children)
952 a8083063 Iustin Pop
953 a8083063 Iustin Pop
954 a8083063 Iustin Pop
def FindBlockDevice(disk):
955 a8083063 Iustin Pop
  """Check if a device is activated.
956 a8083063 Iustin Pop

957 a8083063 Iustin Pop
  If so, return informations about the real device.
958 a8083063 Iustin Pop

959 a8083063 Iustin Pop
  Args:
960 a8083063 Iustin Pop
    disk: the objects.Disk instance
961 a8083063 Iustin Pop
  Returns:
962 a8083063 Iustin Pop
    None if the device can't be found
963 a8083063 Iustin Pop
    (device_path, major, minor, sync_percent, estimated_time, is_degraded)
964 a8083063 Iustin Pop

965 a8083063 Iustin Pop
  """
966 a8083063 Iustin Pop
  rbd = _RecursiveFindBD(disk)
967 a8083063 Iustin Pop
  if rbd is None:
968 a8083063 Iustin Pop
    return rbd
969 0834c866 Iustin Pop
  return (rbd.dev_path, rbd.major, rbd.minor) + rbd.GetSyncStatus()
970 a8083063 Iustin Pop
971 a8083063 Iustin Pop
972 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
973 a8083063 Iustin Pop
  """Write a file to the filesystem.
974 a8083063 Iustin Pop

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

978 a8083063 Iustin Pop
  """
979 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
980 18682bca Iustin Pop
    logging.error("Filename passed to UploadFile is not absolute: '%s'",
981 18682bca Iustin Pop
                  file_name)
982 a8083063 Iustin Pop
    return False
983 a8083063 Iustin Pop
984 97628462 Iustin Pop
  allowed_files = [
985 97628462 Iustin Pop
    constants.CLUSTER_CONF_FILE,
986 97628462 Iustin Pop
    constants.ETC_HOSTS,
987 97628462 Iustin Pop
    constants.SSH_KNOWN_HOSTS_FILE,
988 90fae627 Guido Trotter
    constants.VNC_PASSWORD_FILE,
989 c3f0a12f Iustin Pop
    constants.JOB_QUEUE_SERIAL_FILE,
990 97628462 Iustin Pop
    ]
991 880478f8 Iustin Pop
  allowed_files.extend(ssconf.SimpleStore().GetFileList())
992 880478f8 Iustin Pop
  if file_name not in allowed_files:
993 18682bca Iustin Pop
    logging.error("Filename passed to UploadFile not in allowed"
994 18682bca Iustin Pop
                 " upload targets: '%s'", file_name)
995 a8083063 Iustin Pop
    return False
996 a8083063 Iustin Pop
997 41a57aab Michael Hanselmann
  utils.WriteFile(file_name, data=data, mode=mode, uid=uid, gid=gid,
998 41a57aab Michael Hanselmann
                  atime=atime, mtime=mtime)
999 a8083063 Iustin Pop
  return True
1000 a8083063 Iustin Pop
1001 386b57af Iustin Pop
1002 a8083063 Iustin Pop
def _ErrnoOrStr(err):
1003 a8083063 Iustin Pop
  """Format an EnvironmentError exception.
1004 a8083063 Iustin Pop

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

1009 a8083063 Iustin Pop
  """
1010 a8083063 Iustin Pop
  if hasattr(err, 'errno'):
1011 a8083063 Iustin Pop
    detail = errno.errorcode[err.errno]
1012 a8083063 Iustin Pop
  else:
1013 a8083063 Iustin Pop
    detail = str(err)
1014 a8083063 Iustin Pop
  return detail
1015 a8083063 Iustin Pop
1016 5d0fe286 Iustin Pop
1017 c26dabd7 Guido Trotter
def _OSOndiskVersion(name, os_dir):
1018 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
1019 a8083063 Iustin Pop

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

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

1026 a8083063 Iustin Pop
  """
1027 a8083063 Iustin Pop
  api_file = os.path.sep.join([os_dir, "ganeti_api_version"])
1028 a8083063 Iustin Pop
1029 a8083063 Iustin Pop
  try:
1030 a8083063 Iustin Pop
    st = os.stat(api_file)
1031 a8083063 Iustin Pop
  except EnvironmentError, err:
1032 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "'ganeti_api_version' file not"
1033 3ecf6786 Iustin Pop
                           " found (%s)" % _ErrnoOrStr(err))
1034 a8083063 Iustin Pop
1035 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1036 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "'ganeti_api_version' file is not"
1037 3ecf6786 Iustin Pop
                           " a regular file")
1038 a8083063 Iustin Pop
1039 a8083063 Iustin Pop
  try:
1040 a8083063 Iustin Pop
    f = open(api_file)
1041 a8083063 Iustin Pop
    try:
1042 a8083063 Iustin Pop
      api_version = f.read(256)
1043 a8083063 Iustin Pop
    finally:
1044 a8083063 Iustin Pop
      f.close()
1045 a8083063 Iustin Pop
  except EnvironmentError, err:
1046 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "error while reading the"
1047 3ecf6786 Iustin Pop
                           " API version (%s)" % _ErrnoOrStr(err))
1048 a8083063 Iustin Pop
1049 a8083063 Iustin Pop
  api_version = api_version.strip()
1050 a8083063 Iustin Pop
  try:
1051 a8083063 Iustin Pop
    api_version = int(api_version)
1052 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
1053 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir,
1054 305a7297 Guido Trotter
                           "API version is not integer (%s)" % str(err))
1055 a8083063 Iustin Pop
1056 a8083063 Iustin Pop
  return api_version
1057 a8083063 Iustin Pop
1058 386b57af Iustin Pop
1059 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
1060 a8083063 Iustin Pop
  """Compute the validity for all OSes.
1061 a8083063 Iustin Pop

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

1065 a8083063 Iustin Pop
  Returns:
1066 8fa42c7c Guido Trotter
    list of OS objects
1067 a8083063 Iustin Pop

1068 a8083063 Iustin Pop
  """
1069 7c3d51d4 Guido Trotter
  if top_dirs is None:
1070 7c3d51d4 Guido Trotter
    top_dirs = constants.OS_SEARCH_PATH
1071 a8083063 Iustin Pop
1072 a8083063 Iustin Pop
  result = []
1073 65fe4693 Iustin Pop
  for dir_name in top_dirs:
1074 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
1075 7c3d51d4 Guido Trotter
      try:
1076 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
1077 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
1078 18682bca Iustin Pop
        logging.exception("Can't list the OS directory %s", dir_name)
1079 7c3d51d4 Guido Trotter
        break
1080 7c3d51d4 Guido Trotter
      for name in f_names:
1081 7c3d51d4 Guido Trotter
        try:
1082 65fe4693 Iustin Pop
          os_inst = OSFromDisk(name, base_dir=dir_name)
1083 7c3d51d4 Guido Trotter
          result.append(os_inst)
1084 7c3d51d4 Guido Trotter
        except errors.InvalidOS, err:
1085 8fa42c7c Guido Trotter
          result.append(objects.OS.FromInvalidOS(err))
1086 a8083063 Iustin Pop
1087 a8083063 Iustin Pop
  return result
1088 a8083063 Iustin Pop
1089 a8083063 Iustin Pop
1090 56bcd3f4 Guido Trotter
def OSFromDisk(name, base_dir=None):
1091 a8083063 Iustin Pop
  """Create an OS instance from disk.
1092 a8083063 Iustin Pop

1093 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
1094 a8083063 Iustin Pop
  valid OS name. Otherwise, it will raise an appropriate
1095 a8083063 Iustin Pop
  `errors.InvalidOS` exception, detailing why this is not a valid
1096 a8083063 Iustin Pop
  OS.
1097 a8083063 Iustin Pop

1098 7c3d51d4 Guido Trotter
  Args:
1099 7c3d51d4 Guido Trotter
    os_dir: Directory containing the OS scripts. Defaults to a search
1100 7c3d51d4 Guido Trotter
            in all the OS_SEARCH_PATH directories.
1101 7c3d51d4 Guido Trotter

1102 a8083063 Iustin Pop
  """
1103 7c3d51d4 Guido Trotter
1104 56bcd3f4 Guido Trotter
  if base_dir is None:
1105 57c177af Iustin Pop
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1106 c34c0cfd Iustin Pop
    if os_dir is None:
1107 c34c0cfd Iustin Pop
      raise errors.InvalidOS(name, None, "OS dir not found in search path")
1108 c34c0cfd Iustin Pop
  else:
1109 c34c0cfd Iustin Pop
    os_dir = os.path.sep.join([base_dir, name])
1110 a8083063 Iustin Pop
1111 c26dabd7 Guido Trotter
  api_version = _OSOndiskVersion(name, os_dir)
1112 a8083063 Iustin Pop
1113 a8083063 Iustin Pop
  if api_version != constants.OS_API_VERSION:
1114 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "API version mismatch"
1115 305a7297 Guido Trotter
                           " (found %s want %s)"
1116 3ecf6786 Iustin Pop
                           % (api_version, constants.OS_API_VERSION))
1117 a8083063 Iustin Pop
1118 a8083063 Iustin Pop
  # OS Scripts dictionary, we will populate it with the actual script names
1119 386b57af Iustin Pop
  os_scripts = {'create': '', 'export': '', 'import': '', 'rename': ''}
1120 a8083063 Iustin Pop
1121 a8083063 Iustin Pop
  for script in os_scripts:
1122 a8083063 Iustin Pop
    os_scripts[script] = os.path.sep.join([os_dir, script])
1123 a8083063 Iustin Pop
1124 a8083063 Iustin Pop
    try:
1125 a8083063 Iustin Pop
      st = os.stat(os_scripts[script])
1126 a8083063 Iustin Pop
    except EnvironmentError, err:
1127 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' script missing (%s)" %
1128 3ecf6786 Iustin Pop
                             (script, _ErrnoOrStr(err)))
1129 a8083063 Iustin Pop
1130 a8083063 Iustin Pop
    if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1131 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' script not executable" %
1132 305a7297 Guido Trotter
                             script)
1133 a8083063 Iustin Pop
1134 a8083063 Iustin Pop
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1135 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' is not a regular file" %
1136 305a7297 Guido Trotter
                             script)
1137 a8083063 Iustin Pop
1138 a8083063 Iustin Pop
1139 8fa42c7c Guido Trotter
  return objects.OS(name=name, path=os_dir, status=constants.OS_VALID_STATUS,
1140 a8083063 Iustin Pop
                    create_script=os_scripts['create'],
1141 a8083063 Iustin Pop
                    export_script=os_scripts['export'],
1142 a8083063 Iustin Pop
                    import_script=os_scripts['import'],
1143 386b57af Iustin Pop
                    rename_script=os_scripts['rename'],
1144 a8083063 Iustin Pop
                    api_version=api_version)
1145 a8083063 Iustin Pop
1146 a8083063 Iustin Pop
1147 594609c0 Iustin Pop
def GrowBlockDevice(disk, amount):
1148 594609c0 Iustin Pop
  """Grow a stack of block devices.
1149 594609c0 Iustin Pop

1150 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
1151 594609c0 Iustin Pop
  first one resize.
1152 594609c0 Iustin Pop

1153 594609c0 Iustin Pop
  Args:
1154 594609c0 Iustin Pop
    disk: the disk to be grown
1155 594609c0 Iustin Pop

1156 594609c0 Iustin Pop
  Returns: a tuple of (status, result), with:
1157 594609c0 Iustin Pop
    status: the result (true/false) of the operation
1158 594609c0 Iustin Pop
    result: the error message if the operation failed, otherwise not used
1159 594609c0 Iustin Pop

1160 594609c0 Iustin Pop
  """
1161 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1162 594609c0 Iustin Pop
  if r_dev is None:
1163 594609c0 Iustin Pop
    return False, "Cannot find block device %s" % (disk,)
1164 594609c0 Iustin Pop
1165 594609c0 Iustin Pop
  try:
1166 594609c0 Iustin Pop
    r_dev.Grow(amount)
1167 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
1168 594609c0 Iustin Pop
    return False, str(err)
1169 594609c0 Iustin Pop
1170 594609c0 Iustin Pop
  return True, None
1171 594609c0 Iustin Pop
1172 594609c0 Iustin Pop
1173 a8083063 Iustin Pop
def SnapshotBlockDevice(disk):
1174 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
1175 a8083063 Iustin Pop

1176 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
1177 a8083063 Iustin Pop
  just for the leaf lvm backend device.
1178 a8083063 Iustin Pop

1179 a8083063 Iustin Pop
  Args:
1180 a8083063 Iustin Pop
    disk: the disk to be snapshotted
1181 a8083063 Iustin Pop

1182 a8083063 Iustin Pop
  Returns:
1183 a8083063 Iustin Pop
    a config entry for the actual lvm device snapshotted.
1184 a8083063 Iustin Pop

1185 098c0958 Michael Hanselmann
  """
1186 a8083063 Iustin Pop
  if disk.children:
1187 a8083063 Iustin Pop
    if len(disk.children) == 1:
1188 a8083063 Iustin Pop
      # only one child, let's recurse on it
1189 a8083063 Iustin Pop
      return SnapshotBlockDevice(disk.children[0])
1190 a8083063 Iustin Pop
    else:
1191 a8083063 Iustin Pop
      # more than one child, choose one that matches
1192 a8083063 Iustin Pop
      for child in disk.children:
1193 a8083063 Iustin Pop
        if child.size == disk.size:
1194 a8083063 Iustin Pop
          # return implies breaking the loop
1195 a8083063 Iustin Pop
          return SnapshotBlockDevice(child)
1196 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
1197 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
1198 a8083063 Iustin Pop
    if r_dev is not None:
1199 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
1200 a8083063 Iustin Pop
      return r_dev.Snapshot(disk.size)
1201 a8083063 Iustin Pop
    else:
1202 a8083063 Iustin Pop
      return None
1203 a8083063 Iustin Pop
  else:
1204 3ecf6786 Iustin Pop
    raise errors.ProgrammerError("Cannot snapshot non-lvm block device"
1205 f4bc1f2c Michael Hanselmann
                                 " '%s' of type '%s'" %
1206 3ecf6786 Iustin Pop
                                 (disk.unique_id, disk.dev_type))
1207 a8083063 Iustin Pop
1208 a8083063 Iustin Pop
1209 a8083063 Iustin Pop
def ExportSnapshot(disk, dest_node, instance):
1210 a8083063 Iustin Pop
  """Export a block device snapshot to a remote node.
1211 a8083063 Iustin Pop

1212 a8083063 Iustin Pop
  Args:
1213 a8083063 Iustin Pop
    disk: the snapshot block device
1214 a8083063 Iustin Pop
    dest_node: the node to send the image to
1215 a8083063 Iustin Pop
    instance: instance being exported
1216 a8083063 Iustin Pop

1217 a8083063 Iustin Pop
  Returns:
1218 a8083063 Iustin Pop
    True if successful, False otherwise.
1219 a8083063 Iustin Pop

1220 098c0958 Michael Hanselmann
  """
1221 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1222 a8083063 Iustin Pop
  export_script = inst_os.export_script
1223 a8083063 Iustin Pop
1224 a8083063 Iustin Pop
  logfile = "%s/exp-%s-%s-%s.log" % (constants.LOG_OS_DIR, inst_os.name,
1225 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
1226 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
1227 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
1228 a8083063 Iustin Pop
1229 a8083063 Iustin Pop
  real_os_dev = _RecursiveFindBD(disk)
1230 a8083063 Iustin Pop
  if real_os_dev is None:
1231 a8083063 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
1232 a8083063 Iustin Pop
                                  str(disk))
1233 a8083063 Iustin Pop
  real_os_dev.Open()
1234 a8083063 Iustin Pop
1235 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1236 a8083063 Iustin Pop
  destfile = disk.physical_id[1]
1237 a8083063 Iustin Pop
1238 a8083063 Iustin Pop
  # the target command is built out of three individual commands,
1239 a8083063 Iustin Pop
  # which are joined by pipes; we check each individual command for
1240 a8083063 Iustin Pop
  # valid parameters
1241 a8083063 Iustin Pop
1242 a8083063 Iustin Pop
  expcmd = utils.BuildShellCmd("cd %s; %s -i %s -b %s 2>%s", inst_os.path,
1243 a8083063 Iustin Pop
                               export_script, instance.name,
1244 a8083063 Iustin Pop
                               real_os_dev.dev_path, logfile)
1245 a8083063 Iustin Pop
1246 a8083063 Iustin Pop
  comprcmd = "gzip"
1247 a8083063 Iustin Pop
1248 72f0f7fd Iustin Pop
  destcmd = utils.BuildShellCmd("mkdir -p %s && cat > %s/%s",
1249 00003458 Guido Trotter
                                destdir, destdir, destfile)
1250 c92b310a Michael Hanselmann
  remotecmd = _GetSshRunner().BuildCmd(dest_node, constants.GANETI_RUNAS,
1251 c92b310a Michael Hanselmann
                                       destcmd)
1252 a8083063 Iustin Pop
1253 a8083063 Iustin Pop
  # all commands have been checked, so we're safe to combine them
1254 72f0f7fd Iustin Pop
  command = '|'.join([expcmd, comprcmd, utils.ShellQuoteArgs(remotecmd)])
1255 a8083063 Iustin Pop
1256 a8083063 Iustin Pop
  result = utils.RunCmd(command)
1257 a8083063 Iustin Pop
1258 a8083063 Iustin Pop
  if result.failed:
1259 18682bca Iustin Pop
    logging.error("os snapshot export command '%s' returned error: %s"
1260 18682bca Iustin Pop
                  " output: %s", command, result.fail_reason, result.output)
1261 a8083063 Iustin Pop
    return False
1262 a8083063 Iustin Pop
1263 a8083063 Iustin Pop
  return True
1264 a8083063 Iustin Pop
1265 a8083063 Iustin Pop
1266 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
1267 a8083063 Iustin Pop
  """Write out the export configuration information.
1268 a8083063 Iustin Pop

1269 a8083063 Iustin Pop
  Args:
1270 a8083063 Iustin Pop
    instance: instance configuration
1271 a8083063 Iustin Pop
    snap_disks: snapshot block devices
1272 a8083063 Iustin Pop

1273 a8083063 Iustin Pop
  Returns:
1274 a8083063 Iustin Pop
    False in case of error, True otherwise.
1275 a8083063 Iustin Pop

1276 098c0958 Michael Hanselmann
  """
1277 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1278 a8083063 Iustin Pop
  finaldestdir = os.path.join(constants.EXPORT_DIR, instance.name)
1279 a8083063 Iustin Pop
1280 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1281 a8083063 Iustin Pop
1282 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
1283 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'version', '0')
1284 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
1285 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'source', instance.primary_node)
1286 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'os', instance.os)
1287 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'compression', 'gzip')
1288 a8083063 Iustin Pop
1289 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
1290 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'name', instance.name)
1291 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'memory', '%d' % instance.memory)
1292 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'vcpus', '%d' % instance.vcpus)
1293 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
1294 66f93869 Manuel Franceschini
1295 66f93869 Manuel Franceschini
  nic_count = 0
1296 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
1297 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_mac' %
1298 a8083063 Iustin Pop
               nic_count, '%s' % nic.mac)
1299 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
1300 1cafd236 Guido Trotter
    config.set(constants.INISECT_INS, 'nic%d_bridge' % nic_count, '%s' % nic.bridge)
1301 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
1302 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_count)
1303 a8083063 Iustin Pop
1304 66f93869 Manuel Franceschini
  disk_count = 0
1305 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
1306 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
1307 a8083063 Iustin Pop
               ('%s' % disk.iv_name))
1308 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
1309 a8083063 Iustin Pop
               ('%s' % disk.physical_id[1]))
1310 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
1311 a8083063 Iustin Pop
               ('%d' % disk.size))
1312 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_count)
1313 a8083063 Iustin Pop
1314 a8083063 Iustin Pop
  cff = os.path.join(destdir, constants.EXPORT_CONF_FILE)
1315 a8083063 Iustin Pop
  cfo = open(cff, 'w')
1316 a8083063 Iustin Pop
  try:
1317 a8083063 Iustin Pop
    config.write(cfo)
1318 a8083063 Iustin Pop
  finally:
1319 a8083063 Iustin Pop
    cfo.close()
1320 a8083063 Iustin Pop
1321 a8083063 Iustin Pop
  shutil.rmtree(finaldestdir, True)
1322 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
1323 a8083063 Iustin Pop
1324 a8083063 Iustin Pop
  return True
1325 a8083063 Iustin Pop
1326 a8083063 Iustin Pop
1327 a8083063 Iustin Pop
def ExportInfo(dest):
1328 a8083063 Iustin Pop
  """Get export configuration information.
1329 a8083063 Iustin Pop

1330 a8083063 Iustin Pop
  Args:
1331 a8083063 Iustin Pop
    dest: directory containing the export
1332 a8083063 Iustin Pop

1333 a8083063 Iustin Pop
  Returns:
1334 a8083063 Iustin Pop
    A serializable config file containing the export info.
1335 a8083063 Iustin Pop

1336 a8083063 Iustin Pop
  """
1337 a8083063 Iustin Pop
  cff = os.path.join(dest, constants.EXPORT_CONF_FILE)
1338 a8083063 Iustin Pop
1339 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1340 a8083063 Iustin Pop
  config.read(cff)
1341 a8083063 Iustin Pop
1342 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
1343 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
1344 a8083063 Iustin Pop
    return None
1345 a8083063 Iustin Pop
1346 a8083063 Iustin Pop
  return config
1347 a8083063 Iustin Pop
1348 a8083063 Iustin Pop
1349 a8083063 Iustin Pop
def ImportOSIntoInstance(instance, os_disk, swap_disk, src_node, src_image):
1350 a8083063 Iustin Pop
  """Import an os image into an instance.
1351 a8083063 Iustin Pop

1352 a8083063 Iustin Pop
  Args:
1353 a8083063 Iustin Pop
    instance: the instance object
1354 a8083063 Iustin Pop
    os_disk: the instance-visible name of the os device
1355 a8083063 Iustin Pop
    swap_disk: the instance-visible name of the swap device
1356 a8083063 Iustin Pop
    src_node: node holding the source image
1357 a8083063 Iustin Pop
    src_image: path to the source image on src_node
1358 a8083063 Iustin Pop

1359 a8083063 Iustin Pop
  Returns:
1360 a8083063 Iustin Pop
    False in case of error, True otherwise.
1361 a8083063 Iustin Pop

1362 a8083063 Iustin Pop
  """
1363 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1364 a8083063 Iustin Pop
  import_script = inst_os.import_script
1365 a8083063 Iustin Pop
1366 9716fdce Iustin Pop
  os_device = instance.FindDisk(os_disk)
1367 9716fdce Iustin Pop
  if os_device is None:
1368 18682bca Iustin Pop
    logging.error("Can't find this device-visible name '%s'", os_disk)
1369 a8083063 Iustin Pop
    return False
1370 a8083063 Iustin Pop
1371 9716fdce Iustin Pop
  swap_device = instance.FindDisk(swap_disk)
1372 9716fdce Iustin Pop
  if swap_device is None:
1373 18682bca Iustin Pop
    logging.error("Can't find this device-visible name '%s'", swap_disk)
1374 a8083063 Iustin Pop
    return False
1375 a8083063 Iustin Pop
1376 a8083063 Iustin Pop
  real_os_dev = _RecursiveFindBD(os_device)
1377 a8083063 Iustin Pop
  if real_os_dev is None:
1378 3ecf6786 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
1379 3ecf6786 Iustin Pop
                                  str(os_device))
1380 a8083063 Iustin Pop
  real_os_dev.Open()
1381 a8083063 Iustin Pop
1382 a8083063 Iustin Pop
  real_swap_dev = _RecursiveFindBD(swap_device)
1383 a8083063 Iustin Pop
  if real_swap_dev is None:
1384 3ecf6786 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
1385 3ecf6786 Iustin Pop
                                  str(swap_device))
1386 a8083063 Iustin Pop
  real_swap_dev.Open()
1387 a8083063 Iustin Pop
1388 a8083063 Iustin Pop
  logfile = "%s/import-%s-%s-%s.log" % (constants.LOG_OS_DIR, instance.os,
1389 a8083063 Iustin Pop
                                        instance.name, int(time.time()))
1390 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
1391 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
1392 a8083063 Iustin Pop
1393 00003458 Guido Trotter
  destcmd = utils.BuildShellCmd('cat %s', src_image)
1394 c92b310a Michael Hanselmann
  remotecmd = _GetSshRunner().BuildCmd(src_node, constants.GANETI_RUNAS,
1395 c92b310a Michael Hanselmann
                                       destcmd)
1396 a8083063 Iustin Pop
1397 a8083063 Iustin Pop
  comprcmd = "gunzip"
1398 a8083063 Iustin Pop
  impcmd = utils.BuildShellCmd("(cd %s; %s -i %s -b %s -s %s &>%s)",
1399 a8083063 Iustin Pop
                               inst_os.path, import_script, instance.name,
1400 a8083063 Iustin Pop
                               real_os_dev.dev_path, real_swap_dev.dev_path,
1401 a8083063 Iustin Pop
                               logfile)
1402 a8083063 Iustin Pop
1403 72f0f7fd Iustin Pop
  command = '|'.join([utils.ShellQuoteArgs(remotecmd), comprcmd, impcmd])
1404 a8083063 Iustin Pop
1405 a8083063 Iustin Pop
  result = utils.RunCmd(command)
1406 a8083063 Iustin Pop
1407 a8083063 Iustin Pop
  if result.failed:
1408 18682bca Iustin Pop
    logging.error("os import command '%s' returned error: %s"
1409 18682bca Iustin Pop
                  " output: %s", command, result.fail_reason, result.output)
1410 a8083063 Iustin Pop
    return False
1411 a8083063 Iustin Pop
1412 a8083063 Iustin Pop
  return True
1413 a8083063 Iustin Pop
1414 a8083063 Iustin Pop
1415 a8083063 Iustin Pop
def ListExports():
1416 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
1417 098c0958 Michael Hanselmann

1418 a8083063 Iustin Pop
  """
1419 a8083063 Iustin Pop
  if os.path.isdir(constants.EXPORT_DIR):
1420 eedbda4b Michael Hanselmann
    return utils.ListVisibleFiles(constants.EXPORT_DIR)
1421 a8083063 Iustin Pop
  else:
1422 a8083063 Iustin Pop
    return []
1423 a8083063 Iustin Pop
1424 a8083063 Iustin Pop
1425 a8083063 Iustin Pop
def RemoveExport(export):
1426 a8083063 Iustin Pop
  """Remove an existing export from the node.
1427 a8083063 Iustin Pop

1428 a8083063 Iustin Pop
  Args:
1429 a8083063 Iustin Pop
    export: the name of the export to remove
1430 a8083063 Iustin Pop

1431 a8083063 Iustin Pop
  Returns:
1432 a8083063 Iustin Pop
    False in case of error, True otherwise.
1433 a8083063 Iustin Pop

1434 098c0958 Michael Hanselmann
  """
1435 a8083063 Iustin Pop
  target = os.path.join(constants.EXPORT_DIR, export)
1436 a8083063 Iustin Pop
1437 a8083063 Iustin Pop
  shutil.rmtree(target)
1438 a8083063 Iustin Pop
  # TODO: catch some of the relevant exceptions and provide a pretty
1439 a8083063 Iustin Pop
  # error message if rmtree fails.
1440 a8083063 Iustin Pop
1441 a8083063 Iustin Pop
  return True
1442 a8083063 Iustin Pop
1443 a8083063 Iustin Pop
1444 f3e513ad Iustin Pop
def RenameBlockDevices(devlist):
1445 f3e513ad Iustin Pop
  """Rename a list of block devices.
1446 f3e513ad Iustin Pop

1447 f3e513ad Iustin Pop
  The devlist argument is a list of tuples (disk, new_logical,
1448 f3e513ad Iustin Pop
  new_physical). The return value will be a combined boolean result
1449 f3e513ad Iustin Pop
  (True only if all renames succeeded).
1450 f3e513ad Iustin Pop

1451 f3e513ad Iustin Pop
  """
1452 f3e513ad Iustin Pop
  result = True
1453 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
1454 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
1455 f3e513ad Iustin Pop
    if dev is None:
1456 f3e513ad Iustin Pop
      result = False
1457 f3e513ad Iustin Pop
      continue
1458 f3e513ad Iustin Pop
    try:
1459 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
1460 f3e513ad Iustin Pop
      dev.Rename(unique_id)
1461 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
1462 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
1463 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
1464 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
1465 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
1466 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
1467 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
1468 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
1469 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
1470 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
1471 f3e513ad Iustin Pop
      result = False
1472 f3e513ad Iustin Pop
  return result
1473 f3e513ad Iustin Pop
1474 f3e513ad Iustin Pop
1475 778b75bb Manuel Franceschini
def _TransformFileStorageDir(file_storage_dir):
1476 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
1477 778b75bb Manuel Franceschini

1478 778b75bb Manuel Franceschini
  Checks wheter the given file_storage_dir is within the cluster-wide
1479 778b75bb Manuel Franceschini
  default file_storage_dir stored in SimpleStore. Only paths under that
1480 778b75bb Manuel Franceschini
  directory are allowed.
1481 778b75bb Manuel Franceschini

1482 778b75bb Manuel Franceschini
  Args:
1483 778b75bb Manuel Franceschini
    file_storage_dir: string with path
1484 d61cbe76 Iustin Pop

1485 778b75bb Manuel Franceschini
  Returns:
1486 778b75bb Manuel Franceschini
    normalized file_storage_dir (string) if valid, None otherwise
1487 778b75bb Manuel Franceschini

1488 778b75bb Manuel Franceschini
  """
1489 778b75bb Manuel Franceschini
  file_storage_dir = os.path.normpath(file_storage_dir)
1490 778b75bb Manuel Franceschini
  base_file_storage_dir = ssconf.SimpleStore().GetFileStorageDir()
1491 778b75bb Manuel Franceschini
  if (not os.path.commonprefix([file_storage_dir, base_file_storage_dir]) ==
1492 778b75bb Manuel Franceschini
      base_file_storage_dir):
1493 18682bca Iustin Pop
    logging.error("file storage directory '%s' is not under base file"
1494 18682bca Iustin Pop
                  " storage directory '%s'",
1495 18682bca Iustin Pop
                  file_storage_dir, base_file_storage_dir)
1496 778b75bb Manuel Franceschini
    return None
1497 778b75bb Manuel Franceschini
  return file_storage_dir
1498 778b75bb Manuel Franceschini
1499 778b75bb Manuel Franceschini
1500 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
1501 778b75bb Manuel Franceschini
  """Create file storage directory.
1502 778b75bb Manuel Franceschini

1503 778b75bb Manuel Franceschini
  Args:
1504 778b75bb Manuel Franceschini
    file_storage_dir: string containing the path
1505 778b75bb Manuel Franceschini

1506 778b75bb Manuel Franceschini
  Returns:
1507 778b75bb Manuel Franceschini
    tuple with first element a boolean indicating wheter dir
1508 778b75bb Manuel Franceschini
    creation was successful or not
1509 778b75bb Manuel Franceschini

1510 778b75bb Manuel Franceschini
  """
1511 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
1512 778b75bb Manuel Franceschini
  result = True,
1513 778b75bb Manuel Franceschini
  if not file_storage_dir:
1514 778b75bb Manuel Franceschini
    result = False,
1515 778b75bb Manuel Franceschini
  else:
1516 778b75bb Manuel Franceschini
    if os.path.exists(file_storage_dir):
1517 778b75bb Manuel Franceschini
      if not os.path.isdir(file_storage_dir):
1518 18682bca Iustin Pop
        logging.error("'%s' is not a directory", file_storage_dir)
1519 778b75bb Manuel Franceschini
        result = False,
1520 778b75bb Manuel Franceschini
    else:
1521 778b75bb Manuel Franceschini
      try:
1522 778b75bb Manuel Franceschini
        os.makedirs(file_storage_dir, 0750)
1523 778b75bb Manuel Franceschini
      except OSError, err:
1524 18682bca Iustin Pop
        logging.error("Cannot create file storage directory '%s': %s",
1525 18682bca Iustin Pop
                      file_storage_dir, err)
1526 778b75bb Manuel Franceschini
        result = False,
1527 778b75bb Manuel Franceschini
  return result
1528 778b75bb Manuel Franceschini
1529 778b75bb Manuel Franceschini
1530 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
1531 778b75bb Manuel Franceschini
  """Remove file storage directory.
1532 778b75bb Manuel Franceschini

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

1535 778b75bb Manuel Franceschini
  Args:
1536 778b75bb Manuel Franceschini
    file_storage_dir: string containing the path
1537 778b75bb Manuel Franceschini

1538 778b75bb Manuel Franceschini
  Returns:
1539 778b75bb Manuel Franceschini
    tuple with first element a boolean indicating wheter dir
1540 778b75bb Manuel Franceschini
    removal was successful or not
1541 778b75bb Manuel Franceschini

1542 778b75bb Manuel Franceschini
  """
1543 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
1544 778b75bb Manuel Franceschini
  result = True,
1545 778b75bb Manuel Franceschini
  if not file_storage_dir:
1546 778b75bb Manuel Franceschini
    result = False,
1547 778b75bb Manuel Franceschini
  else:
1548 778b75bb Manuel Franceschini
    if os.path.exists(file_storage_dir):
1549 778b75bb Manuel Franceschini
      if not os.path.isdir(file_storage_dir):
1550 18682bca Iustin Pop
        logging.error("'%s' is not a directory", file_storage_dir)
1551 778b75bb Manuel Franceschini
        result = False,
1552 778b75bb Manuel Franceschini
      # deletes dir only if empty, otherwise we want to return False
1553 778b75bb Manuel Franceschini
      try:
1554 778b75bb Manuel Franceschini
        os.rmdir(file_storage_dir)
1555 778b75bb Manuel Franceschini
      except OSError, err:
1556 18682bca Iustin Pop
        logging.exception("Cannot remove file storage directory '%s'",
1557 18682bca Iustin Pop
                          file_storage_dir)
1558 778b75bb Manuel Franceschini
        result = False,
1559 778b75bb Manuel Franceschini
  return result
1560 778b75bb Manuel Franceschini
1561 778b75bb Manuel Franceschini
1562 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
1563 778b75bb Manuel Franceschini
  """Rename the file storage directory.
1564 778b75bb Manuel Franceschini

1565 778b75bb Manuel Franceschini
  Args:
1566 778b75bb Manuel Franceschini
    old_file_storage_dir: string containing the old path
1567 778b75bb Manuel Franceschini
    new_file_storage_dir: string containing the new path
1568 778b75bb Manuel Franceschini

1569 778b75bb Manuel Franceschini
  Returns:
1570 778b75bb Manuel Franceschini
    tuple with first element a boolean indicating wheter dir
1571 778b75bb Manuel Franceschini
    rename was successful or not
1572 778b75bb Manuel Franceschini

1573 778b75bb Manuel Franceschini
  """
1574 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
1575 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
1576 778b75bb Manuel Franceschini
  result = True,
1577 778b75bb Manuel Franceschini
  if not old_file_storage_dir or not new_file_storage_dir:
1578 778b75bb Manuel Franceschini
    result = False,
1579 778b75bb Manuel Franceschini
  else:
1580 778b75bb Manuel Franceschini
    if not os.path.exists(new_file_storage_dir):
1581 778b75bb Manuel Franceschini
      if os.path.isdir(old_file_storage_dir):
1582 778b75bb Manuel Franceschini
        try:
1583 778b75bb Manuel Franceschini
          os.rename(old_file_storage_dir, new_file_storage_dir)
1584 778b75bb Manuel Franceschini
        except OSError, err:
1585 18682bca Iustin Pop
          logging.exception("Cannot rename '%s' to '%s'",
1586 18682bca Iustin Pop
                            old_file_storage_dir, new_file_storage_dir)
1587 778b75bb Manuel Franceschini
          result =  False,
1588 778b75bb Manuel Franceschini
      else:
1589 18682bca Iustin Pop
        logging.error("'%s' is not a directory", old_file_storage_dir)
1590 778b75bb Manuel Franceschini
        result = False,
1591 778b75bb Manuel Franceschini
    else:
1592 778b75bb Manuel Franceschini
      if os.path.exists(old_file_storage_dir):
1593 18682bca Iustin Pop
        logging.error("Cannot rename '%s' to '%s'. Both locations exist.",
1594 18682bca Iustin Pop
                      old_file_storage_dir, new_file_storage_dir)
1595 778b75bb Manuel Franceschini
        result = False,
1596 778b75bb Manuel Franceschini
  return result
1597 778b75bb Manuel Franceschini
1598 778b75bb Manuel Franceschini
1599 d61cbe76 Iustin Pop
def CloseBlockDevices(disks):
1600 d61cbe76 Iustin Pop
  """Closes the given block devices.
1601 d61cbe76 Iustin Pop

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

1604 d61cbe76 Iustin Pop
  """
1605 d61cbe76 Iustin Pop
  bdevs = []
1606 d61cbe76 Iustin Pop
  for cf in disks:
1607 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
1608 d61cbe76 Iustin Pop
    if rd is None:
1609 d61cbe76 Iustin Pop
      return (False, "Can't find device %s" % cf)
1610 d61cbe76 Iustin Pop
    bdevs.append(rd)
1611 d61cbe76 Iustin Pop
1612 d61cbe76 Iustin Pop
  msg = []
1613 d61cbe76 Iustin Pop
  for rd in bdevs:
1614 d61cbe76 Iustin Pop
    try:
1615 d61cbe76 Iustin Pop
      rd.Close()
1616 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
1617 d61cbe76 Iustin Pop
      msg.append(str(err))
1618 d61cbe76 Iustin Pop
  if msg:
1619 d61cbe76 Iustin Pop
    return (False, "Can't make devices secondary: %s" % ",".join(msg))
1620 d61cbe76 Iustin Pop
  else:
1621 d61cbe76 Iustin Pop
    return (True, "All devices secondary")
1622 d61cbe76 Iustin Pop
1623 d61cbe76 Iustin Pop
1624 a8083063 Iustin Pop
class HooksRunner(object):
1625 a8083063 Iustin Pop
  """Hook runner.
1626 a8083063 Iustin Pop

1627 a8083063 Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
1628 a8083063 Iustin Pop
  the master side.
1629 a8083063 Iustin Pop

1630 a8083063 Iustin Pop
  """
1631 a8083063 Iustin Pop
  RE_MASK = re.compile("^[a-zA-Z0-9_-]+$")
1632 a8083063 Iustin Pop
1633 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
1634 a8083063 Iustin Pop
    """Constructor for hooks runner.
1635 a8083063 Iustin Pop

1636 a8083063 Iustin Pop
    Args:
1637 a8083063 Iustin Pop
      - hooks_base_dir: if not None, this overrides the
1638 a8083063 Iustin Pop
        constants.HOOKS_BASE_DIR (useful for unittests)
1639 a8083063 Iustin Pop

1640 a8083063 Iustin Pop
    """
1641 a8083063 Iustin Pop
    if hooks_base_dir is None:
1642 a8083063 Iustin Pop
      hooks_base_dir = constants.HOOKS_BASE_DIR
1643 a8083063 Iustin Pop
    self._BASE_DIR = hooks_base_dir
1644 a8083063 Iustin Pop
1645 a8083063 Iustin Pop
  @staticmethod
1646 a8083063 Iustin Pop
  def ExecHook(script, env):
1647 a8083063 Iustin Pop
    """Exec one hook script.
1648 a8083063 Iustin Pop

1649 a8083063 Iustin Pop
    Args:
1650 a8083063 Iustin Pop
     - script: the full path to the script
1651 a8083063 Iustin Pop
     - env: the environment with which to exec the script
1652 a8083063 Iustin Pop

1653 a8083063 Iustin Pop
    """
1654 a8083063 Iustin Pop
    # exec the process using subprocess and log the output
1655 a8083063 Iustin Pop
    fdstdin = None
1656 a8083063 Iustin Pop
    try:
1657 a8083063 Iustin Pop
      fdstdin = open("/dev/null", "r")
1658 a8083063 Iustin Pop
      child = subprocess.Popen([script], stdin=fdstdin, stdout=subprocess.PIPE,
1659 a8083063 Iustin Pop
                               stderr=subprocess.STDOUT, close_fds=True,
1660 147af04d Iustin Pop
                               shell=False, cwd="/", env=env)
1661 a8083063 Iustin Pop
      output = ""
1662 a8083063 Iustin Pop
      try:
1663 a8083063 Iustin Pop
        output = child.stdout.read(4096)
1664 a8083063 Iustin Pop
        child.stdout.close()
1665 a8083063 Iustin Pop
      except EnvironmentError, err:
1666 a8083063 Iustin Pop
        output += "Hook script error: %s" % str(err)
1667 a8083063 Iustin Pop
1668 a8083063 Iustin Pop
      while True:
1669 a8083063 Iustin Pop
        try:
1670 a8083063 Iustin Pop
          result = child.wait()
1671 a8083063 Iustin Pop
          break
1672 a8083063 Iustin Pop
        except EnvironmentError, err:
1673 a8083063 Iustin Pop
          if err.errno == errno.EINTR:
1674 a8083063 Iustin Pop
            continue
1675 a8083063 Iustin Pop
          raise
1676 a8083063 Iustin Pop
    finally:
1677 a8083063 Iustin Pop
      # try not to leak fds
1678 a8083063 Iustin Pop
      for fd in (fdstdin, ):
1679 a8083063 Iustin Pop
        if fd is not None:
1680 a8083063 Iustin Pop
          try:
1681 a8083063 Iustin Pop
            fd.close()
1682 a8083063 Iustin Pop
          except EnvironmentError, err:
1683 a8083063 Iustin Pop
            # just log the error
1684 18682bca Iustin Pop
            #logging.exception("Error while closing fd %s", fd)
1685 a8083063 Iustin Pop
            pass
1686 a8083063 Iustin Pop
1687 a8083063 Iustin Pop
    return result == 0, output
1688 a8083063 Iustin Pop
1689 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
1690 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
1691 a8083063 Iustin Pop

1692 a8083063 Iustin Pop
    This method will not be usually overriden by child opcodes.
1693 a8083063 Iustin Pop

1694 a8083063 Iustin Pop
    """
1695 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
1696 a8083063 Iustin Pop
      suffix = "pre"
1697 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
1698 a8083063 Iustin Pop
      suffix = "post"
1699 a8083063 Iustin Pop
    else:
1700 3ecf6786 Iustin Pop
      raise errors.ProgrammerError("Unknown hooks phase: '%s'" % phase)
1701 a8083063 Iustin Pop
    rr = []
1702 a8083063 Iustin Pop
1703 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
1704 a8083063 Iustin Pop
    dir_name = "%s/%s" % (self._BASE_DIR, subdir)
1705 a8083063 Iustin Pop
    try:
1706 eedbda4b Michael Hanselmann
      dir_contents = utils.ListVisibleFiles(dir_name)
1707 a8083063 Iustin Pop
    except OSError, err:
1708 a8083063 Iustin Pop
      # must log
1709 a8083063 Iustin Pop
      return rr
1710 a8083063 Iustin Pop
1711 a8083063 Iustin Pop
    # we use the standard python sort order,
1712 a8083063 Iustin Pop
    # so 00name is the recommended naming scheme
1713 a8083063 Iustin Pop
    dir_contents.sort()
1714 a8083063 Iustin Pop
    for relname in dir_contents:
1715 a8083063 Iustin Pop
      fname = os.path.join(dir_name, relname)
1716 a8083063 Iustin Pop
      if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and
1717 a8083063 Iustin Pop
          self.RE_MASK.match(relname) is not None):
1718 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
1719 a8083063 Iustin Pop
        output = ""
1720 a8083063 Iustin Pop
      else:
1721 a8083063 Iustin Pop
        result, output = self.ExecHook(fname, env)
1722 a8083063 Iustin Pop
        if not result:
1723 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
1724 a8083063 Iustin Pop
        else:
1725 a8083063 Iustin Pop
          rrval = constants.HKR_SUCCESS
1726 a8083063 Iustin Pop
      rr.append(("%s/%s" % (subdir, relname), rrval, output))
1727 a8083063 Iustin Pop
1728 a8083063 Iustin Pop
    return rr
1729 3f78eef2 Iustin Pop
1730 3f78eef2 Iustin Pop
1731 8d528b7c Iustin Pop
class IAllocatorRunner(object):
1732 8d528b7c Iustin Pop
  """IAllocator runner.
1733 8d528b7c Iustin Pop

1734 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
1735 8d528b7c Iustin Pop
  the master side.
1736 8d528b7c Iustin Pop

1737 8d528b7c Iustin Pop
  """
1738 8d528b7c Iustin Pop
  def Run(self, name, idata):
1739 8d528b7c Iustin Pop
    """Run an iallocator script.
1740 8d528b7c Iustin Pop

1741 8d528b7c Iustin Pop
    Return value: tuple of:
1742 8d528b7c Iustin Pop
       - run status (one of the IARUN_ constants)
1743 8d528b7c Iustin Pop
       - stdout
1744 8d528b7c Iustin Pop
       - stderr
1745 8d528b7c Iustin Pop
       - fail reason (as from utils.RunResult)
1746 8d528b7c Iustin Pop

1747 8d528b7c Iustin Pop
    """
1748 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
1749 8d528b7c Iustin Pop
                                  os.path.isfile)
1750 8d528b7c Iustin Pop
    if alloc_script is None:
1751 8d528b7c Iustin Pop
      return (constants.IARUN_NOTFOUND, None, None, None)
1752 8d528b7c Iustin Pop
1753 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
1754 8d528b7c Iustin Pop
    try:
1755 8d528b7c Iustin Pop
      os.write(fd, idata)
1756 8d528b7c Iustin Pop
      os.close(fd)
1757 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
1758 8d528b7c Iustin Pop
      if result.failed:
1759 8d528b7c Iustin Pop
        return (constants.IARUN_FAILURE, result.stdout, result.stderr,
1760 8d528b7c Iustin Pop
                result.fail_reason)
1761 8d528b7c Iustin Pop
    finally:
1762 8d528b7c Iustin Pop
      os.unlink(fin_name)
1763 8d528b7c Iustin Pop
1764 8d528b7c Iustin Pop
    return (constants.IARUN_SUCCESS, result.stdout, result.stderr, None)
1765 8d528b7c Iustin Pop
1766 8d528b7c Iustin Pop
1767 3f78eef2 Iustin Pop
class DevCacheManager(object):
1768 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
1769 3f78eef2 Iustin Pop

1770 3f78eef2 Iustin Pop
  """
1771 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
1772 3f78eef2 Iustin Pop
  _ROOT_DIR = constants.BDEV_CACHE_DIR
1773 3f78eef2 Iustin Pop
1774 3f78eef2 Iustin Pop
  @classmethod
1775 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
1776 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
1777 3f78eef2 Iustin Pop

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

1781 3f78eef2 Iustin Pop
    """
1782 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
1783 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
1784 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
1785 3f78eef2 Iustin Pop
    fpath = "%s/bdev_%s" % (cls._ROOT_DIR, dev_path)
1786 3f78eef2 Iustin Pop
    return fpath
1787 3f78eef2 Iustin Pop
1788 3f78eef2 Iustin Pop
  @classmethod
1789 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
1790 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
1791 3f78eef2 Iustin Pop

1792 3f78eef2 Iustin Pop
    """
1793 cf5a8306 Iustin Pop
    if dev_path is None:
1794 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
1795 cf5a8306 Iustin Pop
      return
1796 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
1797 3f78eef2 Iustin Pop
    if on_primary:
1798 3f78eef2 Iustin Pop
      state = "primary"
1799 3f78eef2 Iustin Pop
    else:
1800 3f78eef2 Iustin Pop
      state = "secondary"
1801 3f78eef2 Iustin Pop
    if iv_name is None:
1802 3f78eef2 Iustin Pop
      iv_name = "not_visible"
1803 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
1804 3f78eef2 Iustin Pop
    try:
1805 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
1806 3f78eef2 Iustin Pop
    except EnvironmentError, err:
1807 18682bca Iustin Pop
      logging.exception("Can't update bdev cache for %s", dev_path)
1808 3f78eef2 Iustin Pop
1809 3f78eef2 Iustin Pop
  @classmethod
1810 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
1811 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
1812 3f78eef2 Iustin Pop

1813 3f78eef2 Iustin Pop
    """
1814 cf5a8306 Iustin Pop
    if dev_path is None:
1815 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
1816 cf5a8306 Iustin Pop
      return
1817 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
1818 3f78eef2 Iustin Pop
    try:
1819 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
1820 3f78eef2 Iustin Pop
    except EnvironmentError, err:
1821 18682bca Iustin Pop
      logging.exception("Can't update bdev cache for %s", dev_path)