Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ b9bddb6b

History | View | Annotate | Download (57.7 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 3b9e6a30 Iustin Pop
import tempfile
36 a8083063 Iustin Pop
37 a8083063 Iustin Pop
from ganeti import errors
38 a8083063 Iustin Pop
from ganeti import utils
39 a8083063 Iustin Pop
from ganeti import ssh
40 a8083063 Iustin Pop
from ganeti import hypervisor
41 a8083063 Iustin Pop
from ganeti import constants
42 a8083063 Iustin Pop
from ganeti import bdev
43 a8083063 Iustin Pop
from ganeti import objects
44 880478f8 Iustin Pop
from ganeti import ssconf
45 a8083063 Iustin Pop
46 a8083063 Iustin Pop
47 c657dcc9 Michael Hanselmann
def _GetConfig():
48 c657dcc9 Michael Hanselmann
  return ssconf.SimpleConfigReader()
49 c657dcc9 Michael Hanselmann
50 c657dcc9 Michael Hanselmann
51 62c9ec92 Iustin Pop
def _GetSshRunner(cluster_name):
52 62c9ec92 Iustin Pop
  return ssh.SshRunner(cluster_name)
53 c92b310a Michael Hanselmann
54 c92b310a Michael Hanselmann
55 76ab5558 Michael Hanselmann
def _CleanDirectory(path, exclude=[]):
56 76ab5558 Michael Hanselmann
  """Removes all regular files in a directory.
57 76ab5558 Michael Hanselmann

58 76ab5558 Michael Hanselmann
  @param exclude: List of files to be excluded.
59 76ab5558 Michael Hanselmann
  @type exclude: list
60 76ab5558 Michael Hanselmann

61 76ab5558 Michael Hanselmann
  """
62 3956cee1 Michael Hanselmann
  if not os.path.isdir(path):
63 3956cee1 Michael Hanselmann
    return
64 76ab5558 Michael Hanselmann
65 76ab5558 Michael Hanselmann
  # Normalize excluded paths
66 76ab5558 Michael Hanselmann
  exclude = [os.path.normpath(i) for i in exclude]
67 76ab5558 Michael Hanselmann
68 3956cee1 Michael Hanselmann
  for rel_name in utils.ListVisibleFiles(path):
69 76ab5558 Michael Hanselmann
    full_name = os.path.normpath(os.path.join(path, rel_name))
70 76ab5558 Michael Hanselmann
    if full_name in exclude:
71 76ab5558 Michael Hanselmann
      continue
72 3956cee1 Michael Hanselmann
    if os.path.isfile(full_name) and not os.path.islink(full_name):
73 3956cee1 Michael Hanselmann
      utils.RemoveFile(full_name)
74 3956cee1 Michael Hanselmann
75 3956cee1 Michael Hanselmann
76 1bc59f76 Michael Hanselmann
def JobQueuePurge():
77 24fc781f Michael Hanselmann
  """Removes job queue files and archived jobs
78 24fc781f Michael Hanselmann

79 24fc781f Michael Hanselmann
  """
80 1bc59f76 Michael Hanselmann
  _CleanDirectory(constants.QUEUE_DIR, exclude=[constants.JOB_QUEUE_LOCK_FILE])
81 24fc781f Michael Hanselmann
  _CleanDirectory(constants.JOB_QUEUE_ARCHIVE_DIR)
82 24fc781f Michael Hanselmann
83 24fc781f Michael Hanselmann
84 bd1e4562 Iustin Pop
def GetMasterInfo():
85 bd1e4562 Iustin Pop
  """Returns master information.
86 bd1e4562 Iustin Pop

87 bd1e4562 Iustin Pop
  This is an utility function to compute master information, either
88 bd1e4562 Iustin Pop
  for consumption here or from the node daemon.
89 bd1e4562 Iustin Pop

90 bd1e4562 Iustin Pop
  @rtype: tuple
91 bd1e4562 Iustin Pop
  @return: (master_netdev, master_ip, master_name)
92 b1b6ea87 Iustin Pop

93 b1b6ea87 Iustin Pop
  """
94 b1b6ea87 Iustin Pop
  try:
95 c657dcc9 Michael Hanselmann
    cfg = _GetConfig()
96 c657dcc9 Michael Hanselmann
    master_netdev = cfg.GetMasterNetdev()
97 c657dcc9 Michael Hanselmann
    master_ip = cfg.GetMasterIP()
98 c657dcc9 Michael Hanselmann
    master_node = cfg.GetMasterNode()
99 b1b6ea87 Iustin Pop
  except errors.ConfigurationError, err:
100 b1b6ea87 Iustin Pop
    logging.exception("Cluster configuration incomplete")
101 b1b6ea87 Iustin Pop
    return (None, None)
102 bd1e4562 Iustin Pop
  return (master_netdev, master_ip, master_node)
103 b1b6ea87 Iustin Pop
104 b1b6ea87 Iustin Pop
105 1c65840b Iustin Pop
def StartMaster(start_daemons):
106 a8083063 Iustin Pop
  """Activate local node as master node.
107 a8083063 Iustin Pop

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

113 a8083063 Iustin Pop
  """
114 b1b6ea87 Iustin Pop
  ok = True
115 bd1e4562 Iustin Pop
  master_netdev, master_ip, _ = GetMasterInfo()
116 b1b6ea87 Iustin Pop
  if not master_netdev:
117 a8083063 Iustin Pop
    return False
118 a8083063 Iustin Pop
119 b1b6ea87 Iustin Pop
  if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
120 b1b6ea87 Iustin Pop
    if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT,
121 b1b6ea87 Iustin Pop
                     source=constants.LOCALHOST_IP_ADDRESS):
122 b1b6ea87 Iustin Pop
      # we already have the ip:
123 b1b6ea87 Iustin Pop
      logging.debug("Already started")
124 b1b6ea87 Iustin Pop
    else:
125 b1b6ea87 Iustin Pop
      logging.error("Someone else has the master ip, not activating")
126 b1b6ea87 Iustin Pop
      ok = False
127 b1b6ea87 Iustin Pop
  else:
128 b1b6ea87 Iustin Pop
    result = utils.RunCmd(["ip", "address", "add", "%s/32" % master_ip,
129 b1b6ea87 Iustin Pop
                           "dev", master_netdev, "label",
130 b1b6ea87 Iustin Pop
                           "%s:0" % master_netdev])
131 b1b6ea87 Iustin Pop
    if result.failed:
132 b1b6ea87 Iustin Pop
      logging.error("Can't activate master IP: %s", result.output)
133 b1b6ea87 Iustin Pop
      ok = False
134 b1b6ea87 Iustin Pop
135 b1b6ea87 Iustin Pop
    result = utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev,
136 b1b6ea87 Iustin Pop
                           "-s", master_ip, master_ip])
137 b1b6ea87 Iustin Pop
    # we'll ignore the exit code of arping
138 b1b6ea87 Iustin Pop
139 b1b6ea87 Iustin Pop
  # and now start the master and rapi daemons
140 b1b6ea87 Iustin Pop
  if start_daemons:
141 b1b6ea87 Iustin Pop
    for daemon in 'ganeti-masterd', 'ganeti-rapi':
142 b1b6ea87 Iustin Pop
      result = utils.RunCmd([daemon])
143 b1b6ea87 Iustin Pop
      if result.failed:
144 b1b6ea87 Iustin Pop
        logging.error("Can't start daemon %s: %s", daemon, result.output)
145 b1b6ea87 Iustin Pop
        ok = False
146 b1b6ea87 Iustin Pop
  return ok
147 a8083063 Iustin Pop
148 a8083063 Iustin Pop
149 1c65840b Iustin Pop
def StopMaster(stop_daemons):
150 a8083063 Iustin Pop
  """Deactivate this node as master.
151 a8083063 Iustin Pop

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

156 a8083063 Iustin Pop
  """
157 bd1e4562 Iustin Pop
  master_netdev, master_ip, _ = GetMasterInfo()
158 b1b6ea87 Iustin Pop
  if not master_netdev:
159 b1b6ea87 Iustin Pop
    return False
160 a8083063 Iustin Pop
161 b1b6ea87 Iustin Pop
  result = utils.RunCmd(["ip", "address", "del", "%s/32" % master_ip,
162 b1b6ea87 Iustin Pop
                         "dev", master_netdev])
163 a8083063 Iustin Pop
  if result.failed:
164 3b9e6a30 Iustin Pop
    logging.error("Can't remove the master IP, error: %s", result.output)
165 b1b6ea87 Iustin Pop
    # but otherwise ignore the failure
166 b1b6ea87 Iustin Pop
167 b1b6ea87 Iustin Pop
  if stop_daemons:
168 b1b6ea87 Iustin Pop
    # stop/kill the rapi and the master daemon
169 b1b6ea87 Iustin Pop
    for daemon in constants.RAPI_PID, constants.MASTERD_PID:
170 b1b6ea87 Iustin Pop
      utils.KillProcess(utils.ReadPidFile(utils.DaemonPidFileName(daemon)))
171 a8083063 Iustin Pop
172 a8083063 Iustin Pop
  return True
173 a8083063 Iustin Pop
174 a8083063 Iustin Pop
175 9716fdce Iustin Pop
def AddNode(dsa, dsapub, rsa, rsapub, sshkey, sshpub):
176 7900ed01 Iustin Pop
  """Joins this node to the cluster.
177 a8083063 Iustin Pop

178 7900ed01 Iustin Pop
  This does the following:
179 7900ed01 Iustin Pop
      - updates the hostkeys of the machine (rsa and dsa)
180 7900ed01 Iustin Pop
      - adds the ssh private key to the user
181 7900ed01 Iustin Pop
      - adds the ssh public key to the users' authorized_keys file
182 a8083063 Iustin Pop

183 7900ed01 Iustin Pop
  """
184 70d9e3d8 Iustin Pop
  sshd_keys =  [(constants.SSH_HOST_RSA_PRIV, rsa, 0600),
185 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_RSA_PUB, rsapub, 0644),
186 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_DSA_PRIV, dsa, 0600),
187 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_DSA_PUB, dsapub, 0644)]
188 7900ed01 Iustin Pop
  for name, content, mode in sshd_keys:
189 70d9e3d8 Iustin Pop
    utils.WriteFile(name, data=content, mode=mode)
190 a8083063 Iustin Pop
191 70d9e3d8 Iustin Pop
  try:
192 70d9e3d8 Iustin Pop
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS,
193 70d9e3d8 Iustin Pop
                                                    mkdir=True)
194 70d9e3d8 Iustin Pop
  except errors.OpExecError, err:
195 18682bca Iustin Pop
    logging.exception("Error while processing user ssh files")
196 70d9e3d8 Iustin Pop
    return False
197 a8083063 Iustin Pop
198 70d9e3d8 Iustin Pop
  for name, content in [(priv_key, sshkey), (pub_key, sshpub)]:
199 70d9e3d8 Iustin Pop
    utils.WriteFile(name, data=content, mode=0600)
200 a8083063 Iustin Pop
201 70d9e3d8 Iustin Pop
  utils.AddAuthorizedKey(auth_keys, sshpub)
202 a8083063 Iustin Pop
203 f491c3a8 Michael Hanselmann
  utils.RunCmd([constants.SSH_INITD_SCRIPT, "restart"])
204 a8083063 Iustin Pop
205 a8083063 Iustin Pop
  return True
206 a8083063 Iustin Pop
207 a8083063 Iustin Pop
208 a8083063 Iustin Pop
def LeaveCluster():
209 a8083063 Iustin Pop
  """Cleans up the current node and prepares it to be removed from the cluster.
210 a8083063 Iustin Pop

211 a8083063 Iustin Pop
  """
212 f78346f5 Michael Hanselmann
  _CleanDirectory(constants.DATA_DIR)
213 1bc59f76 Michael Hanselmann
  JobQueuePurge()
214 f78346f5 Michael Hanselmann
215 70d9e3d8 Iustin Pop
  try:
216 70d9e3d8 Iustin Pop
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
217 18682bca Iustin Pop
  except errors.OpExecError:
218 18682bca Iustin Pop
    logging.exception("Error while processing ssh files")
219 7900ed01 Iustin Pop
    return
220 7900ed01 Iustin Pop
221 70d9e3d8 Iustin Pop
  f = open(pub_key, 'r')
222 a8083063 Iustin Pop
  try:
223 70d9e3d8 Iustin Pop
    utils.RemoveAuthorizedKey(auth_keys, f.read(8192))
224 a8083063 Iustin Pop
  finally:
225 a8083063 Iustin Pop
    f.close()
226 a8083063 Iustin Pop
227 70d9e3d8 Iustin Pop
  utils.RemoveFile(priv_key)
228 70d9e3d8 Iustin Pop
  utils.RemoveFile(pub_key)
229 a8083063 Iustin Pop
230 6d8b6238 Guido Trotter
  # Return a reassuring string to the caller, and quit
231 6d8b6238 Guido Trotter
  raise errors.QuitGanetiException(False, 'Shutdown scheduled')
232 6d8b6238 Guido Trotter
233 a8083063 Iustin Pop
234 e69d05fd Iustin Pop
def GetNodeInfo(vgname, hypervisor_type):
235 2f8598a5 Alexander Schreiber
  """Gives back a hash with different informations about the node.
236 a8083063 Iustin Pop

237 e69d05fd Iustin Pop
  @type vgname: C{string}
238 e69d05fd Iustin Pop
  @param vgname: the name of the volume group to ask for disk space information
239 e69d05fd Iustin Pop
  @type hypervisor_type: C{str}
240 e69d05fd Iustin Pop
  @param hypervisor_type: the name of the hypervisor to ask for
241 e69d05fd Iustin Pop
      memory information
242 e69d05fd Iustin Pop
  @rtype: C{dict}
243 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
244 e69d05fd Iustin Pop
      - vg_size is the size of the configured volume group in MiB
245 e69d05fd Iustin Pop
      - vg_free is the free size of the volume group in MiB
246 e69d05fd Iustin Pop
      - memory_dom0 is the memory allocated for domain0 in MiB
247 e69d05fd Iustin Pop
      - memory_free is the currently available (free) ram in MiB
248 e69d05fd Iustin Pop
      - memory_total is the total number of ram in MiB
249 a8083063 Iustin Pop

250 098c0958 Michael Hanselmann
  """
251 a8083063 Iustin Pop
  outputarray = {}
252 a8083063 Iustin Pop
  vginfo = _GetVGInfo(vgname)
253 a8083063 Iustin Pop
  outputarray['vg_size'] = vginfo['vg_size']
254 a8083063 Iustin Pop
  outputarray['vg_free'] = vginfo['vg_free']
255 a8083063 Iustin Pop
256 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
257 a8083063 Iustin Pop
  hyp_info = hyper.GetNodeInfo()
258 a8083063 Iustin Pop
  if hyp_info is not None:
259 a8083063 Iustin Pop
    outputarray.update(hyp_info)
260 a8083063 Iustin Pop
261 3ef10550 Michael Hanselmann
  f = open("/proc/sys/kernel/random/boot_id", 'r')
262 3ef10550 Michael Hanselmann
  try:
263 3ef10550 Michael Hanselmann
    outputarray["bootid"] = f.read(128).rstrip("\n")
264 3ef10550 Michael Hanselmann
  finally:
265 3ef10550 Michael Hanselmann
    f.close()
266 3ef10550 Michael Hanselmann
267 a8083063 Iustin Pop
  return outputarray
268 a8083063 Iustin Pop
269 a8083063 Iustin Pop
270 62c9ec92 Iustin Pop
def VerifyNode(what, cluster_name):
271 a8083063 Iustin Pop
  """Verify the status of the local node.
272 a8083063 Iustin Pop

273 e69d05fd Iustin Pop
  Based on the input L{what} parameter, various checks are done on the
274 e69d05fd Iustin Pop
  local node.
275 e69d05fd Iustin Pop

276 e69d05fd Iustin Pop
  If the I{filelist} key is present, this list of
277 e69d05fd Iustin Pop
  files is checksummed and the file/checksum pairs are returned.
278 e69d05fd Iustin Pop

279 e69d05fd Iustin Pop
  If the I{nodelist} key is present, we check that we have
280 e69d05fd Iustin Pop
  connectivity via ssh with the target nodes (and check the hostname
281 e69d05fd Iustin Pop
  report).
282 a8083063 Iustin Pop

283 e69d05fd Iustin Pop
  If the I{node-net-test} key is present, we check that we have
284 e69d05fd Iustin Pop
  connectivity to the given nodes via both primary IP and, if
285 e69d05fd Iustin Pop
  applicable, secondary IPs.
286 e69d05fd Iustin Pop

287 e69d05fd Iustin Pop
  @type what: C{dict}
288 e69d05fd Iustin Pop
  @param what: a dictionary of things to check:
289 e69d05fd Iustin Pop
      - filelist: list of files for which to compute checksums
290 e69d05fd Iustin Pop
      - nodelist: list of nodes we should check ssh communication with
291 e69d05fd Iustin Pop
      - node-net-test: list of nodes we should check node daemon port
292 e69d05fd Iustin Pop
        connectivity with
293 e69d05fd Iustin Pop
      - hypervisor: list with hypervisors to run the verify for
294 a8083063 Iustin Pop

295 a8083063 Iustin Pop

296 a8083063 Iustin Pop
  """
297 a8083063 Iustin Pop
  result = {}
298 a8083063 Iustin Pop
299 a8083063 Iustin Pop
  if 'hypervisor' in what:
300 e69d05fd Iustin Pop
    result['hypervisor'] = my_dict = {}
301 e69d05fd Iustin Pop
    for hv_name in what['hypervisor']:
302 e69d05fd Iustin Pop
      my_dict[hv_name] = hypervisor.GetHypervisor(hv_name).Verify()
303 a8083063 Iustin Pop
304 a8083063 Iustin Pop
  if 'filelist' in what:
305 a8083063 Iustin Pop
    result['filelist'] = utils.FingerprintFiles(what['filelist'])
306 a8083063 Iustin Pop
307 a8083063 Iustin Pop
  if 'nodelist' in what:
308 a8083063 Iustin Pop
    result['nodelist'] = {}
309 b544cfe0 Iustin Pop
    random.shuffle(what['nodelist'])
310 a8083063 Iustin Pop
    for node in what['nodelist']:
311 62c9ec92 Iustin Pop
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
312 a8083063 Iustin Pop
      if not success:
313 a8083063 Iustin Pop
        result['nodelist'][node] = message
314 9d4bfc96 Iustin Pop
  if 'node-net-test' in what:
315 9d4bfc96 Iustin Pop
    result['node-net-test'] = {}
316 9d4bfc96 Iustin Pop
    my_name = utils.HostInfo().name
317 9d4bfc96 Iustin Pop
    my_pip = my_sip = None
318 9d4bfc96 Iustin Pop
    for name, pip, sip in what['node-net-test']:
319 9d4bfc96 Iustin Pop
      if name == my_name:
320 9d4bfc96 Iustin Pop
        my_pip = pip
321 9d4bfc96 Iustin Pop
        my_sip = sip
322 9d4bfc96 Iustin Pop
        break
323 9d4bfc96 Iustin Pop
    if not my_pip:
324 9d4bfc96 Iustin Pop
      result['node-net-test'][my_name] = ("Can't find my own"
325 9d4bfc96 Iustin Pop
                                          " primary/secondary IP"
326 9d4bfc96 Iustin Pop
                                          " in the node list")
327 9d4bfc96 Iustin Pop
    else:
328 c657dcc9 Michael Hanselmann
      port = utils.GetNodeDaemonPort()
329 9d4bfc96 Iustin Pop
      for name, pip, sip in what['node-net-test']:
330 9d4bfc96 Iustin Pop
        fail = []
331 9d4bfc96 Iustin Pop
        if not utils.TcpPing(pip, port, source=my_pip):
332 9d4bfc96 Iustin Pop
          fail.append("primary")
333 9d4bfc96 Iustin Pop
        if sip != pip:
334 9d4bfc96 Iustin Pop
          if not utils.TcpPing(sip, port, source=my_sip):
335 9d4bfc96 Iustin Pop
            fail.append("secondary")
336 9d4bfc96 Iustin Pop
        if fail:
337 9d4bfc96 Iustin Pop
          result['node-net-test'][name] = ("failure using the %s"
338 9d4bfc96 Iustin Pop
                                           " interface(s)" %
339 9d4bfc96 Iustin Pop
                                           " and ".join(fail))
340 9d4bfc96 Iustin Pop
341 a8083063 Iustin Pop
  return result
342 a8083063 Iustin Pop
343 a8083063 Iustin Pop
344 a8083063 Iustin Pop
def GetVolumeList(vg_name):
345 a8083063 Iustin Pop
  """Compute list of logical volumes and their size.
346 a8083063 Iustin Pop

347 a8083063 Iustin Pop
  Returns:
348 cb2037a2 Iustin Pop
    dictionary of all partions (key) with their size (in MiB), inactive
349 cb2037a2 Iustin Pop
    and online status:
350 cb2037a2 Iustin Pop
    {'test1': ('20.06', True, True)}
351 a8083063 Iustin Pop

352 a8083063 Iustin Pop
  """
353 cb2037a2 Iustin Pop
  lvs = {}
354 cb2037a2 Iustin Pop
  sep = '|'
355 cb2037a2 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
356 cb2037a2 Iustin Pop
                         "--separator=%s" % sep,
357 cb2037a2 Iustin Pop
                         "-olv_name,lv_size,lv_attr", vg_name])
358 a8083063 Iustin Pop
  if result.failed:
359 18682bca Iustin Pop
    logging.error("Failed to list logical volumes, lvs output: %s",
360 18682bca Iustin Pop
                  result.output)
361 b63ed789 Iustin Pop
    return result.output
362 cb2037a2 Iustin Pop
363 df4c2628 Iustin Pop
  valid_line_re = re.compile("^ *([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
364 cb2037a2 Iustin Pop
  for line in result.stdout.splitlines():
365 df4c2628 Iustin Pop
    line = line.strip()
366 df4c2628 Iustin Pop
    match = valid_line_re.match(line)
367 df4c2628 Iustin Pop
    if not match:
368 18682bca Iustin Pop
      logging.error("Invalid line returned from lvs output: '%s'", line)
369 df4c2628 Iustin Pop
      continue
370 df4c2628 Iustin Pop
    name, size, attr = match.groups()
371 cb2037a2 Iustin Pop
    inactive = attr[4] == '-'
372 cb2037a2 Iustin Pop
    online = attr[5] == 'o'
373 cb2037a2 Iustin Pop
    lvs[name] = (size, inactive, online)
374 cb2037a2 Iustin Pop
375 cb2037a2 Iustin Pop
  return lvs
376 a8083063 Iustin Pop
377 a8083063 Iustin Pop
378 a8083063 Iustin Pop
def ListVolumeGroups():
379 2f8598a5 Alexander Schreiber
  """List the volume groups and their size.
380 a8083063 Iustin Pop

381 a8083063 Iustin Pop
  Returns:
382 a8083063 Iustin Pop
    Dictionary with keys volume name and values the size of the volume
383 a8083063 Iustin Pop

384 a8083063 Iustin Pop
  """
385 a8083063 Iustin Pop
  return utils.ListVolumeGroups()
386 a8083063 Iustin Pop
387 a8083063 Iustin Pop
388 dcb93971 Michael Hanselmann
def NodeVolumes():
389 dcb93971 Michael Hanselmann
  """List all volumes on this node.
390 dcb93971 Michael Hanselmann

391 dcb93971 Michael Hanselmann
  """
392 dcb93971 Michael Hanselmann
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
393 dcb93971 Michael Hanselmann
                         "--separator=|",
394 dcb93971 Michael Hanselmann
                         "--options=lv_name,lv_size,devices,vg_name"])
395 dcb93971 Michael Hanselmann
  if result.failed:
396 18682bca Iustin Pop
    logging.error("Failed to list logical volumes, lvs output: %s",
397 18682bca Iustin Pop
                  result.output)
398 dcb93971 Michael Hanselmann
    return {}
399 dcb93971 Michael Hanselmann
400 dcb93971 Michael Hanselmann
  def parse_dev(dev):
401 dcb93971 Michael Hanselmann
    if '(' in dev:
402 dcb93971 Michael Hanselmann
      return dev.split('(')[0]
403 dcb93971 Michael Hanselmann
    else:
404 dcb93971 Michael Hanselmann
      return dev
405 dcb93971 Michael Hanselmann
406 dcb93971 Michael Hanselmann
  def map_line(line):
407 dcb93971 Michael Hanselmann
    return {
408 dcb93971 Michael Hanselmann
      'name': line[0].strip(),
409 dcb93971 Michael Hanselmann
      'size': line[1].strip(),
410 dcb93971 Michael Hanselmann
      'dev': parse_dev(line[2].strip()),
411 dcb93971 Michael Hanselmann
      'vg': line[3].strip(),
412 dcb93971 Michael Hanselmann
    }
413 dcb93971 Michael Hanselmann
414 a17a7623 Iustin Pop
  return [map_line(line.split('|')) for line in result.stdout.splitlines()
415 a17a7623 Iustin Pop
          if line.count('|') >= 3]
416 dcb93971 Michael Hanselmann
417 dcb93971 Michael Hanselmann
418 a8083063 Iustin Pop
def BridgesExist(bridges_list):
419 2f8598a5 Alexander Schreiber
  """Check if a list of bridges exist on the current node.
420 a8083063 Iustin Pop

421 a8083063 Iustin Pop
  Returns:
422 a8083063 Iustin Pop
    True if all of them exist, false otherwise
423 a8083063 Iustin Pop

424 a8083063 Iustin Pop
  """
425 a8083063 Iustin Pop
  for bridge in bridges_list:
426 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
427 a8083063 Iustin Pop
      return False
428 a8083063 Iustin Pop
429 a8083063 Iustin Pop
  return True
430 a8083063 Iustin Pop
431 a8083063 Iustin Pop
432 e69d05fd Iustin Pop
def GetInstanceList(hypervisor_list):
433 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
434 a8083063 Iustin Pop

435 e69d05fd Iustin Pop
  @type hypervisor_list: list
436 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
437 e69d05fd Iustin Pop

438 e69d05fd Iustin Pop
  @rtype: list
439 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
440 e69d05fd Iustin Pop
             - instance1.example.com
441 e69d05fd Iustin Pop
             - instance2.example.com
442 a8083063 Iustin Pop

443 098c0958 Michael Hanselmann
  """
444 e69d05fd Iustin Pop
  results = []
445 e69d05fd Iustin Pop
  for hname in hypervisor_list:
446 e69d05fd Iustin Pop
    try:
447 e69d05fd Iustin Pop
      names = hypervisor.GetHypervisor(hname).ListInstances()
448 e69d05fd Iustin Pop
      results.extend(names)
449 e69d05fd Iustin Pop
    except errors.HypervisorError, err:
450 e69d05fd Iustin Pop
      logging.exception("Error enumerating instances for hypevisor %s", hname)
451 e69d05fd Iustin Pop
      # FIXME: should we somehow not propagate this to the master?
452 e69d05fd Iustin Pop
      raise
453 a8083063 Iustin Pop
454 e69d05fd Iustin Pop
  return results
455 a8083063 Iustin Pop
456 a8083063 Iustin Pop
457 e69d05fd Iustin Pop
def GetInstanceInfo(instance, hname):
458 2f8598a5 Alexander Schreiber
  """Gives back the informations about an instance as a dictionary.
459 a8083063 Iustin Pop

460 e69d05fd Iustin Pop
  @type instance: string
461 e69d05fd Iustin Pop
  @param instance: the instance name
462 e69d05fd Iustin Pop
  @type hname: string
463 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
464 a8083063 Iustin Pop

465 e69d05fd Iustin Pop
  @rtype: dict
466 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
467 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
468 e69d05fd Iustin Pop
      - state: xen state of instance (string)
469 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
470 a8083063 Iustin Pop

471 098c0958 Michael Hanselmann
  """
472 a8083063 Iustin Pop
  output = {}
473 a8083063 Iustin Pop
474 e69d05fd Iustin Pop
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
475 a8083063 Iustin Pop
  if iinfo is not None:
476 a8083063 Iustin Pop
    output['memory'] = iinfo[2]
477 a8083063 Iustin Pop
    output['state'] = iinfo[4]
478 a8083063 Iustin Pop
    output['time'] = iinfo[5]
479 a8083063 Iustin Pop
480 a8083063 Iustin Pop
  return output
481 a8083063 Iustin Pop
482 a8083063 Iustin Pop
483 e69d05fd Iustin Pop
def GetAllInstancesInfo(hypervisor_list):
484 a8083063 Iustin Pop
  """Gather data about all instances.
485 a8083063 Iustin Pop

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

490 e69d05fd Iustin Pop
  @type hypervisor_list: list
491 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
492 e69d05fd Iustin Pop

493 e69d05fd Iustin Pop
  @rtype: dict of dicts
494 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
495 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
496 e69d05fd Iustin Pop
      - state: xen state of instance (string)
497 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
498 e69d05fd Iustin Pop
      - vcpuus: the number of vcpus
499 a8083063 Iustin Pop

500 098c0958 Michael Hanselmann
  """
501 a8083063 Iustin Pop
  output = {}
502 a8083063 Iustin Pop
503 e69d05fd Iustin Pop
  for hname in hypervisor_list:
504 e69d05fd Iustin Pop
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
505 e69d05fd Iustin Pop
    if iinfo:
506 e69d05fd Iustin Pop
      for name, inst_id, memory, vcpus, state, times in iinfo:
507 e69d05fd Iustin Pop
        if name in output:
508 e69d05fd Iustin Pop
          raise errors.HypervisorError("Instance %s running duplicate" % name)
509 e69d05fd Iustin Pop
        output[name] = {
510 e69d05fd Iustin Pop
          'memory': memory,
511 e69d05fd Iustin Pop
          'vcpus': vcpus,
512 e69d05fd Iustin Pop
          'state': state,
513 e69d05fd Iustin Pop
          'time': times,
514 e69d05fd Iustin Pop
          }
515 a8083063 Iustin Pop
516 a8083063 Iustin Pop
  return output
517 a8083063 Iustin Pop
518 a8083063 Iustin Pop
519 a8083063 Iustin Pop
def AddOSToInstance(instance, os_disk, swap_disk):
520 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
521 a8083063 Iustin Pop

522 a8083063 Iustin Pop
  Args:
523 a8083063 Iustin Pop
    instance: the instance object
524 a8083063 Iustin Pop
    os_disk: the instance-visible name of the os device
525 a8083063 Iustin Pop
    swap_disk: the instance-visible name of the swap device
526 a8083063 Iustin Pop

527 a8083063 Iustin Pop
  """
528 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
529 a8083063 Iustin Pop
530 a8083063 Iustin Pop
  create_script = inst_os.create_script
531 a8083063 Iustin Pop
532 9716fdce Iustin Pop
  os_device = instance.FindDisk(os_disk)
533 9716fdce Iustin Pop
  if os_device is None:
534 18682bca Iustin Pop
    logging.error("Can't find this device-visible name '%s'", os_disk)
535 a8083063 Iustin Pop
    return False
536 a8083063 Iustin Pop
537 9716fdce Iustin Pop
  swap_device = instance.FindDisk(swap_disk)
538 9716fdce Iustin Pop
  if swap_device is None:
539 18682bca Iustin Pop
    logging.error("Can't find this device-visible name '%s'", swap_disk)
540 a8083063 Iustin Pop
    return False
541 a8083063 Iustin Pop
542 a8083063 Iustin Pop
  real_os_dev = _RecursiveFindBD(os_device)
543 a8083063 Iustin Pop
  if real_os_dev is None:
544 a8083063 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
545 a8083063 Iustin Pop
                                  str(os_device))
546 a8083063 Iustin Pop
  real_os_dev.Open()
547 a8083063 Iustin Pop
548 a8083063 Iustin Pop
  real_swap_dev = _RecursiveFindBD(swap_device)
549 a8083063 Iustin Pop
  if real_swap_dev is None:
550 a8083063 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
551 a8083063 Iustin Pop
                                  str(swap_device))
552 a8083063 Iustin Pop
  real_swap_dev.Open()
553 a8083063 Iustin Pop
554 a8083063 Iustin Pop
  logfile = "%s/add-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
555 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
556 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
557 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
558 a8083063 Iustin Pop
559 c20494cd Iustin Pop
  command = utils.BuildShellCmd("cd %s && %s -i %s -b %s -s %s &>%s",
560 a8083063 Iustin Pop
                                inst_os.path, create_script, instance.name,
561 a8083063 Iustin Pop
                                real_os_dev.dev_path, real_swap_dev.dev_path,
562 a8083063 Iustin Pop
                                logfile)
563 e69d05fd Iustin Pop
  env = {'HYPERVISOR': instance.hypervisor}
564 decd5f45 Iustin Pop
565 4f0afaf5 Guido Trotter
  result = utils.RunCmd(command, env=env)
566 decd5f45 Iustin Pop
  if result.failed:
567 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
568 18682bca Iustin Pop
                  " output: %s", command, result.fail_reason, logfile,
569 18682bca Iustin Pop
                  result.output)
570 decd5f45 Iustin Pop
    return False
571 decd5f45 Iustin Pop
572 decd5f45 Iustin Pop
  return True
573 decd5f45 Iustin Pop
574 decd5f45 Iustin Pop
575 decd5f45 Iustin Pop
def RunRenameInstance(instance, old_name, os_disk, swap_disk):
576 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
577 decd5f45 Iustin Pop

578 decd5f45 Iustin Pop
  Args:
579 decd5f45 Iustin Pop
    instance: the instance object
580 decd5f45 Iustin Pop
    old_name: the old name of the instance
581 decd5f45 Iustin Pop
    os_disk: the instance-visible name of the os device
582 decd5f45 Iustin Pop
    swap_disk: the instance-visible name of the swap device
583 decd5f45 Iustin Pop

584 decd5f45 Iustin Pop
  """
585 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
586 decd5f45 Iustin Pop
587 decd5f45 Iustin Pop
  script = inst_os.rename_script
588 decd5f45 Iustin Pop
589 decd5f45 Iustin Pop
  os_device = instance.FindDisk(os_disk)
590 decd5f45 Iustin Pop
  if os_device is None:
591 18682bca Iustin Pop
    logging.error("Can't find this device-visible name '%s'", os_disk)
592 decd5f45 Iustin Pop
    return False
593 decd5f45 Iustin Pop
594 decd5f45 Iustin Pop
  swap_device = instance.FindDisk(swap_disk)
595 decd5f45 Iustin Pop
  if swap_device is None:
596 18682bca Iustin Pop
    logging.error("Can't find this device-visible name '%s'", swap_disk)
597 decd5f45 Iustin Pop
    return False
598 decd5f45 Iustin Pop
599 decd5f45 Iustin Pop
  real_os_dev = _RecursiveFindBD(os_device)
600 decd5f45 Iustin Pop
  if real_os_dev is None:
601 decd5f45 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
602 decd5f45 Iustin Pop
                                  str(os_device))
603 decd5f45 Iustin Pop
  real_os_dev.Open()
604 decd5f45 Iustin Pop
605 decd5f45 Iustin Pop
  real_swap_dev = _RecursiveFindBD(swap_device)
606 decd5f45 Iustin Pop
  if real_swap_dev is None:
607 decd5f45 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
608 decd5f45 Iustin Pop
                                  str(swap_device))
609 decd5f45 Iustin Pop
  real_swap_dev.Open()
610 decd5f45 Iustin Pop
611 decd5f45 Iustin Pop
  logfile = "%s/rename-%s-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
612 decd5f45 Iustin Pop
                                           old_name,
613 decd5f45 Iustin Pop
                                           instance.name, int(time.time()))
614 decd5f45 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
615 decd5f45 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
616 decd5f45 Iustin Pop
617 decd5f45 Iustin Pop
  command = utils.BuildShellCmd("cd %s && %s -o %s -n %s -b %s -s %s &>%s",
618 decd5f45 Iustin Pop
                                inst_os.path, script, old_name, instance.name,
619 decd5f45 Iustin Pop
                                real_os_dev.dev_path, real_swap_dev.dev_path,
620 decd5f45 Iustin Pop
                                logfile)
621 a8083063 Iustin Pop
622 a8083063 Iustin Pop
  result = utils.RunCmd(command)
623 a8083063 Iustin Pop
624 a8083063 Iustin Pop
  if result.failed:
625 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
626 18682bca Iustin Pop
                  command, result.fail_reason, result.output)
627 a8083063 Iustin Pop
    return False
628 a8083063 Iustin Pop
629 a8083063 Iustin Pop
  return True
630 a8083063 Iustin Pop
631 a8083063 Iustin Pop
632 a8083063 Iustin Pop
def _GetVGInfo(vg_name):
633 a8083063 Iustin Pop
  """Get informations about the volume group.
634 a8083063 Iustin Pop

635 a8083063 Iustin Pop
  Args:
636 a8083063 Iustin Pop
    vg_name: the volume group
637 a8083063 Iustin Pop

638 a8083063 Iustin Pop
  Returns:
639 a8083063 Iustin Pop
    { 'vg_size' : xxx, 'vg_free' : xxx, 'pv_count' : xxx }
640 a8083063 Iustin Pop
    where
641 a8083063 Iustin Pop
    vg_size is the total size of the volume group in MiB
642 a8083063 Iustin Pop
    vg_free is the free size of the volume group in MiB
643 a8083063 Iustin Pop
    pv_count are the number of physical disks in that vg
644 a8083063 Iustin Pop

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

648 a8083063 Iustin Pop
  """
649 f4d377e7 Iustin Pop
  retdic = dict.fromkeys(["vg_size", "vg_free", "pv_count"])
650 f4d377e7 Iustin Pop
651 a8083063 Iustin Pop
  retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings",
652 a8083063 Iustin Pop
                         "--nosuffix", "--units=m", "--separator=:", vg_name])
653 a8083063 Iustin Pop
654 a8083063 Iustin Pop
  if retval.failed:
655 18682bca Iustin Pop
    logging.error("volume group %s not present", vg_name)
656 f4d377e7 Iustin Pop
    return retdic
657 d87ae7d2 Iustin Pop
  valarr = retval.stdout.strip().rstrip(':').split(':')
658 f4d377e7 Iustin Pop
  if len(valarr) == 3:
659 f4d377e7 Iustin Pop
    try:
660 f4d377e7 Iustin Pop
      retdic = {
661 f4d377e7 Iustin Pop
        "vg_size": int(round(float(valarr[0]), 0)),
662 f4d377e7 Iustin Pop
        "vg_free": int(round(float(valarr[1]), 0)),
663 f4d377e7 Iustin Pop
        "pv_count": int(valarr[2]),
664 f4d377e7 Iustin Pop
        }
665 f4d377e7 Iustin Pop
    except ValueError, err:
666 18682bca Iustin Pop
      logging.exception("Fail to parse vgs output")
667 f4d377e7 Iustin Pop
  else:
668 18682bca Iustin Pop
    logging.error("vgs output has the wrong number of fields (expected"
669 18682bca Iustin Pop
                  " three): %s", str(valarr))
670 a8083063 Iustin Pop
  return retdic
671 a8083063 Iustin Pop
672 a8083063 Iustin Pop
673 a8083063 Iustin Pop
def _GatherBlockDevs(instance):
674 a8083063 Iustin Pop
  """Set up an instance's block device(s).
675 a8083063 Iustin Pop

676 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
677 a8083063 Iustin Pop
  devices must be already assembled.
678 a8083063 Iustin Pop

679 a8083063 Iustin Pop
  """
680 a8083063 Iustin Pop
  block_devices = []
681 a8083063 Iustin Pop
  for disk in instance.disks:
682 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
683 a8083063 Iustin Pop
    if device is None:
684 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
685 a8083063 Iustin Pop
                                    str(disk))
686 a8083063 Iustin Pop
    device.Open()
687 a8083063 Iustin Pop
    block_devices.append((disk, device))
688 a8083063 Iustin Pop
  return block_devices
689 a8083063 Iustin Pop
690 a8083063 Iustin Pop
691 a8083063 Iustin Pop
def StartInstance(instance, extra_args):
692 a8083063 Iustin Pop
  """Start an instance.
693 a8083063 Iustin Pop

694 e69d05fd Iustin Pop
  @type instance: instance object
695 e69d05fd Iustin Pop
  @param instance: the instance object
696 e69d05fd Iustin Pop
  @rtype: boolean
697 e69d05fd Iustin Pop
  @return: whether the startup was successful or not
698 a8083063 Iustin Pop

699 098c0958 Michael Hanselmann
  """
700 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
701 a8083063 Iustin Pop
702 a8083063 Iustin Pop
  if instance.name in running_instances:
703 a8083063 Iustin Pop
    return True
704 a8083063 Iustin Pop
705 a8083063 Iustin Pop
  block_devices = _GatherBlockDevs(instance)
706 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
707 a8083063 Iustin Pop
708 a8083063 Iustin Pop
  try:
709 a8083063 Iustin Pop
    hyper.StartInstance(instance, block_devices, extra_args)
710 a8083063 Iustin Pop
  except errors.HypervisorError, err:
711 18682bca Iustin Pop
    logging.exception("Failed to start instance")
712 a8083063 Iustin Pop
    return False
713 a8083063 Iustin Pop
714 a8083063 Iustin Pop
  return True
715 a8083063 Iustin Pop
716 a8083063 Iustin Pop
717 a8083063 Iustin Pop
def ShutdownInstance(instance):
718 a8083063 Iustin Pop
  """Shut an instance down.
719 a8083063 Iustin Pop

720 e69d05fd Iustin Pop
  @type instance: instance object
721 e69d05fd Iustin Pop
  @param instance: the instance object
722 e69d05fd Iustin Pop
  @rtype: boolean
723 e69d05fd Iustin Pop
  @return: whether the startup was successful or not
724 a8083063 Iustin Pop

725 098c0958 Michael Hanselmann
  """
726 e69d05fd Iustin Pop
  hv_name = instance.hypervisor
727 e69d05fd Iustin Pop
  running_instances = GetInstanceList([hv_name])
728 a8083063 Iustin Pop
729 a8083063 Iustin Pop
  if instance.name not in running_instances:
730 a8083063 Iustin Pop
    return True
731 a8083063 Iustin Pop
732 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(hv_name)
733 a8083063 Iustin Pop
  try:
734 a8083063 Iustin Pop
    hyper.StopInstance(instance)
735 a8083063 Iustin Pop
  except errors.HypervisorError, err:
736 18682bca Iustin Pop
    logging.error("Failed to stop instance")
737 a8083063 Iustin Pop
    return False
738 a8083063 Iustin Pop
739 a8083063 Iustin Pop
  # test every 10secs for 2min
740 a8083063 Iustin Pop
  shutdown_ok = False
741 a8083063 Iustin Pop
742 a8083063 Iustin Pop
  time.sleep(1)
743 a8083063 Iustin Pop
  for dummy in range(11):
744 e69d05fd Iustin Pop
    if instance.name not in GetInstanceList([hv_name]):
745 a8083063 Iustin Pop
      break
746 a8083063 Iustin Pop
    time.sleep(10)
747 a8083063 Iustin Pop
  else:
748 a8083063 Iustin Pop
    # the shutdown did not succeed
749 18682bca Iustin Pop
    logging.error("shutdown of '%s' unsuccessful, using destroy", instance)
750 a8083063 Iustin Pop
751 a8083063 Iustin Pop
    try:
752 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
753 a8083063 Iustin Pop
    except errors.HypervisorError, err:
754 18682bca Iustin Pop
      logging.exception("Failed to stop instance")
755 a8083063 Iustin Pop
      return False
756 a8083063 Iustin Pop
757 a8083063 Iustin Pop
    time.sleep(1)
758 e69d05fd Iustin Pop
    if instance.name in GetInstanceList([hv_name]):
759 18682bca Iustin Pop
      logging.error("could not shutdown instance '%s' even by destroy",
760 18682bca Iustin Pop
                    instance.name)
761 a8083063 Iustin Pop
      return False
762 a8083063 Iustin Pop
763 a8083063 Iustin Pop
  return True
764 a8083063 Iustin Pop
765 a8083063 Iustin Pop
766 007a2f3e Alexander Schreiber
def RebootInstance(instance, reboot_type, extra_args):
767 007a2f3e Alexander Schreiber
  """Reboot an instance.
768 007a2f3e Alexander Schreiber

769 007a2f3e Alexander Schreiber
  Args:
770 007a2f3e Alexander Schreiber
    instance    - name of instance to reboot
771 007a2f3e Alexander Schreiber
    reboot_type - how to reboot [soft,hard,full]
772 007a2f3e Alexander Schreiber

773 007a2f3e Alexander Schreiber
  """
774 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
775 007a2f3e Alexander Schreiber
776 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
777 18682bca Iustin Pop
    logging.error("Cannot reboot instance that is not running")
778 007a2f3e Alexander Schreiber
    return False
779 007a2f3e Alexander Schreiber
780 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
781 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
782 007a2f3e Alexander Schreiber
    try:
783 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
784 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
785 18682bca Iustin Pop
      logging.exception("Failed to soft reboot instance")
786 007a2f3e Alexander Schreiber
      return False
787 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
788 007a2f3e Alexander Schreiber
    try:
789 007a2f3e Alexander Schreiber
      ShutdownInstance(instance)
790 007a2f3e Alexander Schreiber
      StartInstance(instance, extra_args)
791 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
792 18682bca Iustin Pop
      logging.exception("Failed to hard reboot instance")
793 007a2f3e Alexander Schreiber
      return False
794 007a2f3e Alexander Schreiber
  else:
795 007a2f3e Alexander Schreiber
    raise errors.ParameterError("reboot_type invalid")
796 007a2f3e Alexander Schreiber
797 007a2f3e Alexander Schreiber
  return True
798 007a2f3e Alexander Schreiber
799 007a2f3e Alexander Schreiber
800 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
801 2a10865c Iustin Pop
  """Migrates an instance to another node.
802 2a10865c Iustin Pop

803 9f0e6b37 Iustin Pop
  @type instance: C{objects.Instance}
804 9f0e6b37 Iustin Pop
  @param instance: the instance definition
805 9f0e6b37 Iustin Pop
  @type target: string
806 9f0e6b37 Iustin Pop
  @param target: the target node name
807 9f0e6b37 Iustin Pop
  @type live: boolean
808 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
809 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
810 9f0e6b37 Iustin Pop
  @rtype: tuple
811 9f0e6b37 Iustin Pop
  @return: a tuple of (success, msg) where:
812 9f0e6b37 Iustin Pop
      - succes is a boolean denoting the success/failure of the operation
813 9f0e6b37 Iustin Pop
      - msg is a string with details in case of failure
814 9f0e6b37 Iustin Pop

815 2a10865c Iustin Pop
  """
816 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor_name)
817 2a10865c Iustin Pop
818 2a10865c Iustin Pop
  try:
819 9f0e6b37 Iustin Pop
    hyper.MigrateInstance(instance.name, target, live)
820 2a10865c Iustin Pop
  except errors.HypervisorError, err:
821 2a10865c Iustin Pop
    msg = "Failed to migrate instance: %s" % str(err)
822 18682bca Iustin Pop
    logging.error(msg)
823 2a10865c Iustin Pop
    return (False, msg)
824 2a10865c Iustin Pop
  return (True, "Migration successfull")
825 2a10865c Iustin Pop
826 2a10865c Iustin Pop
827 3f78eef2 Iustin Pop
def CreateBlockDevice(disk, size, owner, on_primary, info):
828 a8083063 Iustin Pop
  """Creates a block device for an instance.
829 a8083063 Iustin Pop

830 a8083063 Iustin Pop
  Args:
831 c99a3cc0 Manuel Franceschini
   disk: a ganeti.objects.Disk object
832 c99a3cc0 Manuel Franceschini
   size: the size of the physical underlying device
833 c99a3cc0 Manuel Franceschini
   owner: a string with the name of the instance
834 6c8af3d0 Manuel Franceschini
   on_primary: a boolean indicating if it is the primary node or not
835 6c8af3d0 Manuel Franceschini
   info: string that will be sent to the physical device creation
836 a8083063 Iustin Pop

837 a8083063 Iustin Pop
  Returns:
838 a8083063 Iustin Pop
    the new unique_id of the device (this can sometime be
839 a8083063 Iustin Pop
    computed only after creation), or None. On secondary nodes,
840 a8083063 Iustin Pop
    it's not required to return anything.
841 a8083063 Iustin Pop

842 a8083063 Iustin Pop
  """
843 a8083063 Iustin Pop
  clist = []
844 a8083063 Iustin Pop
  if disk.children:
845 a8083063 Iustin Pop
    for child in disk.children:
846 3f78eef2 Iustin Pop
      crdev = _RecursiveAssembleBD(child, owner, on_primary)
847 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
848 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
849 a8083063 Iustin Pop
        # be assembled
850 a8083063 Iustin Pop
        crdev.Open()
851 a8083063 Iustin Pop
      clist.append(crdev)
852 a8083063 Iustin Pop
  try:
853 a8083063 Iustin Pop
    device = bdev.FindDevice(disk.dev_type, disk.physical_id, clist)
854 a8083063 Iustin Pop
    if device is not None:
855 18682bca Iustin Pop
      logging.info("removing existing device %s", disk)
856 a8083063 Iustin Pop
      device.Remove()
857 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
858 a8083063 Iustin Pop
    pass
859 a8083063 Iustin Pop
860 a8083063 Iustin Pop
  device = bdev.Create(disk.dev_type, disk.physical_id,
861 a8083063 Iustin Pop
                       clist, size)
862 a8083063 Iustin Pop
  if device is None:
863 a8083063 Iustin Pop
    raise ValueError("Can't create child device for %s, %s" %
864 a8083063 Iustin Pop
                     (disk, size))
865 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
866 cf5a8306 Iustin Pop
    if not device.Assemble():
867 20a0c9ef Guido Trotter
      errorstring = "Can't assemble device after creation"
868 18682bca Iustin Pop
      logging.error(errorstring)
869 20a0c9ef Guido Trotter
      raise errors.BlockDeviceError("%s, very unusual event - check the node"
870 20a0c9ef Guido Trotter
                                    " daemon logs" % errorstring)
871 e31c43f7 Michael Hanselmann
    device.SetSyncSpeed(constants.SYNC_SPEED)
872 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
873 a8083063 Iustin Pop
      device.Open(force=True)
874 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
875 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
876 a0c3fea1 Michael Hanselmann
877 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
878 a0c3fea1 Michael Hanselmann
879 a8083063 Iustin Pop
  physical_id = device.unique_id
880 a8083063 Iustin Pop
  return physical_id
881 a8083063 Iustin Pop
882 a8083063 Iustin Pop
883 a8083063 Iustin Pop
def RemoveBlockDevice(disk):
884 a8083063 Iustin Pop
  """Remove a block device.
885 a8083063 Iustin Pop

886 a8083063 Iustin Pop
  This is intended to be called recursively.
887 a8083063 Iustin Pop

888 a8083063 Iustin Pop
  """
889 a8083063 Iustin Pop
  try:
890 a8083063 Iustin Pop
    # since we are removing the device, allow a partial match
891 a8083063 Iustin Pop
    # this allows removal of broken mirrors
892 a8083063 Iustin Pop
    rdev = _RecursiveFindBD(disk, allow_partial=True)
893 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
894 a8083063 Iustin Pop
    # probably can't attach
895 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
896 a8083063 Iustin Pop
    rdev = None
897 a8083063 Iustin Pop
  if rdev is not None:
898 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
899 a8083063 Iustin Pop
    result = rdev.Remove()
900 3f78eef2 Iustin Pop
    if result:
901 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
902 a8083063 Iustin Pop
  else:
903 a8083063 Iustin Pop
    result = True
904 a8083063 Iustin Pop
  if disk.children:
905 a8083063 Iustin Pop
    for child in disk.children:
906 a8083063 Iustin Pop
      result = result and RemoveBlockDevice(child)
907 a8083063 Iustin Pop
  return result
908 a8083063 Iustin Pop
909 a8083063 Iustin Pop
910 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
911 a8083063 Iustin Pop
  """Activate a block device for an instance.
912 a8083063 Iustin Pop

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

915 a8083063 Iustin Pop
  This function is called recursively.
916 a8083063 Iustin Pop

917 a8083063 Iustin Pop
  Args:
918 a8083063 Iustin Pop
    disk: a objects.Disk object
919 a8083063 Iustin Pop
    as_primary: if we should make the block device read/write
920 a8083063 Iustin Pop

921 a8083063 Iustin Pop
  Returns:
922 a8083063 Iustin Pop
    the assembled device or None (in case no device was assembled)
923 a8083063 Iustin Pop

924 a8083063 Iustin Pop
  If the assembly is not successful, an exception is raised.
925 a8083063 Iustin Pop

926 a8083063 Iustin Pop
  """
927 a8083063 Iustin Pop
  children = []
928 a8083063 Iustin Pop
  if disk.children:
929 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
930 fc1dc9d7 Iustin Pop
    if mcn == -1:
931 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
932 fc1dc9d7 Iustin Pop
    else:
933 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
934 a8083063 Iustin Pop
    for chld_disk in disk.children:
935 fc1dc9d7 Iustin Pop
      try:
936 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
937 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
938 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
939 fc1dc9d7 Iustin Pop
          raise
940 fc1dc9d7 Iustin Pop
        cdev = None
941 18682bca Iustin Pop
        logging.debug("Error in child activation: %s", str(err))
942 fc1dc9d7 Iustin Pop
      children.append(cdev)
943 a8083063 Iustin Pop
944 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
945 a8083063 Iustin Pop
    r_dev = bdev.AttachOrAssemble(disk.dev_type, disk.physical_id, children)
946 e31c43f7 Michael Hanselmann
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
947 a8083063 Iustin Pop
    result = r_dev
948 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
949 a8083063 Iustin Pop
      r_dev.Open()
950 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
951 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
952 3f78eef2 Iustin Pop
953 a8083063 Iustin Pop
  else:
954 a8083063 Iustin Pop
    result = True
955 a8083063 Iustin Pop
  return result
956 a8083063 Iustin Pop
957 a8083063 Iustin Pop
958 3f78eef2 Iustin Pop
def AssembleBlockDevice(disk, owner, as_primary):
959 a8083063 Iustin Pop
  """Activate a block device for an instance.
960 a8083063 Iustin Pop

961 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
962 a8083063 Iustin Pop

963 a8083063 Iustin Pop
  Returns:
964 a8083063 Iustin Pop
    a /dev path for primary nodes
965 a8083063 Iustin Pop
    True for secondary nodes
966 a8083063 Iustin Pop

967 a8083063 Iustin Pop
  """
968 3f78eef2 Iustin Pop
  result = _RecursiveAssembleBD(disk, owner, as_primary)
969 a8083063 Iustin Pop
  if isinstance(result, bdev.BlockDev):
970 a8083063 Iustin Pop
    result = result.dev_path
971 a8083063 Iustin Pop
  return result
972 a8083063 Iustin Pop
973 a8083063 Iustin Pop
974 a8083063 Iustin Pop
def ShutdownBlockDevice(disk):
975 a8083063 Iustin Pop
  """Shut down a block device.
976 a8083063 Iustin Pop

977 a8083063 Iustin Pop
  First, if the device is assembled (can `Attach()`), then the device
978 a8083063 Iustin Pop
  is shutdown. Then the children of the device are shutdown.
979 a8083063 Iustin Pop

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

984 a8083063 Iustin Pop
  """
985 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
986 a8083063 Iustin Pop
  if r_dev is not None:
987 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
988 a8083063 Iustin Pop
    result = r_dev.Shutdown()
989 3f78eef2 Iustin Pop
    if result:
990 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
991 a8083063 Iustin Pop
  else:
992 a8083063 Iustin Pop
    result = True
993 a8083063 Iustin Pop
  if disk.children:
994 a8083063 Iustin Pop
    for child in disk.children:
995 a8083063 Iustin Pop
      result = result and ShutdownBlockDevice(child)
996 a8083063 Iustin Pop
  return result
997 a8083063 Iustin Pop
998 a8083063 Iustin Pop
999 153d9724 Iustin Pop
def MirrorAddChildren(parent_cdev, new_cdevs):
1000 153d9724 Iustin Pop
  """Extend a mirrored block device.
1001 a8083063 Iustin Pop

1002 a8083063 Iustin Pop
  """
1003 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev, allow_partial=True)
1004 153d9724 Iustin Pop
  if parent_bdev is None:
1005 18682bca Iustin Pop
    logging.error("Can't find parent device")
1006 a8083063 Iustin Pop
    return False
1007 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1008 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
1009 18682bca Iustin Pop
    logging.error("Can't find new device(s) to add: %s:%s",
1010 18682bca Iustin Pop
                  new_bdevs, new_cdevs)
1011 a8083063 Iustin Pop
    return False
1012 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
1013 a8083063 Iustin Pop
  return True
1014 a8083063 Iustin Pop
1015 a8083063 Iustin Pop
1016 153d9724 Iustin Pop
def MirrorRemoveChildren(parent_cdev, new_cdevs):
1017 153d9724 Iustin Pop
  """Shrink a mirrored block device.
1018 a8083063 Iustin Pop

1019 a8083063 Iustin Pop
  """
1020 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1021 153d9724 Iustin Pop
  if parent_bdev is None:
1022 18682bca Iustin Pop
    logging.error("Can't find parent in remove children: %s", parent_cdev)
1023 a8083063 Iustin Pop
    return False
1024 e739bd57 Iustin Pop
  devs = []
1025 e739bd57 Iustin Pop
  for disk in new_cdevs:
1026 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
1027 e739bd57 Iustin Pop
    if rpath is None:
1028 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
1029 e739bd57 Iustin Pop
      if bd is None:
1030 18682bca Iustin Pop
        logging.error("Can't find dynamic device %s while removing children",
1031 18682bca Iustin Pop
                      disk)
1032 e739bd57 Iustin Pop
        return False
1033 e739bd57 Iustin Pop
      else:
1034 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
1035 e739bd57 Iustin Pop
    else:
1036 e739bd57 Iustin Pop
      devs.append(rpath)
1037 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
1038 a8083063 Iustin Pop
  return True
1039 a8083063 Iustin Pop
1040 a8083063 Iustin Pop
1041 a8083063 Iustin Pop
def GetMirrorStatus(disks):
1042 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
1043 a8083063 Iustin Pop

1044 a8083063 Iustin Pop
  Args:
1045 a8083063 Iustin Pop
    disks: list of `objects.Disk`
1046 a8083063 Iustin Pop

1047 a8083063 Iustin Pop
  Returns:
1048 a8083063 Iustin Pop
    list of (mirror_done, estimated_time) tuples, which
1049 a8083063 Iustin Pop
    are the result of bdev.BlockDevice.CombinedSyncStatus()
1050 a8083063 Iustin Pop

1051 a8083063 Iustin Pop
  """
1052 a8083063 Iustin Pop
  stats = []
1053 a8083063 Iustin Pop
  for dsk in disks:
1054 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
1055 a8083063 Iustin Pop
    if rbd is None:
1056 3ecf6786 Iustin Pop
      raise errors.BlockDeviceError("Can't find device %s" % str(dsk))
1057 a8083063 Iustin Pop
    stats.append(rbd.CombinedSyncStatus())
1058 a8083063 Iustin Pop
  return stats
1059 a8083063 Iustin Pop
1060 a8083063 Iustin Pop
1061 a8083063 Iustin Pop
def _RecursiveFindBD(disk, allow_partial=False):
1062 a8083063 Iustin Pop
  """Check if a device is activated.
1063 a8083063 Iustin Pop

1064 a8083063 Iustin Pop
  If so, return informations about the real device.
1065 a8083063 Iustin Pop

1066 a8083063 Iustin Pop
  Args:
1067 a8083063 Iustin Pop
    disk: the objects.Disk instance
1068 a8083063 Iustin Pop
    allow_partial: don't abort the find if a child of the
1069 a8083063 Iustin Pop
                   device can't be found; this is intended to be
1070 a8083063 Iustin Pop
                   used when repairing mirrors
1071 a8083063 Iustin Pop

1072 a8083063 Iustin Pop
  Returns:
1073 a8083063 Iustin Pop
    None if the device can't be found
1074 a8083063 Iustin Pop
    otherwise the device instance
1075 a8083063 Iustin Pop

1076 a8083063 Iustin Pop
  """
1077 a8083063 Iustin Pop
  children = []
1078 a8083063 Iustin Pop
  if disk.children:
1079 a8083063 Iustin Pop
    for chdisk in disk.children:
1080 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
1081 a8083063 Iustin Pop
1082 a8083063 Iustin Pop
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children)
1083 a8083063 Iustin Pop
1084 a8083063 Iustin Pop
1085 a8083063 Iustin Pop
def FindBlockDevice(disk):
1086 a8083063 Iustin Pop
  """Check if a device is activated.
1087 a8083063 Iustin Pop

1088 a8083063 Iustin Pop
  If so, return informations about the real device.
1089 a8083063 Iustin Pop

1090 a8083063 Iustin Pop
  Args:
1091 a8083063 Iustin Pop
    disk: the objects.Disk instance
1092 a8083063 Iustin Pop
  Returns:
1093 a8083063 Iustin Pop
    None if the device can't be found
1094 a8083063 Iustin Pop
    (device_path, major, minor, sync_percent, estimated_time, is_degraded)
1095 a8083063 Iustin Pop

1096 a8083063 Iustin Pop
  """
1097 a8083063 Iustin Pop
  rbd = _RecursiveFindBD(disk)
1098 a8083063 Iustin Pop
  if rbd is None:
1099 a8083063 Iustin Pop
    return rbd
1100 0834c866 Iustin Pop
  return (rbd.dev_path, rbd.major, rbd.minor) + rbd.GetSyncStatus()
1101 a8083063 Iustin Pop
1102 a8083063 Iustin Pop
1103 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1104 a8083063 Iustin Pop
  """Write a file to the filesystem.
1105 a8083063 Iustin Pop

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

1109 a8083063 Iustin Pop
  """
1110 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
1111 18682bca Iustin Pop
    logging.error("Filename passed to UploadFile is not absolute: '%s'",
1112 18682bca Iustin Pop
                  file_name)
1113 a8083063 Iustin Pop
    return False
1114 a8083063 Iustin Pop
1115 97628462 Iustin Pop
  allowed_files = [
1116 97628462 Iustin Pop
    constants.CLUSTER_CONF_FILE,
1117 97628462 Iustin Pop
    constants.ETC_HOSTS,
1118 97628462 Iustin Pop
    constants.SSH_KNOWN_HOSTS_FILE,
1119 90fae627 Guido Trotter
    constants.VNC_PASSWORD_FILE,
1120 97628462 Iustin Pop
    ]
1121 afee8008 Michael Hanselmann
1122 553f1c1d Michael Hanselmann
  if file_name not in allowed_files:
1123 18682bca Iustin Pop
    logging.error("Filename passed to UploadFile not in allowed"
1124 18682bca Iustin Pop
                 " upload targets: '%s'", file_name)
1125 a8083063 Iustin Pop
    return False
1126 a8083063 Iustin Pop
1127 41a57aab Michael Hanselmann
  utils.WriteFile(file_name, data=data, mode=mode, uid=uid, gid=gid,
1128 41a57aab Michael Hanselmann
                  atime=atime, mtime=mtime)
1129 a8083063 Iustin Pop
  return True
1130 a8083063 Iustin Pop
1131 386b57af Iustin Pop
1132 a8083063 Iustin Pop
def _ErrnoOrStr(err):
1133 a8083063 Iustin Pop
  """Format an EnvironmentError exception.
1134 a8083063 Iustin Pop

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

1139 a8083063 Iustin Pop
  """
1140 a8083063 Iustin Pop
  if hasattr(err, 'errno'):
1141 a8083063 Iustin Pop
    detail = errno.errorcode[err.errno]
1142 a8083063 Iustin Pop
  else:
1143 a8083063 Iustin Pop
    detail = str(err)
1144 a8083063 Iustin Pop
  return detail
1145 a8083063 Iustin Pop
1146 5d0fe286 Iustin Pop
1147 c26dabd7 Guido Trotter
def _OSOndiskVersion(name, os_dir):
1148 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
1149 a8083063 Iustin Pop

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

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

1156 a8083063 Iustin Pop
  """
1157 a8083063 Iustin Pop
  api_file = os.path.sep.join([os_dir, "ganeti_api_version"])
1158 a8083063 Iustin Pop
1159 a8083063 Iustin Pop
  try:
1160 a8083063 Iustin Pop
    st = os.stat(api_file)
1161 a8083063 Iustin Pop
  except EnvironmentError, err:
1162 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "'ganeti_api_version' file not"
1163 3ecf6786 Iustin Pop
                           " found (%s)" % _ErrnoOrStr(err))
1164 a8083063 Iustin Pop
1165 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1166 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "'ganeti_api_version' file is not"
1167 3ecf6786 Iustin Pop
                           " a regular file")
1168 a8083063 Iustin Pop
1169 a8083063 Iustin Pop
  try:
1170 a8083063 Iustin Pop
    f = open(api_file)
1171 a8083063 Iustin Pop
    try:
1172 a8083063 Iustin Pop
      api_version = f.read(256)
1173 a8083063 Iustin Pop
    finally:
1174 a8083063 Iustin Pop
      f.close()
1175 a8083063 Iustin Pop
  except EnvironmentError, err:
1176 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "error while reading the"
1177 3ecf6786 Iustin Pop
                           " API version (%s)" % _ErrnoOrStr(err))
1178 a8083063 Iustin Pop
1179 a8083063 Iustin Pop
  api_version = api_version.strip()
1180 a8083063 Iustin Pop
  try:
1181 a8083063 Iustin Pop
    api_version = int(api_version)
1182 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
1183 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir,
1184 305a7297 Guido Trotter
                           "API version is not integer (%s)" % str(err))
1185 a8083063 Iustin Pop
1186 a8083063 Iustin Pop
  return api_version
1187 a8083063 Iustin Pop
1188 386b57af Iustin Pop
1189 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
1190 a8083063 Iustin Pop
  """Compute the validity for all OSes.
1191 a8083063 Iustin Pop

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

1195 a8083063 Iustin Pop
  Returns:
1196 8fa42c7c Guido Trotter
    list of OS objects
1197 a8083063 Iustin Pop

1198 a8083063 Iustin Pop
  """
1199 7c3d51d4 Guido Trotter
  if top_dirs is None:
1200 7c3d51d4 Guido Trotter
    top_dirs = constants.OS_SEARCH_PATH
1201 a8083063 Iustin Pop
1202 a8083063 Iustin Pop
  result = []
1203 65fe4693 Iustin Pop
  for dir_name in top_dirs:
1204 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
1205 7c3d51d4 Guido Trotter
      try:
1206 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
1207 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
1208 18682bca Iustin Pop
        logging.exception("Can't list the OS directory %s", dir_name)
1209 7c3d51d4 Guido Trotter
        break
1210 7c3d51d4 Guido Trotter
      for name in f_names:
1211 7c3d51d4 Guido Trotter
        try:
1212 65fe4693 Iustin Pop
          os_inst = OSFromDisk(name, base_dir=dir_name)
1213 7c3d51d4 Guido Trotter
          result.append(os_inst)
1214 7c3d51d4 Guido Trotter
        except errors.InvalidOS, err:
1215 8fa42c7c Guido Trotter
          result.append(objects.OS.FromInvalidOS(err))
1216 a8083063 Iustin Pop
1217 a8083063 Iustin Pop
  return result
1218 a8083063 Iustin Pop
1219 a8083063 Iustin Pop
1220 56bcd3f4 Guido Trotter
def OSFromDisk(name, base_dir=None):
1221 a8083063 Iustin Pop
  """Create an OS instance from disk.
1222 a8083063 Iustin Pop

1223 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
1224 a8083063 Iustin Pop
  valid OS name. Otherwise, it will raise an appropriate
1225 a8083063 Iustin Pop
  `errors.InvalidOS` exception, detailing why this is not a valid
1226 a8083063 Iustin Pop
  OS.
1227 a8083063 Iustin Pop

1228 7c3d51d4 Guido Trotter
  Args:
1229 7c3d51d4 Guido Trotter
    os_dir: Directory containing the OS scripts. Defaults to a search
1230 7c3d51d4 Guido Trotter
            in all the OS_SEARCH_PATH directories.
1231 7c3d51d4 Guido Trotter

1232 a8083063 Iustin Pop
  """
1233 7c3d51d4 Guido Trotter
1234 56bcd3f4 Guido Trotter
  if base_dir is None:
1235 57c177af Iustin Pop
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1236 c34c0cfd Iustin Pop
    if os_dir is None:
1237 c34c0cfd Iustin Pop
      raise errors.InvalidOS(name, None, "OS dir not found in search path")
1238 c34c0cfd Iustin Pop
  else:
1239 c34c0cfd Iustin Pop
    os_dir = os.path.sep.join([base_dir, name])
1240 a8083063 Iustin Pop
1241 c26dabd7 Guido Trotter
  api_version = _OSOndiskVersion(name, os_dir)
1242 a8083063 Iustin Pop
1243 a8083063 Iustin Pop
  if api_version != constants.OS_API_VERSION:
1244 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "API version mismatch"
1245 305a7297 Guido Trotter
                           " (found %s want %s)"
1246 3ecf6786 Iustin Pop
                           % (api_version, constants.OS_API_VERSION))
1247 a8083063 Iustin Pop
1248 a8083063 Iustin Pop
  # OS Scripts dictionary, we will populate it with the actual script names
1249 386b57af Iustin Pop
  os_scripts = {'create': '', 'export': '', 'import': '', 'rename': ''}
1250 a8083063 Iustin Pop
1251 a8083063 Iustin Pop
  for script in os_scripts:
1252 a8083063 Iustin Pop
    os_scripts[script] = os.path.sep.join([os_dir, script])
1253 a8083063 Iustin Pop
1254 a8083063 Iustin Pop
    try:
1255 a8083063 Iustin Pop
      st = os.stat(os_scripts[script])
1256 a8083063 Iustin Pop
    except EnvironmentError, err:
1257 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' script missing (%s)" %
1258 3ecf6786 Iustin Pop
                             (script, _ErrnoOrStr(err)))
1259 a8083063 Iustin Pop
1260 a8083063 Iustin Pop
    if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1261 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' script not executable" %
1262 305a7297 Guido Trotter
                             script)
1263 a8083063 Iustin Pop
1264 a8083063 Iustin Pop
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1265 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' is not a regular file" %
1266 305a7297 Guido Trotter
                             script)
1267 a8083063 Iustin Pop
1268 a8083063 Iustin Pop
1269 8fa42c7c Guido Trotter
  return objects.OS(name=name, path=os_dir, status=constants.OS_VALID_STATUS,
1270 a8083063 Iustin Pop
                    create_script=os_scripts['create'],
1271 a8083063 Iustin Pop
                    export_script=os_scripts['export'],
1272 a8083063 Iustin Pop
                    import_script=os_scripts['import'],
1273 386b57af Iustin Pop
                    rename_script=os_scripts['rename'],
1274 a8083063 Iustin Pop
                    api_version=api_version)
1275 a8083063 Iustin Pop
1276 a8083063 Iustin Pop
1277 594609c0 Iustin Pop
def GrowBlockDevice(disk, amount):
1278 594609c0 Iustin Pop
  """Grow a stack of block devices.
1279 594609c0 Iustin Pop

1280 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
1281 594609c0 Iustin Pop
  first one resize.
1282 594609c0 Iustin Pop

1283 594609c0 Iustin Pop
  Args:
1284 594609c0 Iustin Pop
    disk: the disk to be grown
1285 594609c0 Iustin Pop

1286 594609c0 Iustin Pop
  Returns: a tuple of (status, result), with:
1287 594609c0 Iustin Pop
    status: the result (true/false) of the operation
1288 594609c0 Iustin Pop
    result: the error message if the operation failed, otherwise not used
1289 594609c0 Iustin Pop

1290 594609c0 Iustin Pop
  """
1291 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1292 594609c0 Iustin Pop
  if r_dev is None:
1293 594609c0 Iustin Pop
    return False, "Cannot find block device %s" % (disk,)
1294 594609c0 Iustin Pop
1295 594609c0 Iustin Pop
  try:
1296 594609c0 Iustin Pop
    r_dev.Grow(amount)
1297 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
1298 594609c0 Iustin Pop
    return False, str(err)
1299 594609c0 Iustin Pop
1300 594609c0 Iustin Pop
  return True, None
1301 594609c0 Iustin Pop
1302 594609c0 Iustin Pop
1303 a8083063 Iustin Pop
def SnapshotBlockDevice(disk):
1304 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
1305 a8083063 Iustin Pop

1306 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
1307 a8083063 Iustin Pop
  just for the leaf lvm backend device.
1308 a8083063 Iustin Pop

1309 a8083063 Iustin Pop
  Args:
1310 a8083063 Iustin Pop
    disk: the disk to be snapshotted
1311 a8083063 Iustin Pop

1312 a8083063 Iustin Pop
  Returns:
1313 a8083063 Iustin Pop
    a config entry for the actual lvm device snapshotted.
1314 a8083063 Iustin Pop

1315 098c0958 Michael Hanselmann
  """
1316 a8083063 Iustin Pop
  if disk.children:
1317 a8083063 Iustin Pop
    if len(disk.children) == 1:
1318 a8083063 Iustin Pop
      # only one child, let's recurse on it
1319 a8083063 Iustin Pop
      return SnapshotBlockDevice(disk.children[0])
1320 a8083063 Iustin Pop
    else:
1321 a8083063 Iustin Pop
      # more than one child, choose one that matches
1322 a8083063 Iustin Pop
      for child in disk.children:
1323 a8083063 Iustin Pop
        if child.size == disk.size:
1324 a8083063 Iustin Pop
          # return implies breaking the loop
1325 a8083063 Iustin Pop
          return SnapshotBlockDevice(child)
1326 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
1327 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
1328 a8083063 Iustin Pop
    if r_dev is not None:
1329 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
1330 a8083063 Iustin Pop
      return r_dev.Snapshot(disk.size)
1331 a8083063 Iustin Pop
    else:
1332 a8083063 Iustin Pop
      return None
1333 a8083063 Iustin Pop
  else:
1334 3ecf6786 Iustin Pop
    raise errors.ProgrammerError("Cannot snapshot non-lvm block device"
1335 f4bc1f2c Michael Hanselmann
                                 " '%s' of type '%s'" %
1336 3ecf6786 Iustin Pop
                                 (disk.unique_id, disk.dev_type))
1337 a8083063 Iustin Pop
1338 a8083063 Iustin Pop
1339 62c9ec92 Iustin Pop
def ExportSnapshot(disk, dest_node, instance, cluster_name):
1340 a8083063 Iustin Pop
  """Export a block device snapshot to a remote node.
1341 a8083063 Iustin Pop

1342 a8083063 Iustin Pop
  Args:
1343 a8083063 Iustin Pop
    disk: the snapshot block device
1344 a8083063 Iustin Pop
    dest_node: the node to send the image to
1345 a8083063 Iustin Pop
    instance: instance being exported
1346 a8083063 Iustin Pop

1347 a8083063 Iustin Pop
  Returns:
1348 a8083063 Iustin Pop
    True if successful, False otherwise.
1349 a8083063 Iustin Pop

1350 098c0958 Michael Hanselmann
  """
1351 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1352 a8083063 Iustin Pop
  export_script = inst_os.export_script
1353 a8083063 Iustin Pop
1354 a8083063 Iustin Pop
  logfile = "%s/exp-%s-%s-%s.log" % (constants.LOG_OS_DIR, inst_os.name,
1355 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
1356 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
1357 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
1358 a8083063 Iustin Pop
1359 a8083063 Iustin Pop
  real_os_dev = _RecursiveFindBD(disk)
1360 a8083063 Iustin Pop
  if real_os_dev is None:
1361 a8083063 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
1362 a8083063 Iustin Pop
                                  str(disk))
1363 a8083063 Iustin Pop
  real_os_dev.Open()
1364 a8083063 Iustin Pop
1365 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1366 a8083063 Iustin Pop
  destfile = disk.physical_id[1]
1367 a8083063 Iustin Pop
1368 a8083063 Iustin Pop
  # the target command is built out of three individual commands,
1369 a8083063 Iustin Pop
  # which are joined by pipes; we check each individual command for
1370 a8083063 Iustin Pop
  # valid parameters
1371 a8083063 Iustin Pop
1372 a8083063 Iustin Pop
  expcmd = utils.BuildShellCmd("cd %s; %s -i %s -b %s 2>%s", inst_os.path,
1373 a8083063 Iustin Pop
                               export_script, instance.name,
1374 a8083063 Iustin Pop
                               real_os_dev.dev_path, logfile)
1375 a8083063 Iustin Pop
1376 a8083063 Iustin Pop
  comprcmd = "gzip"
1377 a8083063 Iustin Pop
1378 72f0f7fd Iustin Pop
  destcmd = utils.BuildShellCmd("mkdir -p %s && cat > %s/%s",
1379 00003458 Guido Trotter
                                destdir, destdir, destfile)
1380 62c9ec92 Iustin Pop
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1381 62c9ec92 Iustin Pop
                                                   constants.GANETI_RUNAS,
1382 62c9ec92 Iustin Pop
                                                   destcmd)
1383 a8083063 Iustin Pop
1384 a8083063 Iustin Pop
  # all commands have been checked, so we're safe to combine them
1385 72f0f7fd Iustin Pop
  command = '|'.join([expcmd, comprcmd, utils.ShellQuoteArgs(remotecmd)])
1386 a8083063 Iustin Pop
1387 a8083063 Iustin Pop
  result = utils.RunCmd(command)
1388 a8083063 Iustin Pop
1389 a8083063 Iustin Pop
  if result.failed:
1390 18682bca Iustin Pop
    logging.error("os snapshot export command '%s' returned error: %s"
1391 18682bca Iustin Pop
                  " output: %s", command, result.fail_reason, result.output)
1392 a8083063 Iustin Pop
    return False
1393 a8083063 Iustin Pop
1394 a8083063 Iustin Pop
  return True
1395 a8083063 Iustin Pop
1396 a8083063 Iustin Pop
1397 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
1398 a8083063 Iustin Pop
  """Write out the export configuration information.
1399 a8083063 Iustin Pop

1400 a8083063 Iustin Pop
  Args:
1401 a8083063 Iustin Pop
    instance: instance configuration
1402 a8083063 Iustin Pop
    snap_disks: snapshot block devices
1403 a8083063 Iustin Pop

1404 a8083063 Iustin Pop
  Returns:
1405 a8083063 Iustin Pop
    False in case of error, True otherwise.
1406 a8083063 Iustin Pop

1407 098c0958 Michael Hanselmann
  """
1408 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1409 a8083063 Iustin Pop
  finaldestdir = os.path.join(constants.EXPORT_DIR, instance.name)
1410 a8083063 Iustin Pop
1411 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1412 a8083063 Iustin Pop
1413 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
1414 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'version', '0')
1415 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
1416 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'source', instance.primary_node)
1417 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'os', instance.os)
1418 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'compression', 'gzip')
1419 a8083063 Iustin Pop
1420 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
1421 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'name', instance.name)
1422 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'memory', '%d' % instance.memory)
1423 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'vcpus', '%d' % instance.vcpus)
1424 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
1425 66f93869 Manuel Franceschini
1426 66f93869 Manuel Franceschini
  nic_count = 0
1427 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
1428 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_mac' %
1429 a8083063 Iustin Pop
               nic_count, '%s' % nic.mac)
1430 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
1431 38206f3c Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_bridge' % nic_count,
1432 38206f3c Iustin Pop
               '%s' % nic.bridge)
1433 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
1434 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_count)
1435 a8083063 Iustin Pop
1436 66f93869 Manuel Franceschini
  disk_count = 0
1437 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
1438 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
1439 a8083063 Iustin Pop
               ('%s' % disk.iv_name))
1440 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
1441 a8083063 Iustin Pop
               ('%s' % disk.physical_id[1]))
1442 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
1443 a8083063 Iustin Pop
               ('%d' % disk.size))
1444 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_count)
1445 a8083063 Iustin Pop
1446 a8083063 Iustin Pop
  cff = os.path.join(destdir, constants.EXPORT_CONF_FILE)
1447 a8083063 Iustin Pop
  cfo = open(cff, 'w')
1448 a8083063 Iustin Pop
  try:
1449 a8083063 Iustin Pop
    config.write(cfo)
1450 a8083063 Iustin Pop
  finally:
1451 a8083063 Iustin Pop
    cfo.close()
1452 a8083063 Iustin Pop
1453 a8083063 Iustin Pop
  shutil.rmtree(finaldestdir, True)
1454 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
1455 a8083063 Iustin Pop
1456 a8083063 Iustin Pop
  return True
1457 a8083063 Iustin Pop
1458 a8083063 Iustin Pop
1459 a8083063 Iustin Pop
def ExportInfo(dest):
1460 a8083063 Iustin Pop
  """Get export configuration information.
1461 a8083063 Iustin Pop

1462 a8083063 Iustin Pop
  Args:
1463 a8083063 Iustin Pop
    dest: directory containing the export
1464 a8083063 Iustin Pop

1465 a8083063 Iustin Pop
  Returns:
1466 a8083063 Iustin Pop
    A serializable config file containing the export info.
1467 a8083063 Iustin Pop

1468 a8083063 Iustin Pop
  """
1469 a8083063 Iustin Pop
  cff = os.path.join(dest, constants.EXPORT_CONF_FILE)
1470 a8083063 Iustin Pop
1471 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1472 a8083063 Iustin Pop
  config.read(cff)
1473 a8083063 Iustin Pop
1474 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
1475 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
1476 a8083063 Iustin Pop
    return None
1477 a8083063 Iustin Pop
1478 a8083063 Iustin Pop
  return config
1479 a8083063 Iustin Pop
1480 a8083063 Iustin Pop
1481 62c9ec92 Iustin Pop
def ImportOSIntoInstance(instance, os_disk, swap_disk, src_node, src_image,
1482 62c9ec92 Iustin Pop
                         cluster_name):
1483 a8083063 Iustin Pop
  """Import an os image into an instance.
1484 a8083063 Iustin Pop

1485 a8083063 Iustin Pop
  Args:
1486 a8083063 Iustin Pop
    instance: the instance object
1487 a8083063 Iustin Pop
    os_disk: the instance-visible name of the os device
1488 a8083063 Iustin Pop
    swap_disk: the instance-visible name of the swap device
1489 a8083063 Iustin Pop
    src_node: node holding the source image
1490 a8083063 Iustin Pop
    src_image: path to the source image on src_node
1491 a8083063 Iustin Pop

1492 a8083063 Iustin Pop
  Returns:
1493 a8083063 Iustin Pop
    False in case of error, True otherwise.
1494 a8083063 Iustin Pop

1495 a8083063 Iustin Pop
  """
1496 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1497 a8083063 Iustin Pop
  import_script = inst_os.import_script
1498 a8083063 Iustin Pop
1499 9716fdce Iustin Pop
  os_device = instance.FindDisk(os_disk)
1500 9716fdce Iustin Pop
  if os_device is None:
1501 18682bca Iustin Pop
    logging.error("Can't find this device-visible name '%s'", os_disk)
1502 a8083063 Iustin Pop
    return False
1503 a8083063 Iustin Pop
1504 9716fdce Iustin Pop
  swap_device = instance.FindDisk(swap_disk)
1505 9716fdce Iustin Pop
  if swap_device is None:
1506 18682bca Iustin Pop
    logging.error("Can't find this device-visible name '%s'", swap_disk)
1507 a8083063 Iustin Pop
    return False
1508 a8083063 Iustin Pop
1509 a8083063 Iustin Pop
  real_os_dev = _RecursiveFindBD(os_device)
1510 a8083063 Iustin Pop
  if real_os_dev is None:
1511 3ecf6786 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
1512 3ecf6786 Iustin Pop
                                  str(os_device))
1513 a8083063 Iustin Pop
  real_os_dev.Open()
1514 a8083063 Iustin Pop
1515 a8083063 Iustin Pop
  real_swap_dev = _RecursiveFindBD(swap_device)
1516 a8083063 Iustin Pop
  if real_swap_dev is None:
1517 3ecf6786 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
1518 3ecf6786 Iustin Pop
                                  str(swap_device))
1519 a8083063 Iustin Pop
  real_swap_dev.Open()
1520 a8083063 Iustin Pop
1521 a8083063 Iustin Pop
  logfile = "%s/import-%s-%s-%s.log" % (constants.LOG_OS_DIR, instance.os,
1522 a8083063 Iustin Pop
                                        instance.name, int(time.time()))
1523 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
1524 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
1525 a8083063 Iustin Pop
1526 00003458 Guido Trotter
  destcmd = utils.BuildShellCmd('cat %s', src_image)
1527 62c9ec92 Iustin Pop
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(src_node,
1528 62c9ec92 Iustin Pop
                                                   constants.GANETI_RUNAS,
1529 62c9ec92 Iustin Pop
                                                   destcmd)
1530 a8083063 Iustin Pop
1531 a8083063 Iustin Pop
  comprcmd = "gunzip"
1532 a8083063 Iustin Pop
  impcmd = utils.BuildShellCmd("(cd %s; %s -i %s -b %s -s %s &>%s)",
1533 a8083063 Iustin Pop
                               inst_os.path, import_script, instance.name,
1534 a8083063 Iustin Pop
                               real_os_dev.dev_path, real_swap_dev.dev_path,
1535 a8083063 Iustin Pop
                               logfile)
1536 a8083063 Iustin Pop
1537 72f0f7fd Iustin Pop
  command = '|'.join([utils.ShellQuoteArgs(remotecmd), comprcmd, impcmd])
1538 e69d05fd Iustin Pop
  env = {'HYPERVISOR': instance.hypervisor}
1539 a8083063 Iustin Pop
1540 4f0afaf5 Guido Trotter
  result = utils.RunCmd(command, env=env)
1541 a8083063 Iustin Pop
1542 a8083063 Iustin Pop
  if result.failed:
1543 18682bca Iustin Pop
    logging.error("os import command '%s' returned error: %s"
1544 18682bca Iustin Pop
                  " output: %s", command, result.fail_reason, result.output)
1545 a8083063 Iustin Pop
    return False
1546 a8083063 Iustin Pop
1547 a8083063 Iustin Pop
  return True
1548 a8083063 Iustin Pop
1549 a8083063 Iustin Pop
1550 a8083063 Iustin Pop
def ListExports():
1551 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
1552 098c0958 Michael Hanselmann

1553 a8083063 Iustin Pop
  """
1554 a8083063 Iustin Pop
  if os.path.isdir(constants.EXPORT_DIR):
1555 eedbda4b Michael Hanselmann
    return utils.ListVisibleFiles(constants.EXPORT_DIR)
1556 a8083063 Iustin Pop
  else:
1557 a8083063 Iustin Pop
    return []
1558 a8083063 Iustin Pop
1559 a8083063 Iustin Pop
1560 a8083063 Iustin Pop
def RemoveExport(export):
1561 a8083063 Iustin Pop
  """Remove an existing export from the node.
1562 a8083063 Iustin Pop

1563 a8083063 Iustin Pop
  Args:
1564 a8083063 Iustin Pop
    export: the name of the export to remove
1565 a8083063 Iustin Pop

1566 a8083063 Iustin Pop
  Returns:
1567 a8083063 Iustin Pop
    False in case of error, True otherwise.
1568 a8083063 Iustin Pop

1569 098c0958 Michael Hanselmann
  """
1570 a8083063 Iustin Pop
  target = os.path.join(constants.EXPORT_DIR, export)
1571 a8083063 Iustin Pop
1572 a8083063 Iustin Pop
  shutil.rmtree(target)
1573 a8083063 Iustin Pop
  # TODO: catch some of the relevant exceptions and provide a pretty
1574 a8083063 Iustin Pop
  # error message if rmtree fails.
1575 a8083063 Iustin Pop
1576 a8083063 Iustin Pop
  return True
1577 a8083063 Iustin Pop
1578 a8083063 Iustin Pop
1579 f3e513ad Iustin Pop
def RenameBlockDevices(devlist):
1580 f3e513ad Iustin Pop
  """Rename a list of block devices.
1581 f3e513ad Iustin Pop

1582 f3e513ad Iustin Pop
  The devlist argument is a list of tuples (disk, new_logical,
1583 f3e513ad Iustin Pop
  new_physical). The return value will be a combined boolean result
1584 f3e513ad Iustin Pop
  (True only if all renames succeeded).
1585 f3e513ad Iustin Pop

1586 f3e513ad Iustin Pop
  """
1587 f3e513ad Iustin Pop
  result = True
1588 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
1589 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
1590 f3e513ad Iustin Pop
    if dev is None:
1591 f3e513ad Iustin Pop
      result = False
1592 f3e513ad Iustin Pop
      continue
1593 f3e513ad Iustin Pop
    try:
1594 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
1595 f3e513ad Iustin Pop
      dev.Rename(unique_id)
1596 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
1597 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
1598 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
1599 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
1600 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
1601 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
1602 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
1603 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
1604 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
1605 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
1606 f3e513ad Iustin Pop
      result = False
1607 f3e513ad Iustin Pop
  return result
1608 f3e513ad Iustin Pop
1609 f3e513ad Iustin Pop
1610 778b75bb Manuel Franceschini
def _TransformFileStorageDir(file_storage_dir):
1611 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
1612 778b75bb Manuel Franceschini

1613 778b75bb Manuel Franceschini
  Checks wheter the given file_storage_dir is within the cluster-wide
1614 778b75bb Manuel Franceschini
  default file_storage_dir stored in SimpleStore. Only paths under that
1615 778b75bb Manuel Franceschini
  directory are allowed.
1616 778b75bb Manuel Franceschini

1617 778b75bb Manuel Franceschini
  Args:
1618 778b75bb Manuel Franceschini
    file_storage_dir: string with path
1619 d61cbe76 Iustin Pop

1620 778b75bb Manuel Franceschini
  Returns:
1621 778b75bb Manuel Franceschini
    normalized file_storage_dir (string) if valid, None otherwise
1622 778b75bb Manuel Franceschini

1623 778b75bb Manuel Franceschini
  """
1624 c657dcc9 Michael Hanselmann
  cfg = _GetConfig()
1625 778b75bb Manuel Franceschini
  file_storage_dir = os.path.normpath(file_storage_dir)
1626 c657dcc9 Michael Hanselmann
  base_file_storage_dir = cfg.GetFileStorageDir()
1627 778b75bb Manuel Franceschini
  if (not os.path.commonprefix([file_storage_dir, base_file_storage_dir]) ==
1628 778b75bb Manuel Franceschini
      base_file_storage_dir):
1629 18682bca Iustin Pop
    logging.error("file storage directory '%s' is not under base file"
1630 18682bca Iustin Pop
                  " storage directory '%s'",
1631 18682bca Iustin Pop
                  file_storage_dir, base_file_storage_dir)
1632 778b75bb Manuel Franceschini
    return None
1633 778b75bb Manuel Franceschini
  return file_storage_dir
1634 778b75bb Manuel Franceschini
1635 778b75bb Manuel Franceschini
1636 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
1637 778b75bb Manuel Franceschini
  """Create file storage directory.
1638 778b75bb Manuel Franceschini

1639 778b75bb Manuel Franceschini
  Args:
1640 778b75bb Manuel Franceschini
    file_storage_dir: string containing the path
1641 778b75bb Manuel Franceschini

1642 778b75bb Manuel Franceschini
  Returns:
1643 778b75bb Manuel Franceschini
    tuple with first element a boolean indicating wheter dir
1644 778b75bb Manuel Franceschini
    creation was successful or not
1645 778b75bb Manuel Franceschini

1646 778b75bb Manuel Franceschini
  """
1647 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
1648 778b75bb Manuel Franceschini
  result = True,
1649 778b75bb Manuel Franceschini
  if not file_storage_dir:
1650 778b75bb Manuel Franceschini
    result = False,
1651 778b75bb Manuel Franceschini
  else:
1652 778b75bb Manuel Franceschini
    if os.path.exists(file_storage_dir):
1653 778b75bb Manuel Franceschini
      if not os.path.isdir(file_storage_dir):
1654 18682bca Iustin Pop
        logging.error("'%s' is not a directory", file_storage_dir)
1655 778b75bb Manuel Franceschini
        result = False,
1656 778b75bb Manuel Franceschini
    else:
1657 778b75bb Manuel Franceschini
      try:
1658 778b75bb Manuel Franceschini
        os.makedirs(file_storage_dir, 0750)
1659 778b75bb Manuel Franceschini
      except OSError, err:
1660 18682bca Iustin Pop
        logging.error("Cannot create file storage directory '%s': %s",
1661 18682bca Iustin Pop
                      file_storage_dir, err)
1662 778b75bb Manuel Franceschini
        result = False,
1663 778b75bb Manuel Franceschini
  return result
1664 778b75bb Manuel Franceschini
1665 778b75bb Manuel Franceschini
1666 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
1667 778b75bb Manuel Franceschini
  """Remove file storage directory.
1668 778b75bb Manuel Franceschini

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

1671 778b75bb Manuel Franceschini
  Args:
1672 778b75bb Manuel Franceschini
    file_storage_dir: string containing the path
1673 778b75bb Manuel Franceschini

1674 778b75bb Manuel Franceschini
  Returns:
1675 778b75bb Manuel Franceschini
    tuple with first element a boolean indicating wheter dir
1676 778b75bb Manuel Franceschini
    removal was successful or not
1677 778b75bb Manuel Franceschini

1678 778b75bb Manuel Franceschini
  """
1679 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
1680 778b75bb Manuel Franceschini
  result = True,
1681 778b75bb Manuel Franceschini
  if not file_storage_dir:
1682 778b75bb Manuel Franceschini
    result = False,
1683 778b75bb Manuel Franceschini
  else:
1684 778b75bb Manuel Franceschini
    if os.path.exists(file_storage_dir):
1685 778b75bb Manuel Franceschini
      if not os.path.isdir(file_storage_dir):
1686 18682bca Iustin Pop
        logging.error("'%s' is not a directory", file_storage_dir)
1687 778b75bb Manuel Franceschini
        result = False,
1688 778b75bb Manuel Franceschini
      # deletes dir only if empty, otherwise we want to return False
1689 778b75bb Manuel Franceschini
      try:
1690 778b75bb Manuel Franceschini
        os.rmdir(file_storage_dir)
1691 778b75bb Manuel Franceschini
      except OSError, err:
1692 18682bca Iustin Pop
        logging.exception("Cannot remove file storage directory '%s'",
1693 18682bca Iustin Pop
                          file_storage_dir)
1694 778b75bb Manuel Franceschini
        result = False,
1695 778b75bb Manuel Franceschini
  return result
1696 778b75bb Manuel Franceschini
1697 778b75bb Manuel Franceschini
1698 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
1699 778b75bb Manuel Franceschini
  """Rename the file storage directory.
1700 778b75bb Manuel Franceschini

1701 778b75bb Manuel Franceschini
  Args:
1702 778b75bb Manuel Franceschini
    old_file_storage_dir: string containing the old path
1703 778b75bb Manuel Franceschini
    new_file_storage_dir: string containing the new path
1704 778b75bb Manuel Franceschini

1705 778b75bb Manuel Franceschini
  Returns:
1706 778b75bb Manuel Franceschini
    tuple with first element a boolean indicating wheter dir
1707 778b75bb Manuel Franceschini
    rename was successful or not
1708 778b75bb Manuel Franceschini

1709 778b75bb Manuel Franceschini
  """
1710 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
1711 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
1712 778b75bb Manuel Franceschini
  result = True,
1713 778b75bb Manuel Franceschini
  if not old_file_storage_dir or not new_file_storage_dir:
1714 778b75bb Manuel Franceschini
    result = False,
1715 778b75bb Manuel Franceschini
  else:
1716 778b75bb Manuel Franceschini
    if not os.path.exists(new_file_storage_dir):
1717 778b75bb Manuel Franceschini
      if os.path.isdir(old_file_storage_dir):
1718 778b75bb Manuel Franceschini
        try:
1719 778b75bb Manuel Franceschini
          os.rename(old_file_storage_dir, new_file_storage_dir)
1720 778b75bb Manuel Franceschini
        except OSError, err:
1721 18682bca Iustin Pop
          logging.exception("Cannot rename '%s' to '%s'",
1722 18682bca Iustin Pop
                            old_file_storage_dir, new_file_storage_dir)
1723 778b75bb Manuel Franceschini
          result =  False,
1724 778b75bb Manuel Franceschini
      else:
1725 18682bca Iustin Pop
        logging.error("'%s' is not a directory", old_file_storage_dir)
1726 778b75bb Manuel Franceschini
        result = False,
1727 778b75bb Manuel Franceschini
    else:
1728 778b75bb Manuel Franceschini
      if os.path.exists(old_file_storage_dir):
1729 18682bca Iustin Pop
        logging.error("Cannot rename '%s' to '%s'. Both locations exist.",
1730 18682bca Iustin Pop
                      old_file_storage_dir, new_file_storage_dir)
1731 778b75bb Manuel Franceschini
        result = False,
1732 778b75bb Manuel Franceschini
  return result
1733 778b75bb Manuel Franceschini
1734 778b75bb Manuel Franceschini
1735 dc31eae3 Michael Hanselmann
def _IsJobQueueFile(file_name):
1736 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
1737 ca52cdeb Michael Hanselmann

1738 ca52cdeb Michael Hanselmann
  """
1739 ca52cdeb Michael Hanselmann
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
1740 dc31eae3 Michael Hanselmann
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
1741 dc31eae3 Michael Hanselmann
1742 dc31eae3 Michael Hanselmann
  if not result:
1743 ca52cdeb Michael Hanselmann
    logging.error("'%s' is not a file in the queue directory",
1744 ca52cdeb Michael Hanselmann
                  file_name)
1745 dc31eae3 Michael Hanselmann
1746 dc31eae3 Michael Hanselmann
  return result
1747 dc31eae3 Michael Hanselmann
1748 dc31eae3 Michael Hanselmann
1749 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
1750 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
1751 dc31eae3 Michael Hanselmann

1752 dc31eae3 Michael Hanselmann
  """
1753 dc31eae3 Michael Hanselmann
  if not _IsJobQueueFile(file_name):
1754 ca52cdeb Michael Hanselmann
    return False
1755 ca52cdeb Michael Hanselmann
1756 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
1757 ca52cdeb Michael Hanselmann
  utils.WriteFile(file_name, data=content)
1758 ca52cdeb Michael Hanselmann
1759 ca52cdeb Michael Hanselmann
  return True
1760 ca52cdeb Michael Hanselmann
1761 ca52cdeb Michael Hanselmann
1762 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
1763 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
1764 af5ebcb1 Michael Hanselmann

1765 af5ebcb1 Michael Hanselmann
  """
1766 af5ebcb1 Michael Hanselmann
  if not (_IsJobQueueFile(old) and _IsJobQueueFile(new)):
1767 af5ebcb1 Michael Hanselmann
    return False
1768 af5ebcb1 Michael Hanselmann
1769 af5ebcb1 Michael Hanselmann
  os.rename(old, new)
1770 af5ebcb1 Michael Hanselmann
1771 af5ebcb1 Michael Hanselmann
  return True
1772 af5ebcb1 Michael Hanselmann
1773 af5ebcb1 Michael Hanselmann
1774 d61cbe76 Iustin Pop
def CloseBlockDevices(disks):
1775 d61cbe76 Iustin Pop
  """Closes the given block devices.
1776 d61cbe76 Iustin Pop

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

1779 d61cbe76 Iustin Pop
  """
1780 d61cbe76 Iustin Pop
  bdevs = []
1781 d61cbe76 Iustin Pop
  for cf in disks:
1782 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
1783 d61cbe76 Iustin Pop
    if rd is None:
1784 d61cbe76 Iustin Pop
      return (False, "Can't find device %s" % cf)
1785 d61cbe76 Iustin Pop
    bdevs.append(rd)
1786 d61cbe76 Iustin Pop
1787 d61cbe76 Iustin Pop
  msg = []
1788 d61cbe76 Iustin Pop
  for rd in bdevs:
1789 d61cbe76 Iustin Pop
    try:
1790 d61cbe76 Iustin Pop
      rd.Close()
1791 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
1792 d61cbe76 Iustin Pop
      msg.append(str(err))
1793 d61cbe76 Iustin Pop
  if msg:
1794 d61cbe76 Iustin Pop
    return (False, "Can't make devices secondary: %s" % ",".join(msg))
1795 d61cbe76 Iustin Pop
  else:
1796 d61cbe76 Iustin Pop
    return (True, "All devices secondary")
1797 d61cbe76 Iustin Pop
1798 d61cbe76 Iustin Pop
1799 a8083063 Iustin Pop
class HooksRunner(object):
1800 a8083063 Iustin Pop
  """Hook runner.
1801 a8083063 Iustin Pop

1802 a8083063 Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
1803 a8083063 Iustin Pop
  the master side.
1804 a8083063 Iustin Pop

1805 a8083063 Iustin Pop
  """
1806 a8083063 Iustin Pop
  RE_MASK = re.compile("^[a-zA-Z0-9_-]+$")
1807 a8083063 Iustin Pop
1808 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
1809 a8083063 Iustin Pop
    """Constructor for hooks runner.
1810 a8083063 Iustin Pop

1811 a8083063 Iustin Pop
    Args:
1812 a8083063 Iustin Pop
      - hooks_base_dir: if not None, this overrides the
1813 a8083063 Iustin Pop
        constants.HOOKS_BASE_DIR (useful for unittests)
1814 a8083063 Iustin Pop

1815 a8083063 Iustin Pop
    """
1816 a8083063 Iustin Pop
    if hooks_base_dir is None:
1817 a8083063 Iustin Pop
      hooks_base_dir = constants.HOOKS_BASE_DIR
1818 a8083063 Iustin Pop
    self._BASE_DIR = hooks_base_dir
1819 a8083063 Iustin Pop
1820 a8083063 Iustin Pop
  @staticmethod
1821 a8083063 Iustin Pop
  def ExecHook(script, env):
1822 a8083063 Iustin Pop
    """Exec one hook script.
1823 a8083063 Iustin Pop

1824 a8083063 Iustin Pop
    Args:
1825 a8083063 Iustin Pop
     - script: the full path to the script
1826 a8083063 Iustin Pop
     - env: the environment with which to exec the script
1827 a8083063 Iustin Pop

1828 a8083063 Iustin Pop
    """
1829 a8083063 Iustin Pop
    # exec the process using subprocess and log the output
1830 a8083063 Iustin Pop
    fdstdin = None
1831 a8083063 Iustin Pop
    try:
1832 a8083063 Iustin Pop
      fdstdin = open("/dev/null", "r")
1833 a8083063 Iustin Pop
      child = subprocess.Popen([script], stdin=fdstdin, stdout=subprocess.PIPE,
1834 a8083063 Iustin Pop
                               stderr=subprocess.STDOUT, close_fds=True,
1835 147af04d Iustin Pop
                               shell=False, cwd="/", env=env)
1836 a8083063 Iustin Pop
      output = ""
1837 a8083063 Iustin Pop
      try:
1838 a8083063 Iustin Pop
        output = child.stdout.read(4096)
1839 a8083063 Iustin Pop
        child.stdout.close()
1840 a8083063 Iustin Pop
      except EnvironmentError, err:
1841 a8083063 Iustin Pop
        output += "Hook script error: %s" % str(err)
1842 a8083063 Iustin Pop
1843 a8083063 Iustin Pop
      while True:
1844 a8083063 Iustin Pop
        try:
1845 a8083063 Iustin Pop
          result = child.wait()
1846 a8083063 Iustin Pop
          break
1847 a8083063 Iustin Pop
        except EnvironmentError, err:
1848 a8083063 Iustin Pop
          if err.errno == errno.EINTR:
1849 a8083063 Iustin Pop
            continue
1850 a8083063 Iustin Pop
          raise
1851 a8083063 Iustin Pop
    finally:
1852 a8083063 Iustin Pop
      # try not to leak fds
1853 a8083063 Iustin Pop
      for fd in (fdstdin, ):
1854 a8083063 Iustin Pop
        if fd is not None:
1855 a8083063 Iustin Pop
          try:
1856 a8083063 Iustin Pop
            fd.close()
1857 a8083063 Iustin Pop
          except EnvironmentError, err:
1858 a8083063 Iustin Pop
            # just log the error
1859 18682bca Iustin Pop
            #logging.exception("Error while closing fd %s", fd)
1860 a8083063 Iustin Pop
            pass
1861 a8083063 Iustin Pop
1862 a8083063 Iustin Pop
    return result == 0, output
1863 a8083063 Iustin Pop
1864 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
1865 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
1866 a8083063 Iustin Pop

1867 a8083063 Iustin Pop
    This method will not be usually overriden by child opcodes.
1868 a8083063 Iustin Pop

1869 a8083063 Iustin Pop
    """
1870 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
1871 a8083063 Iustin Pop
      suffix = "pre"
1872 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
1873 a8083063 Iustin Pop
      suffix = "post"
1874 a8083063 Iustin Pop
    else:
1875 3ecf6786 Iustin Pop
      raise errors.ProgrammerError("Unknown hooks phase: '%s'" % phase)
1876 a8083063 Iustin Pop
    rr = []
1877 a8083063 Iustin Pop
1878 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
1879 a8083063 Iustin Pop
    dir_name = "%s/%s" % (self._BASE_DIR, subdir)
1880 a8083063 Iustin Pop
    try:
1881 eedbda4b Michael Hanselmann
      dir_contents = utils.ListVisibleFiles(dir_name)
1882 a8083063 Iustin Pop
    except OSError, err:
1883 a8083063 Iustin Pop
      # must log
1884 a8083063 Iustin Pop
      return rr
1885 a8083063 Iustin Pop
1886 a8083063 Iustin Pop
    # we use the standard python sort order,
1887 a8083063 Iustin Pop
    # so 00name is the recommended naming scheme
1888 a8083063 Iustin Pop
    dir_contents.sort()
1889 a8083063 Iustin Pop
    for relname in dir_contents:
1890 a8083063 Iustin Pop
      fname = os.path.join(dir_name, relname)
1891 a8083063 Iustin Pop
      if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and
1892 a8083063 Iustin Pop
          self.RE_MASK.match(relname) is not None):
1893 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
1894 a8083063 Iustin Pop
        output = ""
1895 a8083063 Iustin Pop
      else:
1896 a8083063 Iustin Pop
        result, output = self.ExecHook(fname, env)
1897 a8083063 Iustin Pop
        if not result:
1898 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
1899 a8083063 Iustin Pop
        else:
1900 a8083063 Iustin Pop
          rrval = constants.HKR_SUCCESS
1901 a8083063 Iustin Pop
      rr.append(("%s/%s" % (subdir, relname), rrval, output))
1902 a8083063 Iustin Pop
1903 a8083063 Iustin Pop
    return rr
1904 3f78eef2 Iustin Pop
1905 3f78eef2 Iustin Pop
1906 8d528b7c Iustin Pop
class IAllocatorRunner(object):
1907 8d528b7c Iustin Pop
  """IAllocator runner.
1908 8d528b7c Iustin Pop

1909 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
1910 8d528b7c Iustin Pop
  the master side.
1911 8d528b7c Iustin Pop

1912 8d528b7c Iustin Pop
  """
1913 8d528b7c Iustin Pop
  def Run(self, name, idata):
1914 8d528b7c Iustin Pop
    """Run an iallocator script.
1915 8d528b7c Iustin Pop

1916 8d528b7c Iustin Pop
    Return value: tuple of:
1917 8d528b7c Iustin Pop
       - run status (one of the IARUN_ constants)
1918 8d528b7c Iustin Pop
       - stdout
1919 8d528b7c Iustin Pop
       - stderr
1920 8d528b7c Iustin Pop
       - fail reason (as from utils.RunResult)
1921 8d528b7c Iustin Pop

1922 8d528b7c Iustin Pop
    """
1923 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
1924 8d528b7c Iustin Pop
                                  os.path.isfile)
1925 8d528b7c Iustin Pop
    if alloc_script is None:
1926 8d528b7c Iustin Pop
      return (constants.IARUN_NOTFOUND, None, None, None)
1927 8d528b7c Iustin Pop
1928 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
1929 8d528b7c Iustin Pop
    try:
1930 8d528b7c Iustin Pop
      os.write(fd, idata)
1931 8d528b7c Iustin Pop
      os.close(fd)
1932 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
1933 8d528b7c Iustin Pop
      if result.failed:
1934 8d528b7c Iustin Pop
        return (constants.IARUN_FAILURE, result.stdout, result.stderr,
1935 8d528b7c Iustin Pop
                result.fail_reason)
1936 8d528b7c Iustin Pop
    finally:
1937 8d528b7c Iustin Pop
      os.unlink(fin_name)
1938 8d528b7c Iustin Pop
1939 8d528b7c Iustin Pop
    return (constants.IARUN_SUCCESS, result.stdout, result.stderr, None)
1940 8d528b7c Iustin Pop
1941 8d528b7c Iustin Pop
1942 3f78eef2 Iustin Pop
class DevCacheManager(object):
1943 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
1944 3f78eef2 Iustin Pop

1945 3f78eef2 Iustin Pop
  """
1946 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
1947 3f78eef2 Iustin Pop
  _ROOT_DIR = constants.BDEV_CACHE_DIR
1948 3f78eef2 Iustin Pop
1949 3f78eef2 Iustin Pop
  @classmethod
1950 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
1951 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
1952 3f78eef2 Iustin Pop

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

1956 3f78eef2 Iustin Pop
    """
1957 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
1958 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
1959 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
1960 3f78eef2 Iustin Pop
    fpath = "%s/bdev_%s" % (cls._ROOT_DIR, dev_path)
1961 3f78eef2 Iustin Pop
    return fpath
1962 3f78eef2 Iustin Pop
1963 3f78eef2 Iustin Pop
  @classmethod
1964 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
1965 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
1966 3f78eef2 Iustin Pop

1967 3f78eef2 Iustin Pop
    """
1968 cf5a8306 Iustin Pop
    if dev_path is None:
1969 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
1970 cf5a8306 Iustin Pop
      return
1971 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
1972 3f78eef2 Iustin Pop
    if on_primary:
1973 3f78eef2 Iustin Pop
      state = "primary"
1974 3f78eef2 Iustin Pop
    else:
1975 3f78eef2 Iustin Pop
      state = "secondary"
1976 3f78eef2 Iustin Pop
    if iv_name is None:
1977 3f78eef2 Iustin Pop
      iv_name = "not_visible"
1978 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
1979 3f78eef2 Iustin Pop
    try:
1980 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
1981 3f78eef2 Iustin Pop
    except EnvironmentError, err:
1982 18682bca Iustin Pop
      logging.exception("Can't update bdev cache for %s", dev_path)
1983 3f78eef2 Iustin Pop
1984 3f78eef2 Iustin Pop
  @classmethod
1985 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
1986 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
1987 3f78eef2 Iustin Pop

1988 3f78eef2 Iustin Pop
    """
1989 cf5a8306 Iustin Pop
    if dev_path is None:
1990 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
1991 cf5a8306 Iustin Pop
      return
1992 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
1993 3f78eef2 Iustin Pop
    try:
1994 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
1995 3f78eef2 Iustin Pop
    except EnvironmentError, err:
1996 18682bca Iustin Pop
      logging.exception("Can't update bdev cache for %s", dev_path)