Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 93384844

History | View | Annotate | Download (67.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 93384844 Iustin Pop
  """Simple wrapper to return a SimpleStore.
49 10c2650b Iustin Pop

50 93384844 Iustin Pop
  @rtype: L{ssconf.SimpleStore}
51 93384844 Iustin Pop
  @return: a SimpleStore instance
52 10c2650b Iustin Pop

53 10c2650b Iustin Pop
  """
54 93384844 Iustin Pop
  return ssconf.SimpleStore()
55 c657dcc9 Michael Hanselmann
56 c657dcc9 Michael Hanselmann
57 62c9ec92 Iustin Pop
def _GetSshRunner(cluster_name):
58 10c2650b Iustin Pop
  """Simple wrapper to return an SshRunner.
59 10c2650b Iustin Pop

60 10c2650b Iustin Pop
  @type cluster_name: str
61 10c2650b Iustin Pop
  @param cluster_name: the cluster name, which is needed
62 10c2650b Iustin Pop
      by the SshRunner constructor
63 10c2650b Iustin Pop
  @rtype: L{ssh.SshRunner}
64 10c2650b Iustin Pop
  @return: an SshRunner instance
65 10c2650b Iustin Pop

66 10c2650b Iustin Pop
  """
67 62c9ec92 Iustin Pop
  return ssh.SshRunner(cluster_name)
68 c92b310a Michael Hanselmann
69 c92b310a Michael Hanselmann
70 76ab5558 Michael Hanselmann
def _CleanDirectory(path, exclude=[]):
71 76ab5558 Michael Hanselmann
  """Removes all regular files in a directory.
72 76ab5558 Michael Hanselmann

73 10c2650b Iustin Pop
  @type path: str
74 10c2650b Iustin Pop
  @param path: the directory to clean
75 76ab5558 Michael Hanselmann
  @type exclude: list
76 10c2650b Iustin Pop
  @param exclude: list of files to be excluded, defaults
77 10c2650b Iustin Pop
      to the empty list
78 10c2650b Iustin Pop
  @rtype: None
79 76ab5558 Michael Hanselmann

80 76ab5558 Michael Hanselmann
  """
81 3956cee1 Michael Hanselmann
  if not os.path.isdir(path):
82 3956cee1 Michael Hanselmann
    return
83 76ab5558 Michael Hanselmann
84 76ab5558 Michael Hanselmann
  # Normalize excluded paths
85 76ab5558 Michael Hanselmann
  exclude = [os.path.normpath(i) for i in exclude]
86 76ab5558 Michael Hanselmann
87 3956cee1 Michael Hanselmann
  for rel_name in utils.ListVisibleFiles(path):
88 76ab5558 Michael Hanselmann
    full_name = os.path.normpath(os.path.join(path, rel_name))
89 76ab5558 Michael Hanselmann
    if full_name in exclude:
90 76ab5558 Michael Hanselmann
      continue
91 3956cee1 Michael Hanselmann
    if os.path.isfile(full_name) and not os.path.islink(full_name):
92 3956cee1 Michael Hanselmann
      utils.RemoveFile(full_name)
93 3956cee1 Michael Hanselmann
94 3956cee1 Michael Hanselmann
95 1bc59f76 Michael Hanselmann
def JobQueuePurge():
96 10c2650b Iustin Pop
  """Removes job queue files and archived jobs.
97 10c2650b Iustin Pop

98 10c2650b Iustin Pop
  @rtype: None
99 24fc781f Michael Hanselmann

100 24fc781f Michael Hanselmann
  """
101 1bc59f76 Michael Hanselmann
  _CleanDirectory(constants.QUEUE_DIR, exclude=[constants.JOB_QUEUE_LOCK_FILE])
102 24fc781f Michael Hanselmann
  _CleanDirectory(constants.JOB_QUEUE_ARCHIVE_DIR)
103 24fc781f Michael Hanselmann
104 24fc781f Michael Hanselmann
105 bd1e4562 Iustin Pop
def GetMasterInfo():
106 bd1e4562 Iustin Pop
  """Returns master information.
107 bd1e4562 Iustin Pop

108 bd1e4562 Iustin Pop
  This is an utility function to compute master information, either
109 bd1e4562 Iustin Pop
  for consumption here or from the node daemon.
110 bd1e4562 Iustin Pop

111 bd1e4562 Iustin Pop
  @rtype: tuple
112 10c2650b Iustin Pop
  @return: (master_netdev, master_ip, master_name) if we have a good
113 10c2650b Iustin Pop
      configuration, otherwise (None, None, None)
114 b1b6ea87 Iustin Pop

115 b1b6ea87 Iustin Pop
  """
116 b1b6ea87 Iustin Pop
  try:
117 c657dcc9 Michael Hanselmann
    cfg = _GetConfig()
118 c657dcc9 Michael Hanselmann
    master_netdev = cfg.GetMasterNetdev()
119 c657dcc9 Michael Hanselmann
    master_ip = cfg.GetMasterIP()
120 c657dcc9 Michael Hanselmann
    master_node = cfg.GetMasterNode()
121 b1b6ea87 Iustin Pop
  except errors.ConfigurationError, err:
122 b1b6ea87 Iustin Pop
    logging.exception("Cluster configuration incomplete")
123 0a70a72a Iustin Pop
    return (None, None, None)
124 bd1e4562 Iustin Pop
  return (master_netdev, master_ip, master_node)
125 b1b6ea87 Iustin Pop
126 b1b6ea87 Iustin Pop
127 1c65840b Iustin Pop
def StartMaster(start_daemons):
128 a8083063 Iustin Pop
  """Activate local node as master node.
129 a8083063 Iustin Pop

130 1c65840b Iustin Pop
  The function will always try activate the IP address of the master
131 10c2650b Iustin Pop
  (unless someone else has it). It will also start the master daemons,
132 10c2650b Iustin Pop
  based on the start_daemons parameter.
133 10c2650b Iustin Pop

134 10c2650b Iustin Pop
  @type start_daemons: boolean
135 10c2650b Iustin Pop
  @param start_daemons: whther to also start the master
136 10c2650b Iustin Pop
      daemons (ganeti-masterd and ganeti-rapi)
137 10c2650b Iustin Pop
  @rtype: None
138 a8083063 Iustin Pop

139 a8083063 Iustin Pop
  """
140 b1b6ea87 Iustin Pop
  ok = True
141 bd1e4562 Iustin Pop
  master_netdev, master_ip, _ = GetMasterInfo()
142 b1b6ea87 Iustin Pop
  if not master_netdev:
143 a8083063 Iustin Pop
    return False
144 a8083063 Iustin Pop
145 b1b6ea87 Iustin Pop
  if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
146 caad16e2 Iustin Pop
    if utils.OwnIpAddress(master_ip):
147 b1b6ea87 Iustin Pop
      # we already have the ip:
148 b1b6ea87 Iustin Pop
      logging.debug("Already started")
149 b1b6ea87 Iustin Pop
    else:
150 b1b6ea87 Iustin Pop
      logging.error("Someone else has the master ip, not activating")
151 b1b6ea87 Iustin Pop
      ok = False
152 b1b6ea87 Iustin Pop
  else:
153 b1b6ea87 Iustin Pop
    result = utils.RunCmd(["ip", "address", "add", "%s/32" % master_ip,
154 b1b6ea87 Iustin Pop
                           "dev", master_netdev, "label",
155 b1b6ea87 Iustin Pop
                           "%s:0" % master_netdev])
156 b1b6ea87 Iustin Pop
    if result.failed:
157 b1b6ea87 Iustin Pop
      logging.error("Can't activate master IP: %s", result.output)
158 b1b6ea87 Iustin Pop
      ok = False
159 b1b6ea87 Iustin Pop
160 b1b6ea87 Iustin Pop
    result = utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev,
161 b1b6ea87 Iustin Pop
                           "-s", master_ip, master_ip])
162 b1b6ea87 Iustin Pop
    # we'll ignore the exit code of arping
163 b1b6ea87 Iustin Pop
164 b1b6ea87 Iustin Pop
  # and now start the master and rapi daemons
165 b1b6ea87 Iustin Pop
  if start_daemons:
166 b1b6ea87 Iustin Pop
    for daemon in 'ganeti-masterd', 'ganeti-rapi':
167 b1b6ea87 Iustin Pop
      result = utils.RunCmd([daemon])
168 b1b6ea87 Iustin Pop
      if result.failed:
169 b1b6ea87 Iustin Pop
        logging.error("Can't start daemon %s: %s", daemon, result.output)
170 b1b6ea87 Iustin Pop
        ok = False
171 b1b6ea87 Iustin Pop
  return ok
172 a8083063 Iustin Pop
173 a8083063 Iustin Pop
174 1c65840b Iustin Pop
def StopMaster(stop_daemons):
175 a8083063 Iustin Pop
  """Deactivate this node as master.
176 a8083063 Iustin Pop

177 1c65840b Iustin Pop
  The function will always try to deactivate the IP address of the
178 10c2650b Iustin Pop
  master. It will also stop the master daemons depending on the
179 10c2650b Iustin Pop
  stop_daemons parameter.
180 10c2650b Iustin Pop

181 10c2650b Iustin Pop
  @type stop_daemons: boolean
182 10c2650b Iustin Pop
  @param stop_daemons: whether to also stop the master daemons
183 10c2650b Iustin Pop
      (ganeti-masterd and ganeti-rapi)
184 10c2650b Iustin Pop
  @rtype: None
185 a8083063 Iustin Pop

186 a8083063 Iustin Pop
  """
187 bd1e4562 Iustin Pop
  master_netdev, master_ip, _ = GetMasterInfo()
188 b1b6ea87 Iustin Pop
  if not master_netdev:
189 b1b6ea87 Iustin Pop
    return False
190 a8083063 Iustin Pop
191 b1b6ea87 Iustin Pop
  result = utils.RunCmd(["ip", "address", "del", "%s/32" % master_ip,
192 b1b6ea87 Iustin Pop
                         "dev", master_netdev])
193 a8083063 Iustin Pop
  if result.failed:
194 3b9e6a30 Iustin Pop
    logging.error("Can't remove the master IP, error: %s", result.output)
195 b1b6ea87 Iustin Pop
    # but otherwise ignore the failure
196 b1b6ea87 Iustin Pop
197 b1b6ea87 Iustin Pop
  if stop_daemons:
198 b1b6ea87 Iustin Pop
    # stop/kill the rapi and the master daemon
199 b1b6ea87 Iustin Pop
    for daemon in constants.RAPI_PID, constants.MASTERD_PID:
200 b1b6ea87 Iustin Pop
      utils.KillProcess(utils.ReadPidFile(utils.DaemonPidFileName(daemon)))
201 a8083063 Iustin Pop
202 a8083063 Iustin Pop
  return True
203 a8083063 Iustin Pop
204 a8083063 Iustin Pop
205 9716fdce Iustin Pop
def AddNode(dsa, dsapub, rsa, rsapub, sshkey, sshpub):
206 7900ed01 Iustin Pop
  """Joins this node to the cluster.
207 a8083063 Iustin Pop

208 7900ed01 Iustin Pop
  This does the following:
209 7900ed01 Iustin Pop
      - updates the hostkeys of the machine (rsa and dsa)
210 7900ed01 Iustin Pop
      - adds the ssh private key to the user
211 7900ed01 Iustin Pop
      - adds the ssh public key to the users' authorized_keys file
212 a8083063 Iustin Pop

213 10c2650b Iustin Pop
  @type dsa: str
214 10c2650b Iustin Pop
  @param dsa: the DSA private key to write
215 10c2650b Iustin Pop
  @type dsapub: str
216 10c2650b Iustin Pop
  @param dsapub: the DSA public key to write
217 10c2650b Iustin Pop
  @type rsa: str
218 10c2650b Iustin Pop
  @param rsa: the RSA private key to write
219 10c2650b Iustin Pop
  @type rsapub: str
220 10c2650b Iustin Pop
  @param rsapub: the RSA public key to write
221 10c2650b Iustin Pop
  @type sshkey: str
222 10c2650b Iustin Pop
  @param sshkey: the SSH private key to write
223 10c2650b Iustin Pop
  @type sshpub: str
224 10c2650b Iustin Pop
  @param sshpub: the SSH public key to write
225 10c2650b Iustin Pop
  @rtype: boolean
226 10c2650b Iustin Pop
  @return: the success of the operation
227 10c2650b Iustin Pop

228 7900ed01 Iustin Pop
  """
229 70d9e3d8 Iustin Pop
  sshd_keys =  [(constants.SSH_HOST_RSA_PRIV, rsa, 0600),
230 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_RSA_PUB, rsapub, 0644),
231 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_DSA_PRIV, dsa, 0600),
232 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_DSA_PUB, dsapub, 0644)]
233 7900ed01 Iustin Pop
  for name, content, mode in sshd_keys:
234 70d9e3d8 Iustin Pop
    utils.WriteFile(name, data=content, mode=mode)
235 a8083063 Iustin Pop
236 70d9e3d8 Iustin Pop
  try:
237 70d9e3d8 Iustin Pop
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS,
238 70d9e3d8 Iustin Pop
                                                    mkdir=True)
239 70d9e3d8 Iustin Pop
  except errors.OpExecError, err:
240 18682bca Iustin Pop
    logging.exception("Error while processing user ssh files")
241 70d9e3d8 Iustin Pop
    return False
242 a8083063 Iustin Pop
243 70d9e3d8 Iustin Pop
  for name, content in [(priv_key, sshkey), (pub_key, sshpub)]:
244 70d9e3d8 Iustin Pop
    utils.WriteFile(name, data=content, mode=0600)
245 a8083063 Iustin Pop
246 70d9e3d8 Iustin Pop
  utils.AddAuthorizedKey(auth_keys, sshpub)
247 a8083063 Iustin Pop
248 f491c3a8 Michael Hanselmann
  utils.RunCmd([constants.SSH_INITD_SCRIPT, "restart"])
249 a8083063 Iustin Pop
250 a8083063 Iustin Pop
  return True
251 a8083063 Iustin Pop
252 a8083063 Iustin Pop
253 a8083063 Iustin Pop
def LeaveCluster():
254 10c2650b Iustin Pop
  """Cleans up and remove the current node.
255 10c2650b Iustin Pop

256 10c2650b Iustin Pop
  This function cleans up and prepares the current node to be removed
257 10c2650b Iustin Pop
  from the cluster.
258 10c2650b Iustin Pop

259 10c2650b Iustin Pop
  If processing is successful, then it raises an
260 10c2650b Iustin Pop
  L{errors.GanetiQuitException} which is used as a special case to
261 10c2650b Iustin Pop
  shutdown the node daemon.
262 a8083063 Iustin Pop

263 a8083063 Iustin Pop
  """
264 f78346f5 Michael Hanselmann
  _CleanDirectory(constants.DATA_DIR)
265 1bc59f76 Michael Hanselmann
  JobQueuePurge()
266 f78346f5 Michael Hanselmann
267 70d9e3d8 Iustin Pop
  try:
268 70d9e3d8 Iustin Pop
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
269 18682bca Iustin Pop
  except errors.OpExecError:
270 18682bca Iustin Pop
    logging.exception("Error while processing ssh files")
271 7900ed01 Iustin Pop
    return
272 7900ed01 Iustin Pop
273 70d9e3d8 Iustin Pop
  f = open(pub_key, 'r')
274 a8083063 Iustin Pop
  try:
275 70d9e3d8 Iustin Pop
    utils.RemoveAuthorizedKey(auth_keys, f.read(8192))
276 a8083063 Iustin Pop
  finally:
277 a8083063 Iustin Pop
    f.close()
278 a8083063 Iustin Pop
279 70d9e3d8 Iustin Pop
  utils.RemoveFile(priv_key)
280 70d9e3d8 Iustin Pop
  utils.RemoveFile(pub_key)
281 a8083063 Iustin Pop
282 6d8b6238 Guido Trotter
  # Return a reassuring string to the caller, and quit
283 6d8b6238 Guido Trotter
  raise errors.QuitGanetiException(False, 'Shutdown scheduled')
284 6d8b6238 Guido Trotter
285 a8083063 Iustin Pop
286 e69d05fd Iustin Pop
def GetNodeInfo(vgname, hypervisor_type):
287 2f8598a5 Alexander Schreiber
  """Gives back a hash with different informations about the node.
288 a8083063 Iustin Pop

289 e69d05fd Iustin Pop
  @type vgname: C{string}
290 e69d05fd Iustin Pop
  @param vgname: the name of the volume group to ask for disk space information
291 e69d05fd Iustin Pop
  @type hypervisor_type: C{str}
292 e69d05fd Iustin Pop
  @param hypervisor_type: the name of the hypervisor to ask for
293 e69d05fd Iustin Pop
      memory information
294 e69d05fd Iustin Pop
  @rtype: C{dict}
295 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
296 e69d05fd Iustin Pop
      - vg_size is the size of the configured volume group in MiB
297 e69d05fd Iustin Pop
      - vg_free is the free size of the volume group in MiB
298 e69d05fd Iustin Pop
      - memory_dom0 is the memory allocated for domain0 in MiB
299 e69d05fd Iustin Pop
      - memory_free is the currently available (free) ram in MiB
300 e69d05fd Iustin Pop
      - memory_total is the total number of ram in MiB
301 a8083063 Iustin Pop

302 098c0958 Michael Hanselmann
  """
303 a8083063 Iustin Pop
  outputarray = {}
304 a8083063 Iustin Pop
  vginfo = _GetVGInfo(vgname)
305 a8083063 Iustin Pop
  outputarray['vg_size'] = vginfo['vg_size']
306 a8083063 Iustin Pop
  outputarray['vg_free'] = vginfo['vg_free']
307 a8083063 Iustin Pop
308 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
309 a8083063 Iustin Pop
  hyp_info = hyper.GetNodeInfo()
310 a8083063 Iustin Pop
  if hyp_info is not None:
311 a8083063 Iustin Pop
    outputarray.update(hyp_info)
312 a8083063 Iustin Pop
313 3ef10550 Michael Hanselmann
  f = open("/proc/sys/kernel/random/boot_id", 'r')
314 3ef10550 Michael Hanselmann
  try:
315 3ef10550 Michael Hanselmann
    outputarray["bootid"] = f.read(128).rstrip("\n")
316 3ef10550 Michael Hanselmann
  finally:
317 3ef10550 Michael Hanselmann
    f.close()
318 3ef10550 Michael Hanselmann
319 a8083063 Iustin Pop
  return outputarray
320 a8083063 Iustin Pop
321 a8083063 Iustin Pop
322 62c9ec92 Iustin Pop
def VerifyNode(what, cluster_name):
323 a8083063 Iustin Pop
  """Verify the status of the local node.
324 a8083063 Iustin Pop

325 e69d05fd Iustin Pop
  Based on the input L{what} parameter, various checks are done on the
326 e69d05fd Iustin Pop
  local node.
327 e69d05fd Iustin Pop

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

331 e69d05fd Iustin Pop
  If the I{nodelist} key is present, we check that we have
332 e69d05fd Iustin Pop
  connectivity via ssh with the target nodes (and check the hostname
333 e69d05fd Iustin Pop
  report).
334 a8083063 Iustin Pop

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

339 e69d05fd Iustin Pop
  @type what: C{dict}
340 e69d05fd Iustin Pop
  @param what: a dictionary of things to check:
341 e69d05fd Iustin Pop
      - filelist: list of files for which to compute checksums
342 e69d05fd Iustin Pop
      - nodelist: list of nodes we should check ssh communication with
343 e69d05fd Iustin Pop
      - node-net-test: list of nodes we should check node daemon port
344 e69d05fd Iustin Pop
        connectivity with
345 e69d05fd Iustin Pop
      - hypervisor: list with hypervisors to run the verify for
346 10c2650b Iustin Pop
  @rtype: dict
347 10c2650b Iustin Pop
  @return: a dictionary with the same keys as the input dict, and
348 10c2650b Iustin Pop
      values representing the result of the checks
349 a8083063 Iustin Pop

350 a8083063 Iustin Pop
  """
351 a8083063 Iustin Pop
  result = {}
352 a8083063 Iustin Pop
353 a8083063 Iustin Pop
  if 'hypervisor' in what:
354 e69d05fd Iustin Pop
    result['hypervisor'] = my_dict = {}
355 e69d05fd Iustin Pop
    for hv_name in what['hypervisor']:
356 e69d05fd Iustin Pop
      my_dict[hv_name] = hypervisor.GetHypervisor(hv_name).Verify()
357 a8083063 Iustin Pop
358 a8083063 Iustin Pop
  if 'filelist' in what:
359 a8083063 Iustin Pop
    result['filelist'] = utils.FingerprintFiles(what['filelist'])
360 a8083063 Iustin Pop
361 a8083063 Iustin Pop
  if 'nodelist' in what:
362 a8083063 Iustin Pop
    result['nodelist'] = {}
363 b544cfe0 Iustin Pop
    random.shuffle(what['nodelist'])
364 a8083063 Iustin Pop
    for node in what['nodelist']:
365 62c9ec92 Iustin Pop
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
366 a8083063 Iustin Pop
      if not success:
367 a8083063 Iustin Pop
        result['nodelist'][node] = message
368 9d4bfc96 Iustin Pop
  if 'node-net-test' in what:
369 9d4bfc96 Iustin Pop
    result['node-net-test'] = {}
370 9d4bfc96 Iustin Pop
    my_name = utils.HostInfo().name
371 9d4bfc96 Iustin Pop
    my_pip = my_sip = None
372 9d4bfc96 Iustin Pop
    for name, pip, sip in what['node-net-test']:
373 9d4bfc96 Iustin Pop
      if name == my_name:
374 9d4bfc96 Iustin Pop
        my_pip = pip
375 9d4bfc96 Iustin Pop
        my_sip = sip
376 9d4bfc96 Iustin Pop
        break
377 9d4bfc96 Iustin Pop
    if not my_pip:
378 9d4bfc96 Iustin Pop
      result['node-net-test'][my_name] = ("Can't find my own"
379 9d4bfc96 Iustin Pop
                                          " primary/secondary IP"
380 9d4bfc96 Iustin Pop
                                          " in the node list")
381 9d4bfc96 Iustin Pop
    else:
382 c657dcc9 Michael Hanselmann
      port = utils.GetNodeDaemonPort()
383 9d4bfc96 Iustin Pop
      for name, pip, sip in what['node-net-test']:
384 9d4bfc96 Iustin Pop
        fail = []
385 9d4bfc96 Iustin Pop
        if not utils.TcpPing(pip, port, source=my_pip):
386 9d4bfc96 Iustin Pop
          fail.append("primary")
387 9d4bfc96 Iustin Pop
        if sip != pip:
388 9d4bfc96 Iustin Pop
          if not utils.TcpPing(sip, port, source=my_sip):
389 9d4bfc96 Iustin Pop
            fail.append("secondary")
390 9d4bfc96 Iustin Pop
        if fail:
391 9d4bfc96 Iustin Pop
          result['node-net-test'][name] = ("failure using the %s"
392 9d4bfc96 Iustin Pop
                                           " interface(s)" %
393 9d4bfc96 Iustin Pop
                                           " and ".join(fail))
394 9d4bfc96 Iustin Pop
395 a8083063 Iustin Pop
  return result
396 a8083063 Iustin Pop
397 a8083063 Iustin Pop
398 a8083063 Iustin Pop
def GetVolumeList(vg_name):
399 a8083063 Iustin Pop
  """Compute list of logical volumes and their size.
400 a8083063 Iustin Pop

401 10c2650b Iustin Pop
  @type vg_name: str
402 10c2650b Iustin Pop
  @param vg_name: the volume group whose LVs we should list
403 10c2650b Iustin Pop
  @rtype: dict
404 10c2650b Iustin Pop
  @return:
405 10c2650b Iustin Pop
      dictionary of all partions (key) with value being a tuple of
406 10c2650b Iustin Pop
      their size (in MiB), inactive and online status::
407 10c2650b Iustin Pop

408 10c2650b Iustin Pop
        {'test1': ('20.06', True, True)}
409 10c2650b Iustin Pop

410 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
411 10c2650b Iustin Pop
      details.
412 a8083063 Iustin Pop

413 a8083063 Iustin Pop
  """
414 cb2037a2 Iustin Pop
  lvs = {}
415 cb2037a2 Iustin Pop
  sep = '|'
416 cb2037a2 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
417 cb2037a2 Iustin Pop
                         "--separator=%s" % sep,
418 cb2037a2 Iustin Pop
                         "-olv_name,lv_size,lv_attr", vg_name])
419 a8083063 Iustin Pop
  if result.failed:
420 18682bca Iustin Pop
    logging.error("Failed to list logical volumes, lvs output: %s",
421 18682bca Iustin Pop
                  result.output)
422 b63ed789 Iustin Pop
    return result.output
423 cb2037a2 Iustin Pop
424 df4c2628 Iustin Pop
  valid_line_re = re.compile("^ *([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
425 cb2037a2 Iustin Pop
  for line in result.stdout.splitlines():
426 df4c2628 Iustin Pop
    line = line.strip()
427 df4c2628 Iustin Pop
    match = valid_line_re.match(line)
428 df4c2628 Iustin Pop
    if not match:
429 18682bca Iustin Pop
      logging.error("Invalid line returned from lvs output: '%s'", line)
430 df4c2628 Iustin Pop
      continue
431 df4c2628 Iustin Pop
    name, size, attr = match.groups()
432 cb2037a2 Iustin Pop
    inactive = attr[4] == '-'
433 cb2037a2 Iustin Pop
    online = attr[5] == 'o'
434 cb2037a2 Iustin Pop
    lvs[name] = (size, inactive, online)
435 cb2037a2 Iustin Pop
436 cb2037a2 Iustin Pop
  return lvs
437 a8083063 Iustin Pop
438 a8083063 Iustin Pop
439 a8083063 Iustin Pop
def ListVolumeGroups():
440 2f8598a5 Alexander Schreiber
  """List the volume groups and their size.
441 a8083063 Iustin Pop

442 10c2650b Iustin Pop
  @rtype: dict
443 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
444 10c2650b Iustin Pop
      size of the volume
445 a8083063 Iustin Pop

446 a8083063 Iustin Pop
  """
447 a8083063 Iustin Pop
  return utils.ListVolumeGroups()
448 a8083063 Iustin Pop
449 a8083063 Iustin Pop
450 dcb93971 Michael Hanselmann
def NodeVolumes():
451 dcb93971 Michael Hanselmann
  """List all volumes on this node.
452 dcb93971 Michael Hanselmann

453 10c2650b Iustin Pop
  @rtype: list
454 10c2650b Iustin Pop
  @return:
455 10c2650b Iustin Pop
    A list of dictionaries, each having four keys:
456 10c2650b Iustin Pop
      - name: the logical volume name,
457 10c2650b Iustin Pop
      - size: the size of the logical volume
458 10c2650b Iustin Pop
      - dev: the physical device on which the LV lives
459 10c2650b Iustin Pop
      - vg: the volume group to which it belongs
460 10c2650b Iustin Pop

461 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
462 10c2650b Iustin Pop
    error.
463 10c2650b Iustin Pop

464 10c2650b Iustin Pop
    Note that since a logical volume can live on multiple physical
465 10c2650b Iustin Pop
    volumes, the resulting list might include a logical volume
466 10c2650b Iustin Pop
    multiple times.
467 10c2650b Iustin Pop

468 dcb93971 Michael Hanselmann
  """
469 dcb93971 Michael Hanselmann
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
470 dcb93971 Michael Hanselmann
                         "--separator=|",
471 dcb93971 Michael Hanselmann
                         "--options=lv_name,lv_size,devices,vg_name"])
472 dcb93971 Michael Hanselmann
  if result.failed:
473 18682bca Iustin Pop
    logging.error("Failed to list logical volumes, lvs output: %s",
474 18682bca Iustin Pop
                  result.output)
475 3f5bd234 Iustin Pop
    return []
476 dcb93971 Michael Hanselmann
477 dcb93971 Michael Hanselmann
  def parse_dev(dev):
478 dcb93971 Michael Hanselmann
    if '(' in dev:
479 dcb93971 Michael Hanselmann
      return dev.split('(')[0]
480 dcb93971 Michael Hanselmann
    else:
481 dcb93971 Michael Hanselmann
      return dev
482 dcb93971 Michael Hanselmann
483 dcb93971 Michael Hanselmann
  def map_line(line):
484 dcb93971 Michael Hanselmann
    return {
485 dcb93971 Michael Hanselmann
      'name': line[0].strip(),
486 dcb93971 Michael Hanselmann
      'size': line[1].strip(),
487 dcb93971 Michael Hanselmann
      'dev': parse_dev(line[2].strip()),
488 dcb93971 Michael Hanselmann
      'vg': line[3].strip(),
489 dcb93971 Michael Hanselmann
    }
490 dcb93971 Michael Hanselmann
491 a17a7623 Iustin Pop
  return [map_line(line.split('|')) for line in result.stdout.splitlines()
492 a17a7623 Iustin Pop
          if line.count('|') >= 3]
493 dcb93971 Michael Hanselmann
494 dcb93971 Michael Hanselmann
495 a8083063 Iustin Pop
def BridgesExist(bridges_list):
496 2f8598a5 Alexander Schreiber
  """Check if a list of bridges exist on the current node.
497 a8083063 Iustin Pop

498 b1206984 Iustin Pop
  @rtype: boolean
499 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
500 a8083063 Iustin Pop

501 a8083063 Iustin Pop
  """
502 a8083063 Iustin Pop
  for bridge in bridges_list:
503 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
504 a8083063 Iustin Pop
      return False
505 a8083063 Iustin Pop
506 a8083063 Iustin Pop
  return True
507 a8083063 Iustin Pop
508 a8083063 Iustin Pop
509 e69d05fd Iustin Pop
def GetInstanceList(hypervisor_list):
510 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
511 a8083063 Iustin Pop

512 e69d05fd Iustin Pop
  @type hypervisor_list: list
513 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
514 e69d05fd Iustin Pop

515 e69d05fd Iustin Pop
  @rtype: list
516 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
517 10c2650b Iustin Pop
    - instance1.example.com
518 10c2650b Iustin Pop
    - instance2.example.com
519 a8083063 Iustin Pop

520 098c0958 Michael Hanselmann
  """
521 e69d05fd Iustin Pop
  results = []
522 e69d05fd Iustin Pop
  for hname in hypervisor_list:
523 e69d05fd Iustin Pop
    try:
524 e69d05fd Iustin Pop
      names = hypervisor.GetHypervisor(hname).ListInstances()
525 e69d05fd Iustin Pop
      results.extend(names)
526 e69d05fd Iustin Pop
    except errors.HypervisorError, err:
527 e69d05fd Iustin Pop
      logging.exception("Error enumerating instances for hypevisor %s", hname)
528 e69d05fd Iustin Pop
      # FIXME: should we somehow not propagate this to the master?
529 e69d05fd Iustin Pop
      raise
530 a8083063 Iustin Pop
531 e69d05fd Iustin Pop
  return results
532 a8083063 Iustin Pop
533 a8083063 Iustin Pop
534 e69d05fd Iustin Pop
def GetInstanceInfo(instance, hname):
535 2f8598a5 Alexander Schreiber
  """Gives back the informations about an instance as a dictionary.
536 a8083063 Iustin Pop

537 e69d05fd Iustin Pop
  @type instance: string
538 e69d05fd Iustin Pop
  @param instance: the instance name
539 e69d05fd Iustin Pop
  @type hname: string
540 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
541 a8083063 Iustin Pop

542 e69d05fd Iustin Pop
  @rtype: dict
543 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
544 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
545 e69d05fd Iustin Pop
      - state: xen state of instance (string)
546 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
547 a8083063 Iustin Pop

548 098c0958 Michael Hanselmann
  """
549 a8083063 Iustin Pop
  output = {}
550 a8083063 Iustin Pop
551 e69d05fd Iustin Pop
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
552 a8083063 Iustin Pop
  if iinfo is not None:
553 a8083063 Iustin Pop
    output['memory'] = iinfo[2]
554 a8083063 Iustin Pop
    output['state'] = iinfo[4]
555 a8083063 Iustin Pop
    output['time'] = iinfo[5]
556 a8083063 Iustin Pop
557 a8083063 Iustin Pop
  return output
558 a8083063 Iustin Pop
559 a8083063 Iustin Pop
560 e69d05fd Iustin Pop
def GetAllInstancesInfo(hypervisor_list):
561 a8083063 Iustin Pop
  """Gather data about all instances.
562 a8083063 Iustin Pop

563 10c2650b Iustin Pop
  This is the equivalent of L{GetInstanceInfo}, except that it
564 a8083063 Iustin Pop
  computes data for all instances at once, thus being faster if one
565 a8083063 Iustin Pop
  needs data about more than one instance.
566 a8083063 Iustin Pop

567 e69d05fd Iustin Pop
  @type hypervisor_list: list
568 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
569 e69d05fd Iustin Pop

570 955db481 Guido Trotter
  @rtype: dict
571 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
572 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
573 e69d05fd Iustin Pop
      - state: xen state of instance (string)
574 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
575 10c2650b Iustin Pop
      - vcpus: the number of vcpus
576 a8083063 Iustin Pop

577 098c0958 Michael Hanselmann
  """
578 a8083063 Iustin Pop
  output = {}
579 a8083063 Iustin Pop
580 e69d05fd Iustin Pop
  for hname in hypervisor_list:
581 e69d05fd Iustin Pop
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
582 e69d05fd Iustin Pop
    if iinfo:
583 e69d05fd Iustin Pop
      for name, inst_id, memory, vcpus, state, times in iinfo:
584 f23b5ae8 Iustin Pop
        value = {
585 e69d05fd Iustin Pop
          'memory': memory,
586 e69d05fd Iustin Pop
          'vcpus': vcpus,
587 e69d05fd Iustin Pop
          'state': state,
588 e69d05fd Iustin Pop
          'time': times,
589 e69d05fd Iustin Pop
          }
590 f23b5ae8 Iustin Pop
        if name in output and output[name] != value:
591 f23b5ae8 Iustin Pop
          raise errors.HypervisorError("Instance %s running duplicate"
592 f23b5ae8 Iustin Pop
                                       " with different parameters" % name)
593 f23b5ae8 Iustin Pop
        output[name] = value
594 a8083063 Iustin Pop
595 a8083063 Iustin Pop
  return output
596 a8083063 Iustin Pop
597 a8083063 Iustin Pop
598 d15a9ad3 Guido Trotter
def AddOSToInstance(instance):
599 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
600 a8083063 Iustin Pop

601 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
602 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
603 10c2650b Iustin Pop
  @rtype: boolean
604 10c2650b Iustin Pop
  @return: the success of the operation
605 a8083063 Iustin Pop

606 a8083063 Iustin Pop
  """
607 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
608 a8083063 Iustin Pop
609 58f6e5ca Guido Trotter
  create_env = OSEnvironment(instance)
610 a8083063 Iustin Pop
611 a8083063 Iustin Pop
  logfile = "%s/add-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
612 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
613 decd5f45 Iustin Pop
614 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.create_script], env=create_env,
615 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile,)
616 decd5f45 Iustin Pop
  if result.failed:
617 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
618 d868edb4 Iustin Pop
                  " output: %s", result.cmd, result.fail_reason, logfile,
619 18682bca Iustin Pop
                  result.output)
620 decd5f45 Iustin Pop
    return False
621 decd5f45 Iustin Pop
622 decd5f45 Iustin Pop
  return True
623 decd5f45 Iustin Pop
624 decd5f45 Iustin Pop
625 d15a9ad3 Guido Trotter
def RunRenameInstance(instance, old_name):
626 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
627 decd5f45 Iustin Pop

628 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
629 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
630 d15a9ad3 Guido Trotter
  @type old_name: string
631 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
632 10c2650b Iustin Pop
  @rtype: boolean
633 10c2650b Iustin Pop
  @return: the success of the operation
634 decd5f45 Iustin Pop

635 decd5f45 Iustin Pop
  """
636 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
637 decd5f45 Iustin Pop
638 ff38b6c0 Guido Trotter
  rename_env = OSEnvironment(instance)
639 ff38b6c0 Guido Trotter
  rename_env['OLD_INSTANCE_NAME'] = old_name
640 decd5f45 Iustin Pop
641 decd5f45 Iustin Pop
  logfile = "%s/rename-%s-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
642 decd5f45 Iustin Pop
                                           old_name,
643 decd5f45 Iustin Pop
                                           instance.name, int(time.time()))
644 a8083063 Iustin Pop
645 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
646 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile)
647 a8083063 Iustin Pop
648 a8083063 Iustin Pop
  if result.failed:
649 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
650 d868edb4 Iustin Pop
                  result.cmd, result.fail_reason, result.output)
651 a8083063 Iustin Pop
    return False
652 a8083063 Iustin Pop
653 a8083063 Iustin Pop
  return True
654 a8083063 Iustin Pop
655 a8083063 Iustin Pop
656 a8083063 Iustin Pop
def _GetVGInfo(vg_name):
657 a8083063 Iustin Pop
  """Get informations about the volume group.
658 a8083063 Iustin Pop

659 10c2650b Iustin Pop
  @type vg_name: str
660 10c2650b Iustin Pop
  @param vg_name: the volume group which we query
661 10c2650b Iustin Pop
  @rtype: dict
662 10c2650b Iustin Pop
  @return:
663 10c2650b Iustin Pop
    A dictionary with the following keys:
664 10c2650b Iustin Pop
      - C{vg_size} is the total size of the volume group in MiB
665 10c2650b Iustin Pop
      - C{vg_free} is the free size of the volume group in MiB
666 10c2650b Iustin Pop
      - C{pv_count} are the number of physical disks in that VG
667 a8083063 Iustin Pop

668 10c2650b Iustin Pop
    If an error occurs during gathering of data, we return the same dict
669 10c2650b Iustin Pop
    with keys all set to None.
670 f4d377e7 Iustin Pop

671 a8083063 Iustin Pop
  """
672 f4d377e7 Iustin Pop
  retdic = dict.fromkeys(["vg_size", "vg_free", "pv_count"])
673 f4d377e7 Iustin Pop
674 a8083063 Iustin Pop
  retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings",
675 a8083063 Iustin Pop
                         "--nosuffix", "--units=m", "--separator=:", vg_name])
676 a8083063 Iustin Pop
677 a8083063 Iustin Pop
  if retval.failed:
678 18682bca Iustin Pop
    logging.error("volume group %s not present", vg_name)
679 f4d377e7 Iustin Pop
    return retdic
680 d87ae7d2 Iustin Pop
  valarr = retval.stdout.strip().rstrip(':').split(':')
681 f4d377e7 Iustin Pop
  if len(valarr) == 3:
682 f4d377e7 Iustin Pop
    try:
683 f4d377e7 Iustin Pop
      retdic = {
684 f4d377e7 Iustin Pop
        "vg_size": int(round(float(valarr[0]), 0)),
685 f4d377e7 Iustin Pop
        "vg_free": int(round(float(valarr[1]), 0)),
686 f4d377e7 Iustin Pop
        "pv_count": int(valarr[2]),
687 f4d377e7 Iustin Pop
        }
688 f4d377e7 Iustin Pop
    except ValueError, err:
689 18682bca Iustin Pop
      logging.exception("Fail to parse vgs output")
690 f4d377e7 Iustin Pop
  else:
691 18682bca Iustin Pop
    logging.error("vgs output has the wrong number of fields (expected"
692 18682bca Iustin Pop
                  " three): %s", str(valarr))
693 a8083063 Iustin Pop
  return retdic
694 a8083063 Iustin Pop
695 a8083063 Iustin Pop
696 a8083063 Iustin Pop
def _GatherBlockDevs(instance):
697 a8083063 Iustin Pop
  """Set up an instance's block device(s).
698 a8083063 Iustin Pop

699 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
700 a8083063 Iustin Pop
  devices must be already assembled.
701 a8083063 Iustin Pop

702 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
703 10c2650b Iustin Pop
  @param instance: the instance whose disks we shoul assemble
704 10c2650b Iustin Pop
  @rtype: list of L{bdev.BlockDev}
705 10c2650b Iustin Pop
  @return: list of the block devices
706 10c2650b Iustin Pop

707 a8083063 Iustin Pop
  """
708 a8083063 Iustin Pop
  block_devices = []
709 a8083063 Iustin Pop
  for disk in instance.disks:
710 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
711 a8083063 Iustin Pop
    if device is None:
712 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
713 a8083063 Iustin Pop
                                    str(disk))
714 a8083063 Iustin Pop
    device.Open()
715 a8083063 Iustin Pop
    block_devices.append((disk, device))
716 a8083063 Iustin Pop
  return block_devices
717 a8083063 Iustin Pop
718 a8083063 Iustin Pop
719 a8083063 Iustin Pop
def StartInstance(instance, extra_args):
720 a8083063 Iustin Pop
  """Start an instance.
721 a8083063 Iustin Pop

722 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
723 e69d05fd Iustin Pop
  @param instance: the instance object
724 e69d05fd Iustin Pop
  @rtype: boolean
725 e69d05fd Iustin Pop
  @return: whether the startup was successful or not
726 a8083063 Iustin Pop

727 098c0958 Michael Hanselmann
  """
728 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
729 a8083063 Iustin Pop
730 a8083063 Iustin Pop
  if instance.name in running_instances:
731 a8083063 Iustin Pop
    return True
732 a8083063 Iustin Pop
733 a8083063 Iustin Pop
  block_devices = _GatherBlockDevs(instance)
734 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
735 a8083063 Iustin Pop
736 a8083063 Iustin Pop
  try:
737 a8083063 Iustin Pop
    hyper.StartInstance(instance, block_devices, extra_args)
738 a8083063 Iustin Pop
  except errors.HypervisorError, err:
739 18682bca Iustin Pop
    logging.exception("Failed to start instance")
740 a8083063 Iustin Pop
    return False
741 a8083063 Iustin Pop
742 a8083063 Iustin Pop
  return True
743 a8083063 Iustin Pop
744 a8083063 Iustin Pop
745 a8083063 Iustin Pop
def ShutdownInstance(instance):
746 a8083063 Iustin Pop
  """Shut an instance down.
747 a8083063 Iustin Pop

748 10c2650b Iustin Pop
  @note: this functions uses polling with a hardcoded timeout.
749 10c2650b Iustin Pop

750 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
751 e69d05fd Iustin Pop
  @param instance: the instance object
752 e69d05fd Iustin Pop
  @rtype: boolean
753 e69d05fd Iustin Pop
  @return: whether the startup was successful or not
754 a8083063 Iustin Pop

755 098c0958 Michael Hanselmann
  """
756 e69d05fd Iustin Pop
  hv_name = instance.hypervisor
757 e69d05fd Iustin Pop
  running_instances = GetInstanceList([hv_name])
758 a8083063 Iustin Pop
759 a8083063 Iustin Pop
  if instance.name not in running_instances:
760 a8083063 Iustin Pop
    return True
761 a8083063 Iustin Pop
762 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(hv_name)
763 a8083063 Iustin Pop
  try:
764 a8083063 Iustin Pop
    hyper.StopInstance(instance)
765 a8083063 Iustin Pop
  except errors.HypervisorError, err:
766 18682bca Iustin Pop
    logging.error("Failed to stop instance")
767 a8083063 Iustin Pop
    return False
768 a8083063 Iustin Pop
769 a8083063 Iustin Pop
  # test every 10secs for 2min
770 a8083063 Iustin Pop
  shutdown_ok = False
771 a8083063 Iustin Pop
772 a8083063 Iustin Pop
  time.sleep(1)
773 a8083063 Iustin Pop
  for dummy in range(11):
774 e69d05fd Iustin Pop
    if instance.name not in GetInstanceList([hv_name]):
775 a8083063 Iustin Pop
      break
776 a8083063 Iustin Pop
    time.sleep(10)
777 a8083063 Iustin Pop
  else:
778 a8083063 Iustin Pop
    # the shutdown did not succeed
779 18682bca Iustin Pop
    logging.error("shutdown of '%s' unsuccessful, using destroy", instance)
780 a8083063 Iustin Pop
781 a8083063 Iustin Pop
    try:
782 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
783 a8083063 Iustin Pop
    except errors.HypervisorError, err:
784 18682bca Iustin Pop
      logging.exception("Failed to stop instance")
785 a8083063 Iustin Pop
      return False
786 a8083063 Iustin Pop
787 a8083063 Iustin Pop
    time.sleep(1)
788 e69d05fd Iustin Pop
    if instance.name in GetInstanceList([hv_name]):
789 18682bca Iustin Pop
      logging.error("could not shutdown instance '%s' even by destroy",
790 18682bca Iustin Pop
                    instance.name)
791 a8083063 Iustin Pop
      return False
792 a8083063 Iustin Pop
793 a8083063 Iustin Pop
  return True
794 a8083063 Iustin Pop
795 a8083063 Iustin Pop
796 007a2f3e Alexander Schreiber
def RebootInstance(instance, reboot_type, extra_args):
797 007a2f3e Alexander Schreiber
  """Reboot an instance.
798 007a2f3e Alexander Schreiber

799 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
800 10c2650b Iustin Pop
  @param instance: the instance object to reboot
801 10c2650b Iustin Pop
  @type reboot_type: str
802 10c2650b Iustin Pop
  @param reboot_type: the type of reboot, one the following
803 10c2650b Iustin Pop
    constants:
804 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
805 10c2650b Iustin Pop
        instance OS, do not recreate the VM
806 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
807 10c2650b Iustin Pop
        restart the VM (at the hypervisor level)
808 10c2650b Iustin Pop
      - the other reboot type (L{constants.INSTANCE_REBOOT_HARD})
809 10c2650b Iustin Pop
        is not accepted here, since that mode is handled
810 10c2650b Iustin Pop
        differently
811 10c2650b Iustin Pop
  @rtype: boolean
812 10c2650b Iustin Pop
  @return: the success of the operation
813 007a2f3e Alexander Schreiber

814 007a2f3e Alexander Schreiber
  """
815 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
816 007a2f3e Alexander Schreiber
817 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
818 18682bca Iustin Pop
    logging.error("Cannot reboot instance that is not running")
819 007a2f3e Alexander Schreiber
    return False
820 007a2f3e Alexander Schreiber
821 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
822 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
823 007a2f3e Alexander Schreiber
    try:
824 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
825 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
826 18682bca Iustin Pop
      logging.exception("Failed to soft reboot instance")
827 007a2f3e Alexander Schreiber
      return False
828 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
829 007a2f3e Alexander Schreiber
    try:
830 007a2f3e Alexander Schreiber
      ShutdownInstance(instance)
831 007a2f3e Alexander Schreiber
      StartInstance(instance, extra_args)
832 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
833 18682bca Iustin Pop
      logging.exception("Failed to hard reboot instance")
834 007a2f3e Alexander Schreiber
      return False
835 007a2f3e Alexander Schreiber
  else:
836 007a2f3e Alexander Schreiber
    raise errors.ParameterError("reboot_type invalid")
837 007a2f3e Alexander Schreiber
838 007a2f3e Alexander Schreiber
  return True
839 007a2f3e Alexander Schreiber
840 007a2f3e Alexander Schreiber
841 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
842 2a10865c Iustin Pop
  """Migrates an instance to another node.
843 2a10865c Iustin Pop

844 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
845 9f0e6b37 Iustin Pop
  @param instance: the instance definition
846 9f0e6b37 Iustin Pop
  @type target: string
847 9f0e6b37 Iustin Pop
  @param target: the target node name
848 9f0e6b37 Iustin Pop
  @type live: boolean
849 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
850 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
851 9f0e6b37 Iustin Pop
  @rtype: tuple
852 9f0e6b37 Iustin Pop
  @return: a tuple of (success, msg) where:
853 9f0e6b37 Iustin Pop
      - succes is a boolean denoting the success/failure of the operation
854 9f0e6b37 Iustin Pop
      - msg is a string with details in case of failure
855 9f0e6b37 Iustin Pop

856 2a10865c Iustin Pop
  """
857 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor_name)
858 2a10865c Iustin Pop
859 2a10865c Iustin Pop
  try:
860 9f0e6b37 Iustin Pop
    hyper.MigrateInstance(instance.name, target, live)
861 2a10865c Iustin Pop
  except errors.HypervisorError, err:
862 2a10865c Iustin Pop
    msg = "Failed to migrate instance: %s" % str(err)
863 18682bca Iustin Pop
    logging.error(msg)
864 2a10865c Iustin Pop
    return (False, msg)
865 2a10865c Iustin Pop
  return (True, "Migration successfull")
866 2a10865c Iustin Pop
867 2a10865c Iustin Pop
868 3f78eef2 Iustin Pop
def CreateBlockDevice(disk, size, owner, on_primary, info):
869 a8083063 Iustin Pop
  """Creates a block device for an instance.
870 a8083063 Iustin Pop

871 b1206984 Iustin Pop
  @type disk: L{objects.Disk}
872 b1206984 Iustin Pop
  @param disk: the object describing the disk we should create
873 b1206984 Iustin Pop
  @type size: int
874 b1206984 Iustin Pop
  @param size: the size of the physical underlying device, in MiB
875 b1206984 Iustin Pop
  @type owner: str
876 b1206984 Iustin Pop
  @param owner: the name of the instance for which disk is created,
877 b1206984 Iustin Pop
      used for device cache data
878 b1206984 Iustin Pop
  @type on_primary: boolean
879 b1206984 Iustin Pop
  @param on_primary:  indicates if it is the primary node or not
880 b1206984 Iustin Pop
  @type info: string
881 b1206984 Iustin Pop
  @param info: string that will be sent to the physical device
882 b1206984 Iustin Pop
      creation, used for example to set (LVM) tags on LVs
883 b1206984 Iustin Pop

884 b1206984 Iustin Pop
  @return: the new unique_id of the device (this can sometime be
885 b1206984 Iustin Pop
      computed only after creation), or None. On secondary nodes,
886 b1206984 Iustin Pop
      it's not required to return anything.
887 a8083063 Iustin Pop

888 a8083063 Iustin Pop
  """
889 a8083063 Iustin Pop
  clist = []
890 a8083063 Iustin Pop
  if disk.children:
891 a8083063 Iustin Pop
    for child in disk.children:
892 3f78eef2 Iustin Pop
      crdev = _RecursiveAssembleBD(child, owner, on_primary)
893 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
894 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
895 a8083063 Iustin Pop
        # be assembled
896 a8083063 Iustin Pop
        crdev.Open()
897 a8083063 Iustin Pop
      clist.append(crdev)
898 a8083063 Iustin Pop
  try:
899 a8083063 Iustin Pop
    device = bdev.FindDevice(disk.dev_type, disk.physical_id, clist)
900 a8083063 Iustin Pop
    if device is not None:
901 18682bca Iustin Pop
      logging.info("removing existing device %s", disk)
902 a8083063 Iustin Pop
      device.Remove()
903 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
904 a8083063 Iustin Pop
    pass
905 a8083063 Iustin Pop
906 a8083063 Iustin Pop
  device = bdev.Create(disk.dev_type, disk.physical_id,
907 a8083063 Iustin Pop
                       clist, size)
908 a8083063 Iustin Pop
  if device is None:
909 a8083063 Iustin Pop
    raise ValueError("Can't create child device for %s, %s" %
910 a8083063 Iustin Pop
                     (disk, size))
911 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
912 cf5a8306 Iustin Pop
    if not device.Assemble():
913 20a0c9ef Guido Trotter
      errorstring = "Can't assemble device after creation"
914 18682bca Iustin Pop
      logging.error(errorstring)
915 20a0c9ef Guido Trotter
      raise errors.BlockDeviceError("%s, very unusual event - check the node"
916 20a0c9ef Guido Trotter
                                    " daemon logs" % errorstring)
917 e31c43f7 Michael Hanselmann
    device.SetSyncSpeed(constants.SYNC_SPEED)
918 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
919 a8083063 Iustin Pop
      device.Open(force=True)
920 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
921 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
922 a0c3fea1 Michael Hanselmann
923 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
924 a0c3fea1 Michael Hanselmann
925 a8083063 Iustin Pop
  physical_id = device.unique_id
926 a8083063 Iustin Pop
  return physical_id
927 a8083063 Iustin Pop
928 a8083063 Iustin Pop
929 a8083063 Iustin Pop
def RemoveBlockDevice(disk):
930 a8083063 Iustin Pop
  """Remove a block device.
931 a8083063 Iustin Pop

932 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
933 10c2650b Iustin Pop

934 10c2650b Iustin Pop
  @type disk: L{objects.disk}
935 10c2650b Iustin Pop
  @param disk: the disk object we should remove
936 10c2650b Iustin Pop
  @rtype: boolean
937 10c2650b Iustin Pop
  @return: the success of the operation
938 a8083063 Iustin Pop

939 a8083063 Iustin Pop
  """
940 a8083063 Iustin Pop
  try:
941 a8083063 Iustin Pop
    # since we are removing the device, allow a partial match
942 a8083063 Iustin Pop
    # this allows removal of broken mirrors
943 a8083063 Iustin Pop
    rdev = _RecursiveFindBD(disk, allow_partial=True)
944 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
945 a8083063 Iustin Pop
    # probably can't attach
946 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
947 a8083063 Iustin Pop
    rdev = None
948 a8083063 Iustin Pop
  if rdev is not None:
949 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
950 a8083063 Iustin Pop
    result = rdev.Remove()
951 3f78eef2 Iustin Pop
    if result:
952 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
953 a8083063 Iustin Pop
  else:
954 a8083063 Iustin Pop
    result = True
955 a8083063 Iustin Pop
  if disk.children:
956 a8083063 Iustin Pop
    for child in disk.children:
957 a8083063 Iustin Pop
      result = result and RemoveBlockDevice(child)
958 a8083063 Iustin Pop
  return result
959 a8083063 Iustin Pop
960 a8083063 Iustin Pop
961 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
962 a8083063 Iustin Pop
  """Activate a block device for an instance.
963 a8083063 Iustin Pop

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

966 10c2650b Iustin Pop
  @note: this function is called recursively.
967 a8083063 Iustin Pop

968 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
969 10c2650b Iustin Pop
  @param disk: the disk we try to assemble
970 10c2650b Iustin Pop
  @type owner: str
971 10c2650b Iustin Pop
  @param owner: the name of the instance which owns the disk
972 10c2650b Iustin Pop
  @type as_primary: boolean
973 10c2650b Iustin Pop
  @param as_primary: if we should make the block device
974 10c2650b Iustin Pop
      read/write
975 a8083063 Iustin Pop

976 10c2650b Iustin Pop
  @return: the assembled device or None (in case no device
977 10c2650b Iustin Pop
      was assembled)
978 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: in case there is an error
979 10c2650b Iustin Pop
      during the activation of the children or the device
980 10c2650b Iustin Pop
      itself
981 a8083063 Iustin Pop

982 a8083063 Iustin Pop
  """
983 a8083063 Iustin Pop
  children = []
984 a8083063 Iustin Pop
  if disk.children:
985 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
986 fc1dc9d7 Iustin Pop
    if mcn == -1:
987 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
988 fc1dc9d7 Iustin Pop
    else:
989 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
990 a8083063 Iustin Pop
    for chld_disk in disk.children:
991 fc1dc9d7 Iustin Pop
      try:
992 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
993 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
994 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
995 fc1dc9d7 Iustin Pop
          raise
996 fc1dc9d7 Iustin Pop
        cdev = None
997 18682bca Iustin Pop
        logging.debug("Error in child activation: %s", str(err))
998 fc1dc9d7 Iustin Pop
      children.append(cdev)
999 a8083063 Iustin Pop
1000 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
1001 a8083063 Iustin Pop
    r_dev = bdev.AttachOrAssemble(disk.dev_type, disk.physical_id, children)
1002 e31c43f7 Michael Hanselmann
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1003 a8083063 Iustin Pop
    result = r_dev
1004 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
1005 a8083063 Iustin Pop
      r_dev.Open()
1006 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1007 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
1008 3f78eef2 Iustin Pop
1009 a8083063 Iustin Pop
  else:
1010 a8083063 Iustin Pop
    result = True
1011 a8083063 Iustin Pop
  return result
1012 a8083063 Iustin Pop
1013 a8083063 Iustin Pop
1014 3f78eef2 Iustin Pop
def AssembleBlockDevice(disk, owner, as_primary):
1015 a8083063 Iustin Pop
  """Activate a block device for an instance.
1016 a8083063 Iustin Pop

1017 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
1018 a8083063 Iustin Pop

1019 b1206984 Iustin Pop
  @rtype: str or boolean
1020 b1206984 Iustin Pop
  @return: a C{/dev/...} path for primary nodes, and
1021 b1206984 Iustin Pop
      C{True} for secondary nodes
1022 a8083063 Iustin Pop

1023 a8083063 Iustin Pop
  """
1024 3f78eef2 Iustin Pop
  result = _RecursiveAssembleBD(disk, owner, as_primary)
1025 a8083063 Iustin Pop
  if isinstance(result, bdev.BlockDev):
1026 a8083063 Iustin Pop
    result = result.dev_path
1027 a8083063 Iustin Pop
  return result
1028 a8083063 Iustin Pop
1029 a8083063 Iustin Pop
1030 a8083063 Iustin Pop
def ShutdownBlockDevice(disk):
1031 a8083063 Iustin Pop
  """Shut down a block device.
1032 a8083063 Iustin Pop

1033 10c2650b Iustin Pop
  First, if the device is assembled (can L{Attach()}), then the device
1034 a8083063 Iustin Pop
  is shutdown. Then the children of the device are shutdown.
1035 a8083063 Iustin Pop

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

1040 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1041 10c2650b Iustin Pop
  @param disk: the description of the disk we should
1042 10c2650b Iustin Pop
      shutdown
1043 10c2650b Iustin Pop
  @rtype: boolean
1044 10c2650b Iustin Pop
  @return: the success of the operation
1045 10c2650b Iustin Pop

1046 a8083063 Iustin Pop
  """
1047 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1048 a8083063 Iustin Pop
  if r_dev is not None:
1049 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
1050 a8083063 Iustin Pop
    result = r_dev.Shutdown()
1051 3f78eef2 Iustin Pop
    if result:
1052 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1053 a8083063 Iustin Pop
  else:
1054 a8083063 Iustin Pop
    result = True
1055 a8083063 Iustin Pop
  if disk.children:
1056 a8083063 Iustin Pop
    for child in disk.children:
1057 a8083063 Iustin Pop
      result = result and ShutdownBlockDevice(child)
1058 a8083063 Iustin Pop
  return result
1059 a8083063 Iustin Pop
1060 a8083063 Iustin Pop
1061 153d9724 Iustin Pop
def MirrorAddChildren(parent_cdev, new_cdevs):
1062 153d9724 Iustin Pop
  """Extend a mirrored block device.
1063 a8083063 Iustin Pop

1064 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1065 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
1066 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1067 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
1068 10c2650b Iustin Pop
  @rtype: boolean
1069 10c2650b Iustin Pop
  @return: the success of the operation
1070 10c2650b Iustin Pop

1071 a8083063 Iustin Pop
  """
1072 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev, allow_partial=True)
1073 153d9724 Iustin Pop
  if parent_bdev is None:
1074 18682bca Iustin Pop
    logging.error("Can't find parent device")
1075 a8083063 Iustin Pop
    return False
1076 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1077 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
1078 18682bca Iustin Pop
    logging.error("Can't find new device(s) to add: %s:%s",
1079 18682bca Iustin Pop
                  new_bdevs, new_cdevs)
1080 a8083063 Iustin Pop
    return False
1081 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
1082 a8083063 Iustin Pop
  return True
1083 a8083063 Iustin Pop
1084 a8083063 Iustin Pop
1085 153d9724 Iustin Pop
def MirrorRemoveChildren(parent_cdev, new_cdevs):
1086 153d9724 Iustin Pop
  """Shrink a mirrored block device.
1087 a8083063 Iustin Pop

1088 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1089 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
1090 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1091 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
1092 10c2650b Iustin Pop
  @rtype: boolean
1093 10c2650b Iustin Pop
  @return: the success of the operation
1094 10c2650b Iustin Pop

1095 a8083063 Iustin Pop
  """
1096 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1097 153d9724 Iustin Pop
  if parent_bdev is None:
1098 18682bca Iustin Pop
    logging.error("Can't find parent in remove children: %s", parent_cdev)
1099 a8083063 Iustin Pop
    return False
1100 e739bd57 Iustin Pop
  devs = []
1101 e739bd57 Iustin Pop
  for disk in new_cdevs:
1102 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
1103 e739bd57 Iustin Pop
    if rpath is None:
1104 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
1105 e739bd57 Iustin Pop
      if bd is None:
1106 18682bca Iustin Pop
        logging.error("Can't find dynamic device %s while removing children",
1107 18682bca Iustin Pop
                      disk)
1108 e739bd57 Iustin Pop
        return False
1109 e739bd57 Iustin Pop
      else:
1110 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
1111 e739bd57 Iustin Pop
    else:
1112 e739bd57 Iustin Pop
      devs.append(rpath)
1113 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
1114 a8083063 Iustin Pop
  return True
1115 a8083063 Iustin Pop
1116 a8083063 Iustin Pop
1117 a8083063 Iustin Pop
def GetMirrorStatus(disks):
1118 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
1119 a8083063 Iustin Pop

1120 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
1121 10c2650b Iustin Pop
  @param disks: the list of disks which we should query
1122 10c2650b Iustin Pop
  @rtype: disk
1123 10c2650b Iustin Pop
  @return:
1124 10c2650b Iustin Pop
      a list of (mirror_done, estimated_time) tuples, which
1125 10c2650b Iustin Pop
      are the result of L{bdev.BlockDevice.CombinedSyncStatus}
1126 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if any of the disks cannot be
1127 10c2650b Iustin Pop
      found
1128 a8083063 Iustin Pop

1129 a8083063 Iustin Pop
  """
1130 a8083063 Iustin Pop
  stats = []
1131 a8083063 Iustin Pop
  for dsk in disks:
1132 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
1133 a8083063 Iustin Pop
    if rbd is None:
1134 3ecf6786 Iustin Pop
      raise errors.BlockDeviceError("Can't find device %s" % str(dsk))
1135 a8083063 Iustin Pop
    stats.append(rbd.CombinedSyncStatus())
1136 a8083063 Iustin Pop
  return stats
1137 a8083063 Iustin Pop
1138 a8083063 Iustin Pop
1139 a8083063 Iustin Pop
def _RecursiveFindBD(disk, allow_partial=False):
1140 a8083063 Iustin Pop
  """Check if a device is activated.
1141 a8083063 Iustin Pop

1142 a8083063 Iustin Pop
  If so, return informations about the real device.
1143 a8083063 Iustin Pop

1144 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1145 10c2650b Iustin Pop
  @param disk: the disk object we need to find
1146 10c2650b Iustin Pop
  @type allow_partial: boolean
1147 10c2650b Iustin Pop
  @param allow_partial: if true, don't abort the find if a
1148 10c2650b Iustin Pop
      child of the device can't be found; this is intended
1149 10c2650b Iustin Pop
      to be used when repairing mirrors
1150 a8083063 Iustin Pop

1151 10c2650b Iustin Pop
  @return: None if the device can't be found,
1152 10c2650b Iustin Pop
      otherwise the device instance
1153 a8083063 Iustin Pop

1154 a8083063 Iustin Pop
  """
1155 a8083063 Iustin Pop
  children = []
1156 a8083063 Iustin Pop
  if disk.children:
1157 a8083063 Iustin Pop
    for chdisk in disk.children:
1158 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
1159 a8083063 Iustin Pop
1160 a8083063 Iustin Pop
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children)
1161 a8083063 Iustin Pop
1162 a8083063 Iustin Pop
1163 a8083063 Iustin Pop
def FindBlockDevice(disk):
1164 a8083063 Iustin Pop
  """Check if a device is activated.
1165 a8083063 Iustin Pop

1166 10c2650b Iustin Pop
  If it is, return informations about the real device.
1167 a8083063 Iustin Pop

1168 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1169 10c2650b Iustin Pop
  @param disk: the disk to find
1170 10c2650b Iustin Pop
  @rtype: None or tuple
1171 10c2650b Iustin Pop
  @return: None if the disk cannot be found, otherwise a
1172 10c2650b Iustin Pop
      tuple (device_path, major, minor, sync_percent,
1173 10c2650b Iustin Pop
      estimated_time, is_degraded)
1174 a8083063 Iustin Pop

1175 a8083063 Iustin Pop
  """
1176 a8083063 Iustin Pop
  rbd = _RecursiveFindBD(disk)
1177 a8083063 Iustin Pop
  if rbd is None:
1178 a8083063 Iustin Pop
    return rbd
1179 0834c866 Iustin Pop
  return (rbd.dev_path, rbd.major, rbd.minor) + rbd.GetSyncStatus()
1180 a8083063 Iustin Pop
1181 a8083063 Iustin Pop
1182 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1183 a8083063 Iustin Pop
  """Write a file to the filesystem.
1184 a8083063 Iustin Pop

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

1188 10c2650b Iustin Pop
  @type file_name: str
1189 10c2650b Iustin Pop
  @param file_name: the target file name
1190 10c2650b Iustin Pop
  @type data: str
1191 10c2650b Iustin Pop
  @param data: the new contents of the file
1192 10c2650b Iustin Pop
  @type mode: int
1193 10c2650b Iustin Pop
  @param mode: the mode to give the file (can be None)
1194 10c2650b Iustin Pop
  @type uid: int
1195 10c2650b Iustin Pop
  @param uid: the owner of the file (can be -1 for default)
1196 10c2650b Iustin Pop
  @type gid: int
1197 10c2650b Iustin Pop
  @param gid: the group of the file (can be -1 for default)
1198 10c2650b Iustin Pop
  @type atime: float
1199 10c2650b Iustin Pop
  @param atime: the atime to set on the file (can be None)
1200 10c2650b Iustin Pop
  @type mtime: float
1201 10c2650b Iustin Pop
  @param mtime: the mtime to set on the file (can be None)
1202 10c2650b Iustin Pop
  @rtype: boolean
1203 10c2650b Iustin Pop
  @return: the success of the operation; errors are logged
1204 10c2650b Iustin Pop
      in the node daemon log
1205 10c2650b Iustin Pop

1206 a8083063 Iustin Pop
  """
1207 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
1208 18682bca Iustin Pop
    logging.error("Filename passed to UploadFile is not absolute: '%s'",
1209 18682bca Iustin Pop
                  file_name)
1210 a8083063 Iustin Pop
    return False
1211 a8083063 Iustin Pop
1212 97628462 Iustin Pop
  allowed_files = [
1213 97628462 Iustin Pop
    constants.CLUSTER_CONF_FILE,
1214 97628462 Iustin Pop
    constants.ETC_HOSTS,
1215 97628462 Iustin Pop
    constants.SSH_KNOWN_HOSTS_FILE,
1216 90fae627 Guido Trotter
    constants.VNC_PASSWORD_FILE,
1217 97628462 Iustin Pop
    ]
1218 afee8008 Michael Hanselmann
1219 553f1c1d Michael Hanselmann
  if file_name not in allowed_files:
1220 18682bca Iustin Pop
    logging.error("Filename passed to UploadFile not in allowed"
1221 18682bca Iustin Pop
                 " upload targets: '%s'", file_name)
1222 a8083063 Iustin Pop
    return False
1223 a8083063 Iustin Pop
1224 41a57aab Michael Hanselmann
  utils.WriteFile(file_name, data=data, mode=mode, uid=uid, gid=gid,
1225 41a57aab Michael Hanselmann
                  atime=atime, mtime=mtime)
1226 a8083063 Iustin Pop
  return True
1227 a8083063 Iustin Pop
1228 386b57af Iustin Pop
1229 03d1dba2 Michael Hanselmann
def WriteSsconfFiles(values):
1230 03d1dba2 Michael Hanselmann
  ssconf.WriteSsconfFiles(values)
1231 6ddc95ec Michael Hanselmann
1232 6ddc95ec Michael Hanselmann
1233 a8083063 Iustin Pop
def _ErrnoOrStr(err):
1234 a8083063 Iustin Pop
  """Format an EnvironmentError exception.
1235 a8083063 Iustin Pop

1236 10c2650b Iustin Pop
  If the L{err} argument has an errno attribute, it will be looked up
1237 10c2650b Iustin Pop
  and converted into a textual C{E...} description. Otherwise the
1238 10c2650b Iustin Pop
  string representation of the error will be returned.
1239 10c2650b Iustin Pop

1240 10c2650b Iustin Pop
  @type err: L{EnvironmentError}
1241 10c2650b Iustin Pop
  @param err: the exception to format
1242 a8083063 Iustin Pop

1243 a8083063 Iustin Pop
  """
1244 a8083063 Iustin Pop
  if hasattr(err, 'errno'):
1245 a8083063 Iustin Pop
    detail = errno.errorcode[err.errno]
1246 a8083063 Iustin Pop
  else:
1247 a8083063 Iustin Pop
    detail = str(err)
1248 a8083063 Iustin Pop
  return detail
1249 a8083063 Iustin Pop
1250 5d0fe286 Iustin Pop
1251 c26dabd7 Guido Trotter
def _OSOndiskVersion(name, os_dir):
1252 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
1253 a8083063 Iustin Pop

1254 10c2650b Iustin Pop
  This function will try to read the API version of the OS given by
1255 7c3d51d4 Guido Trotter
  the 'name' parameter and residing in the 'os_dir' directory.
1256 7c3d51d4 Guido Trotter

1257 10c2650b Iustin Pop
  @type name: str
1258 10c2650b Iustin Pop
  @param name: the OS name we should look for
1259 10c2650b Iustin Pop
  @type os_dir: str
1260 10c2650b Iustin Pop
  @param os_dir: the directory inwhich we should look for the OS
1261 10c2650b Iustin Pop
  @rtype: int or None
1262 10c2650b Iustin Pop
  @return:
1263 10c2650b Iustin Pop
      Either an integer denoting the version or None in the
1264 10c2650b Iustin Pop
      case when this is not a valid OS name.
1265 10c2650b Iustin Pop
  @raise errors.InvalidOS: if the OS cannot be found
1266 a8083063 Iustin Pop

1267 a8083063 Iustin Pop
  """
1268 a8083063 Iustin Pop
  api_file = os.path.sep.join([os_dir, "ganeti_api_version"])
1269 a8083063 Iustin Pop
1270 a8083063 Iustin Pop
  try:
1271 a8083063 Iustin Pop
    st = os.stat(api_file)
1272 a8083063 Iustin Pop
  except EnvironmentError, err:
1273 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "'ganeti_api_version' file not"
1274 3ecf6786 Iustin Pop
                           " found (%s)" % _ErrnoOrStr(err))
1275 a8083063 Iustin Pop
1276 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1277 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "'ganeti_api_version' file is not"
1278 3ecf6786 Iustin Pop
                           " a regular file")
1279 a8083063 Iustin Pop
1280 a8083063 Iustin Pop
  try:
1281 a8083063 Iustin Pop
    f = open(api_file)
1282 a8083063 Iustin Pop
    try:
1283 082a7f91 Guido Trotter
      api_versions = f.readlines()
1284 a8083063 Iustin Pop
    finally:
1285 a8083063 Iustin Pop
      f.close()
1286 a8083063 Iustin Pop
  except EnvironmentError, err:
1287 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "error while reading the"
1288 3ecf6786 Iustin Pop
                           " API version (%s)" % _ErrnoOrStr(err))
1289 a8083063 Iustin Pop
1290 082a7f91 Guido Trotter
  api_versions = [version.strip() for version in api_versions]
1291 a8083063 Iustin Pop
  try:
1292 082a7f91 Guido Trotter
    api_versions = [int(version) for version in api_versions]
1293 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
1294 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir,
1295 305a7297 Guido Trotter
                           "API version is not integer (%s)" % str(err))
1296 a8083063 Iustin Pop
1297 082a7f91 Guido Trotter
  return api_versions
1298 a8083063 Iustin Pop
1299 386b57af Iustin Pop
1300 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
1301 a8083063 Iustin Pop
  """Compute the validity for all OSes.
1302 a8083063 Iustin Pop

1303 10c2650b Iustin Pop
  @type top_dirs: list
1304 10c2650b Iustin Pop
  @param top_dirs: the list of directories in which to
1305 10c2650b Iustin Pop
      search (if not given defaults to
1306 10c2650b Iustin Pop
      L{constants.OS_SEARCH_PATH})
1307 10c2650b Iustin Pop
  @rtype: list of L{objects.OS}
1308 10c2650b Iustin Pop
  @return: an OS object for each name in all the given
1309 10c2650b Iustin Pop
      directories
1310 a8083063 Iustin Pop

1311 a8083063 Iustin Pop
  """
1312 7c3d51d4 Guido Trotter
  if top_dirs is None:
1313 7c3d51d4 Guido Trotter
    top_dirs = constants.OS_SEARCH_PATH
1314 a8083063 Iustin Pop
1315 a8083063 Iustin Pop
  result = []
1316 65fe4693 Iustin Pop
  for dir_name in top_dirs:
1317 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
1318 7c3d51d4 Guido Trotter
      try:
1319 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
1320 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
1321 18682bca Iustin Pop
        logging.exception("Can't list the OS directory %s", dir_name)
1322 7c3d51d4 Guido Trotter
        break
1323 7c3d51d4 Guido Trotter
      for name in f_names:
1324 7c3d51d4 Guido Trotter
        try:
1325 65fe4693 Iustin Pop
          os_inst = OSFromDisk(name, base_dir=dir_name)
1326 7c3d51d4 Guido Trotter
          result.append(os_inst)
1327 7c3d51d4 Guido Trotter
        except errors.InvalidOS, err:
1328 8fa42c7c Guido Trotter
          result.append(objects.OS.FromInvalidOS(err))
1329 a8083063 Iustin Pop
1330 a8083063 Iustin Pop
  return result
1331 a8083063 Iustin Pop
1332 a8083063 Iustin Pop
1333 56bcd3f4 Guido Trotter
def OSFromDisk(name, base_dir=None):
1334 a8083063 Iustin Pop
  """Create an OS instance from disk.
1335 a8083063 Iustin Pop

1336 a8083063 Iustin Pop
  This function will return an OS instance if the given name is a
1337 a8083063 Iustin Pop
  valid OS name. Otherwise, it will raise an appropriate
1338 10c2650b Iustin Pop
  L{errors.InvalidOS} exception, detailing why this is not a valid OS.
1339 a8083063 Iustin Pop

1340 8ee4dc80 Guido Trotter
  @type base_dir: string
1341 8ee4dc80 Guido Trotter
  @keyword base_dir: Base directory containing OS installations.
1342 8ee4dc80 Guido Trotter
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1343 10c2650b Iustin Pop
  @rtype: L{objects.OS}
1344 10c2650b Iustin Pop
  @return: the OS instance if we find a valid one
1345 10c2650b Iustin Pop
  @raise errors.InvalidOS: if we don't find a valid OS
1346 7c3d51d4 Guido Trotter

1347 a8083063 Iustin Pop
  """
1348 56bcd3f4 Guido Trotter
  if base_dir is None:
1349 57c177af Iustin Pop
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1350 c34c0cfd Iustin Pop
    if os_dir is None:
1351 c34c0cfd Iustin Pop
      raise errors.InvalidOS(name, None, "OS dir not found in search path")
1352 c34c0cfd Iustin Pop
  else:
1353 c34c0cfd Iustin Pop
    os_dir = os.path.sep.join([base_dir, name])
1354 a8083063 Iustin Pop
1355 082a7f91 Guido Trotter
  api_versions = _OSOndiskVersion(name, os_dir)
1356 a8083063 Iustin Pop
1357 082a7f91 Guido Trotter
  if constants.OS_API_VERSION not in api_versions:
1358 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "API version mismatch"
1359 305a7297 Guido Trotter
                           " (found %s want %s)"
1360 082a7f91 Guido Trotter
                           % (api_versions, constants.OS_API_VERSION))
1361 a8083063 Iustin Pop
1362 a8083063 Iustin Pop
  # OS Scripts dictionary, we will populate it with the actual script names
1363 62dbbe7e Guido Trotter
  os_scripts = dict.fromkeys(constants.OS_SCRIPTS)
1364 a8083063 Iustin Pop
1365 a8083063 Iustin Pop
  for script in os_scripts:
1366 a8083063 Iustin Pop
    os_scripts[script] = os.path.sep.join([os_dir, script])
1367 a8083063 Iustin Pop
1368 a8083063 Iustin Pop
    try:
1369 a8083063 Iustin Pop
      st = os.stat(os_scripts[script])
1370 a8083063 Iustin Pop
    except EnvironmentError, err:
1371 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' script missing (%s)" %
1372 3ecf6786 Iustin Pop
                             (script, _ErrnoOrStr(err)))
1373 a8083063 Iustin Pop
1374 a8083063 Iustin Pop
    if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1375 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' script not executable" %
1376 305a7297 Guido Trotter
                             script)
1377 a8083063 Iustin Pop
1378 a8083063 Iustin Pop
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1379 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' is not a regular file" %
1380 305a7297 Guido Trotter
                             script)
1381 a8083063 Iustin Pop
1382 a8083063 Iustin Pop
1383 8fa42c7c Guido Trotter
  return objects.OS(name=name, path=os_dir, status=constants.OS_VALID_STATUS,
1384 62dbbe7e Guido Trotter
                    create_script=os_scripts[constants.OS_SCRIPT_CREATE],
1385 62dbbe7e Guido Trotter
                    export_script=os_scripts[constants.OS_SCRIPT_EXPORT],
1386 62dbbe7e Guido Trotter
                    import_script=os_scripts[constants.OS_SCRIPT_IMPORT],
1387 62dbbe7e Guido Trotter
                    rename_script=os_scripts[constants.OS_SCRIPT_RENAME],
1388 082a7f91 Guido Trotter
                    api_versions=api_versions)
1389 a8083063 Iustin Pop
1390 2266edb2 Guido Trotter
def OSEnvironment(instance, debug=0):
1391 2266edb2 Guido Trotter
  """Calculate the environment for an os script.
1392 2266edb2 Guido Trotter

1393 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1394 2266edb2 Guido Trotter
  @param instance: target instance for the os script run
1395 2266edb2 Guido Trotter
  @type debug: integer
1396 10c2650b Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
1397 2266edb2 Guido Trotter
  @rtype: dict
1398 2266edb2 Guido Trotter
  @return: dict of environment variables
1399 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if the block device
1400 10c2650b Iustin Pop
      cannot be found
1401 2266edb2 Guido Trotter

1402 2266edb2 Guido Trotter
  """
1403 2266edb2 Guido Trotter
  result = {}
1404 2266edb2 Guido Trotter
  result['OS_API_VERSION'] = '%d' % constants.OS_API_VERSION
1405 2266edb2 Guido Trotter
  result['INSTANCE_NAME'] = instance.name
1406 2266edb2 Guido Trotter
  result['HYPERVISOR'] = instance.hypervisor
1407 2266edb2 Guido Trotter
  result['DISK_COUNT'] = '%d' % len(instance.disks)
1408 2266edb2 Guido Trotter
  result['NIC_COUNT'] = '%d' % len(instance.nics)
1409 2266edb2 Guido Trotter
  result['DEBUG_LEVEL'] = '%d' % debug
1410 2266edb2 Guido Trotter
  for idx, disk in enumerate(instance.disks):
1411 2266edb2 Guido Trotter
    real_disk = _RecursiveFindBD(disk)
1412 2266edb2 Guido Trotter
    if real_disk is None:
1413 2266edb2 Guido Trotter
      raise errors.BlockDeviceError("Block device '%s' is not set up" %
1414 2266edb2 Guido Trotter
                                    str(disk))
1415 2266edb2 Guido Trotter
    real_disk.Open()
1416 2266edb2 Guido Trotter
    result['DISK_%d_PATH' % idx] = real_disk.dev_path
1417 2266edb2 Guido Trotter
    # FIXME: When disks will have read-only mode, populate this
1418 2266edb2 Guido Trotter
    result['DISK_%d_ACCESS' % idx] = 'W'
1419 2266edb2 Guido Trotter
    if constants.HV_DISK_TYPE in instance.hvparams:
1420 2266edb2 Guido Trotter
      result['DISK_%d_FRONTEND_TYPE' % idx] = \
1421 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_DISK_TYPE]
1422 2266edb2 Guido Trotter
    if disk.dev_type in constants.LDS_BLOCK:
1423 2266edb2 Guido Trotter
      result['DISK_%d_BACKEND_TYPE' % idx] = 'block'
1424 2266edb2 Guido Trotter
    elif disk.dev_type == constants.LD_FILE:
1425 2266edb2 Guido Trotter
      result['DISK_%d_BACKEND_TYPE' % idx] = \
1426 2266edb2 Guido Trotter
        'file:%s' % disk.physical_id[0]
1427 2266edb2 Guido Trotter
  for idx, nic in enumerate(instance.nics):
1428 2266edb2 Guido Trotter
    result['NIC_%d_MAC' % idx] = nic.mac
1429 2266edb2 Guido Trotter
    if nic.ip:
1430 2266edb2 Guido Trotter
      result['NIC_%d_IP' % idx] = nic.ip
1431 2266edb2 Guido Trotter
    result['NIC_%d_BRIDGE' % idx] = nic.bridge
1432 2266edb2 Guido Trotter
    if constants.HV_NIC_TYPE in instance.hvparams:
1433 2266edb2 Guido Trotter
      result['NIC_%d_FRONTEND_TYPE' % idx] = \
1434 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_NIC_TYPE]
1435 2266edb2 Guido Trotter
1436 2266edb2 Guido Trotter
  return result
1437 a8083063 Iustin Pop
1438 594609c0 Iustin Pop
def GrowBlockDevice(disk, amount):
1439 594609c0 Iustin Pop
  """Grow a stack of block devices.
1440 594609c0 Iustin Pop

1441 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
1442 10c2650b Iustin Pop
  first ones to resize.
1443 594609c0 Iustin Pop

1444 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1445 10c2650b Iustin Pop
  @param disk: the disk to be grown
1446 10c2650b Iustin Pop
  @rtype: (status, result)
1447 10c2650b Iustin Pop
  @return: a tuple with the status of the operation
1448 10c2650b Iustin Pop
      (True/False), and the errors message if status
1449 10c2650b Iustin Pop
      is False
1450 594609c0 Iustin Pop

1451 594609c0 Iustin Pop
  """
1452 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1453 594609c0 Iustin Pop
  if r_dev is None:
1454 594609c0 Iustin Pop
    return False, "Cannot find block device %s" % (disk,)
1455 594609c0 Iustin Pop
1456 594609c0 Iustin Pop
  try:
1457 594609c0 Iustin Pop
    r_dev.Grow(amount)
1458 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
1459 594609c0 Iustin Pop
    return False, str(err)
1460 594609c0 Iustin Pop
1461 594609c0 Iustin Pop
  return True, None
1462 594609c0 Iustin Pop
1463 594609c0 Iustin Pop
1464 a8083063 Iustin Pop
def SnapshotBlockDevice(disk):
1465 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
1466 a8083063 Iustin Pop

1467 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
1468 a8083063 Iustin Pop
  just for the leaf lvm backend device.
1469 a8083063 Iustin Pop

1470 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
1471 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
1472 e9e9263d Guido Trotter
  @rtype: string
1473 e9e9263d Guido Trotter
  @return: snapshot disk path
1474 a8083063 Iustin Pop

1475 098c0958 Michael Hanselmann
  """
1476 a8083063 Iustin Pop
  if disk.children:
1477 a8083063 Iustin Pop
    if len(disk.children) == 1:
1478 a8083063 Iustin Pop
      # only one child, let's recurse on it
1479 a8083063 Iustin Pop
      return SnapshotBlockDevice(disk.children[0])
1480 a8083063 Iustin Pop
    else:
1481 a8083063 Iustin Pop
      # more than one child, choose one that matches
1482 a8083063 Iustin Pop
      for child in disk.children:
1483 a8083063 Iustin Pop
        if child.size == disk.size:
1484 a8083063 Iustin Pop
          # return implies breaking the loop
1485 a8083063 Iustin Pop
          return SnapshotBlockDevice(child)
1486 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
1487 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
1488 a8083063 Iustin Pop
    if r_dev is not None:
1489 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
1490 a8083063 Iustin Pop
      return r_dev.Snapshot(disk.size)
1491 a8083063 Iustin Pop
    else:
1492 a8083063 Iustin Pop
      return None
1493 a8083063 Iustin Pop
  else:
1494 3ecf6786 Iustin Pop
    raise errors.ProgrammerError("Cannot snapshot non-lvm block device"
1495 f4bc1f2c Michael Hanselmann
                                 " '%s' of type '%s'" %
1496 3ecf6786 Iustin Pop
                                 (disk.unique_id, disk.dev_type))
1497 a8083063 Iustin Pop
1498 a8083063 Iustin Pop
1499 74c47259 Iustin Pop
def ExportSnapshot(disk, dest_node, instance, cluster_name, idx):
1500 a8083063 Iustin Pop
  """Export a block device snapshot to a remote node.
1501 a8083063 Iustin Pop

1502 74c47259 Iustin Pop
  @type disk: L{objects.Disk}
1503 74c47259 Iustin Pop
  @param disk: the description of the disk to export
1504 74c47259 Iustin Pop
  @type dest_node: str
1505 74c47259 Iustin Pop
  @param dest_node: the destination node to export to
1506 74c47259 Iustin Pop
  @type instance: L{objects.Instance}
1507 74c47259 Iustin Pop
  @param instance: the instance object to whom the disk belongs
1508 74c47259 Iustin Pop
  @type cluster_name: str
1509 74c47259 Iustin Pop
  @param cluster_name: the cluster name, needed for SSH hostalias
1510 74c47259 Iustin Pop
  @type idx: int
1511 74c47259 Iustin Pop
  @param idx: the index of the disk in the instance's disk list,
1512 74c47259 Iustin Pop
      used to export to the OS scripts environment
1513 10c2650b Iustin Pop
  @rtype: boolean
1514 74c47259 Iustin Pop
  @return: the success of the operation
1515 a8083063 Iustin Pop

1516 098c0958 Michael Hanselmann
  """
1517 0607699d Guido Trotter
  export_env = OSEnvironment(instance)
1518 d324e3fc Guido Trotter
1519 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1520 a8083063 Iustin Pop
  export_script = inst_os.export_script
1521 a8083063 Iustin Pop
1522 a8083063 Iustin Pop
  logfile = "%s/exp-%s-%s-%s.log" % (constants.LOG_OS_DIR, inst_os.name,
1523 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
1524 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
1525 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
1526 0607699d Guido Trotter
  real_disk = _RecursiveFindBD(disk)
1527 0607699d Guido Trotter
  if real_disk is None:
1528 a8083063 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
1529 a8083063 Iustin Pop
                                  str(disk))
1530 0607699d Guido Trotter
  real_disk.Open()
1531 0607699d Guido Trotter
1532 0607699d Guido Trotter
  export_env['EXPORT_DEVICE'] = real_disk.dev_path
1533 74c47259 Iustin Pop
  export_env['EXPORT_INDEX'] = str(idx)
1534 a8083063 Iustin Pop
1535 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1536 a8083063 Iustin Pop
  destfile = disk.physical_id[1]
1537 a8083063 Iustin Pop
1538 a8083063 Iustin Pop
  # the target command is built out of three individual commands,
1539 a8083063 Iustin Pop
  # which are joined by pipes; we check each individual command for
1540 a8083063 Iustin Pop
  # valid parameters
1541 0607699d Guido Trotter
  expcmd = utils.BuildShellCmd("cd %s; %s 2>%s", inst_os.path,
1542 0607699d Guido Trotter
                               export_script, logfile)
1543 a8083063 Iustin Pop
1544 a8083063 Iustin Pop
  comprcmd = "gzip"
1545 a8083063 Iustin Pop
1546 72f0f7fd Iustin Pop
  destcmd = utils.BuildShellCmd("mkdir -p %s && cat > %s/%s",
1547 00003458 Guido Trotter
                                destdir, destdir, destfile)
1548 62c9ec92 Iustin Pop
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1549 62c9ec92 Iustin Pop
                                                   constants.GANETI_RUNAS,
1550 62c9ec92 Iustin Pop
                                                   destcmd)
1551 a8083063 Iustin Pop
1552 a8083063 Iustin Pop
  # all commands have been checked, so we're safe to combine them
1553 72f0f7fd Iustin Pop
  command = '|'.join([expcmd, comprcmd, utils.ShellQuoteArgs(remotecmd)])
1554 a8083063 Iustin Pop
1555 0607699d Guido Trotter
  result = utils.RunCmd(command, env=export_env)
1556 a8083063 Iustin Pop
1557 a8083063 Iustin Pop
  if result.failed:
1558 18682bca Iustin Pop
    logging.error("os snapshot export command '%s' returned error: %s"
1559 18682bca Iustin Pop
                  " output: %s", command, result.fail_reason, result.output)
1560 a8083063 Iustin Pop
    return False
1561 a8083063 Iustin Pop
1562 a8083063 Iustin Pop
  return True
1563 a8083063 Iustin Pop
1564 a8083063 Iustin Pop
1565 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
1566 a8083063 Iustin Pop
  """Write out the export configuration information.
1567 a8083063 Iustin Pop

1568 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1569 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
1570 10c2650b Iustin Pop
      saving configuration
1571 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
1572 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
1573 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
1574 a8083063 Iustin Pop

1575 10c2650b Iustin Pop
  @rtype: boolean
1576 10c2650b Iustin Pop
  @return: the success of the operation
1577 a8083063 Iustin Pop

1578 098c0958 Michael Hanselmann
  """
1579 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1580 a8083063 Iustin Pop
  finaldestdir = os.path.join(constants.EXPORT_DIR, instance.name)
1581 a8083063 Iustin Pop
1582 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1583 a8083063 Iustin Pop
1584 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
1585 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'version', '0')
1586 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
1587 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'source', instance.primary_node)
1588 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'os', instance.os)
1589 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'compression', 'gzip')
1590 a8083063 Iustin Pop
1591 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
1592 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'name', instance.name)
1593 51de46bf Iustin Pop
  config.set(constants.INISECT_INS, 'memory', '%d' %
1594 51de46bf Iustin Pop
             instance.beparams[constants.BE_MEMORY])
1595 51de46bf Iustin Pop
  config.set(constants.INISECT_INS, 'vcpus', '%d' %
1596 51de46bf Iustin Pop
             instance.beparams[constants.BE_VCPUS])
1597 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
1598 66f93869 Manuel Franceschini
1599 66f93869 Manuel Franceschini
  nic_count = 0
1600 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
1601 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_mac' %
1602 a8083063 Iustin Pop
               nic_count, '%s' % nic.mac)
1603 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
1604 38206f3c Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_bridge' % nic_count,
1605 38206f3c Iustin Pop
               '%s' % nic.bridge)
1606 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
1607 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_count)
1608 a8083063 Iustin Pop
1609 726d7d68 Iustin Pop
  disk_total = 0
1610 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
1611 19d7f90a Guido Trotter
    if disk:
1612 726d7d68 Iustin Pop
      disk_total += 1
1613 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
1614 19d7f90a Guido Trotter
                 ('%s' % disk.iv_name))
1615 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
1616 19d7f90a Guido Trotter
                 ('%s' % disk.physical_id[1]))
1617 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
1618 19d7f90a Guido Trotter
                 ('%d' % disk.size))
1619 a8083063 Iustin Pop
1620 726d7d68 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_total)
1621 a8083063 Iustin Pop
1622 726d7d68 Iustin Pop
  utils.WriteFile(os.path.join(destdir, constants.EXPORT_CONF_FILE),
1623 726d7d68 Iustin Pop
                  data=config.Dumps())
1624 a8083063 Iustin Pop
  shutil.rmtree(finaldestdir, True)
1625 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
1626 a8083063 Iustin Pop
1627 a8083063 Iustin Pop
  return True
1628 a8083063 Iustin Pop
1629 a8083063 Iustin Pop
1630 a8083063 Iustin Pop
def ExportInfo(dest):
1631 a8083063 Iustin Pop
  """Get export configuration information.
1632 a8083063 Iustin Pop

1633 10c2650b Iustin Pop
  @type dest: str
1634 10c2650b Iustin Pop
  @param dest: directory containing the export
1635 a8083063 Iustin Pop

1636 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
1637 10c2650b Iustin Pop
  @return: a serializable config file containing the
1638 10c2650b Iustin Pop
      export info
1639 a8083063 Iustin Pop

1640 a8083063 Iustin Pop
  """
1641 a8083063 Iustin Pop
  cff = os.path.join(dest, constants.EXPORT_CONF_FILE)
1642 a8083063 Iustin Pop
1643 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1644 a8083063 Iustin Pop
  config.read(cff)
1645 a8083063 Iustin Pop
1646 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
1647 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
1648 a8083063 Iustin Pop
    return None
1649 a8083063 Iustin Pop
1650 a8083063 Iustin Pop
  return config
1651 a8083063 Iustin Pop
1652 a8083063 Iustin Pop
1653 6c0af70e Guido Trotter
def ImportOSIntoInstance(instance, src_node, src_images, cluster_name):
1654 a8083063 Iustin Pop
  """Import an os image into an instance.
1655 a8083063 Iustin Pop

1656 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1657 6c0af70e Guido Trotter
  @param instance: instance to import the disks into
1658 6c0af70e Guido Trotter
  @type src_node: string
1659 6c0af70e Guido Trotter
  @param src_node: source node for the disk images
1660 6c0af70e Guido Trotter
  @type src_images: list of string
1661 6c0af70e Guido Trotter
  @param src_images: absolute paths of the disk images
1662 6c0af70e Guido Trotter
  @rtype: list of boolean
1663 6c0af70e Guido Trotter
  @return: each boolean represent the success of importing the n-th disk
1664 a8083063 Iustin Pop

1665 a8083063 Iustin Pop
  """
1666 6c0af70e Guido Trotter
  import_env = OSEnvironment(instance)
1667 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1668 a8083063 Iustin Pop
  import_script = inst_os.import_script
1669 a8083063 Iustin Pop
1670 a8083063 Iustin Pop
  logfile = "%s/import-%s-%s-%s.log" % (constants.LOG_OS_DIR, instance.os,
1671 a8083063 Iustin Pop
                                        instance.name, int(time.time()))
1672 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
1673 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
1674 a8083063 Iustin Pop
1675 a8083063 Iustin Pop
  comprcmd = "gunzip"
1676 d868edb4 Iustin Pop
  impcmd = utils.BuildShellCmd("(cd %s; %s >%s 2>&1)", inst_os.path,
1677 d868edb4 Iustin Pop
                               import_script, logfile)
1678 a8083063 Iustin Pop
1679 6c0af70e Guido Trotter
  final_result = []
1680 6c0af70e Guido Trotter
  for idx, image in enumerate(src_images):
1681 6c0af70e Guido Trotter
    if image:
1682 6c0af70e Guido Trotter
      destcmd = utils.BuildShellCmd('cat %s', image)
1683 6c0af70e Guido Trotter
      remotecmd = _GetSshRunner(cluster_name).BuildCmd(src_node,
1684 6c0af70e Guido Trotter
                                                       constants.GANETI_RUNAS,
1685 6c0af70e Guido Trotter
                                                       destcmd)
1686 6c0af70e Guido Trotter
      command = '|'.join([utils.ShellQuoteArgs(remotecmd), comprcmd, impcmd])
1687 6c0af70e Guido Trotter
      import_env['IMPORT_DEVICE'] = import_env['DISK_%d_PATH' % idx]
1688 74c47259 Iustin Pop
      import_env['IMPORT_INDEX'] = str(idx)
1689 6c0af70e Guido Trotter
      result = utils.RunCmd(command, env=import_env)
1690 6c0af70e Guido Trotter
      if result.failed:
1691 726d7d68 Iustin Pop
        logging.error("Disk import command '%s' returned error: %s"
1692 726d7d68 Iustin Pop
                      " output: %s", command, result.fail_reason,
1693 726d7d68 Iustin Pop
                      result.output)
1694 6c0af70e Guido Trotter
        final_result.append(False)
1695 6c0af70e Guido Trotter
      else:
1696 6c0af70e Guido Trotter
        final_result.append(True)
1697 6c0af70e Guido Trotter
    else:
1698 6c0af70e Guido Trotter
      final_result.append(True)
1699 a8083063 Iustin Pop
1700 6c0af70e Guido Trotter
  return final_result
1701 a8083063 Iustin Pop
1702 a8083063 Iustin Pop
1703 a8083063 Iustin Pop
def ListExports():
1704 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
1705 098c0958 Michael Hanselmann

1706 10c2650b Iustin Pop
  @rtype: list
1707 10c2650b Iustin Pop
  @return: list of the exports
1708 10c2650b Iustin Pop

1709 a8083063 Iustin Pop
  """
1710 a8083063 Iustin Pop
  if os.path.isdir(constants.EXPORT_DIR):
1711 eedbda4b Michael Hanselmann
    return utils.ListVisibleFiles(constants.EXPORT_DIR)
1712 a8083063 Iustin Pop
  else:
1713 a8083063 Iustin Pop
    return []
1714 a8083063 Iustin Pop
1715 a8083063 Iustin Pop
1716 a8083063 Iustin Pop
def RemoveExport(export):
1717 a8083063 Iustin Pop
  """Remove an existing export from the node.
1718 a8083063 Iustin Pop

1719 10c2650b Iustin Pop
  @type export: str
1720 10c2650b Iustin Pop
  @param export: the name of the export to remove
1721 10c2650b Iustin Pop
  @rtype: boolean
1722 10c2650b Iustin Pop
  @return: the success of the operation
1723 a8083063 Iustin Pop

1724 098c0958 Michael Hanselmann
  """
1725 a8083063 Iustin Pop
  target = os.path.join(constants.EXPORT_DIR, export)
1726 a8083063 Iustin Pop
1727 a8083063 Iustin Pop
  shutil.rmtree(target)
1728 a8083063 Iustin Pop
  # TODO: catch some of the relevant exceptions and provide a pretty
1729 a8083063 Iustin Pop
  # error message if rmtree fails.
1730 a8083063 Iustin Pop
1731 a8083063 Iustin Pop
  return True
1732 a8083063 Iustin Pop
1733 a8083063 Iustin Pop
1734 f3e513ad Iustin Pop
def RenameBlockDevices(devlist):
1735 f3e513ad Iustin Pop
  """Rename a list of block devices.
1736 f3e513ad Iustin Pop

1737 10c2650b Iustin Pop
  @type devlist: list of tuples
1738 10c2650b Iustin Pop
  @param devlist: list of tuples of the form  (disk,
1739 10c2650b Iustin Pop
      new_logical_id, new_physical_id); disk is an
1740 10c2650b Iustin Pop
      L{objects.Disk} object describing the current disk,
1741 10c2650b Iustin Pop
      and new logical_id/physical_id is the name we
1742 10c2650b Iustin Pop
      rename it to
1743 10c2650b Iustin Pop
  @rtype: boolean
1744 10c2650b Iustin Pop
  @return: True if all renames succeeded, False otherwise
1745 f3e513ad Iustin Pop

1746 f3e513ad Iustin Pop
  """
1747 f3e513ad Iustin Pop
  result = True
1748 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
1749 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
1750 f3e513ad Iustin Pop
    if dev is None:
1751 f3e513ad Iustin Pop
      result = False
1752 f3e513ad Iustin Pop
      continue
1753 f3e513ad Iustin Pop
    try:
1754 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
1755 f3e513ad Iustin Pop
      dev.Rename(unique_id)
1756 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
1757 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
1758 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
1759 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
1760 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
1761 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
1762 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
1763 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
1764 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
1765 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
1766 f3e513ad Iustin Pop
      result = False
1767 f3e513ad Iustin Pop
  return result
1768 f3e513ad Iustin Pop
1769 f3e513ad Iustin Pop
1770 778b75bb Manuel Franceschini
def _TransformFileStorageDir(file_storage_dir):
1771 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
1772 778b75bb Manuel Franceschini

1773 778b75bb Manuel Franceschini
  Checks wheter the given file_storage_dir is within the cluster-wide
1774 778b75bb Manuel Franceschini
  default file_storage_dir stored in SimpleStore. Only paths under that
1775 778b75bb Manuel Franceschini
  directory are allowed.
1776 778b75bb Manuel Franceschini

1777 b1206984 Iustin Pop
  @type file_storage_dir: str
1778 b1206984 Iustin Pop
  @param file_storage_dir: the path to check
1779 d61cbe76 Iustin Pop

1780 b1206984 Iustin Pop
  @return: the normalized path if valid, None otherwise
1781 778b75bb Manuel Franceschini

1782 778b75bb Manuel Franceschini
  """
1783 c657dcc9 Michael Hanselmann
  cfg = _GetConfig()
1784 778b75bb Manuel Franceschini
  file_storage_dir = os.path.normpath(file_storage_dir)
1785 c657dcc9 Michael Hanselmann
  base_file_storage_dir = cfg.GetFileStorageDir()
1786 778b75bb Manuel Franceschini
  if (not os.path.commonprefix([file_storage_dir, base_file_storage_dir]) ==
1787 778b75bb Manuel Franceschini
      base_file_storage_dir):
1788 18682bca Iustin Pop
    logging.error("file storage directory '%s' is not under base file"
1789 18682bca Iustin Pop
                  " storage directory '%s'",
1790 18682bca Iustin Pop
                  file_storage_dir, base_file_storage_dir)
1791 778b75bb Manuel Franceschini
    return None
1792 778b75bb Manuel Franceschini
  return file_storage_dir
1793 778b75bb Manuel Franceschini
1794 778b75bb Manuel Franceschini
1795 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
1796 778b75bb Manuel Franceschini
  """Create file storage directory.
1797 778b75bb Manuel Franceschini

1798 b1206984 Iustin Pop
  @type file_storage_dir: str
1799 b1206984 Iustin Pop
  @param file_storage_dir: directory to create
1800 778b75bb Manuel Franceschini

1801 b1206984 Iustin Pop
  @rtype: tuple
1802 b1206984 Iustin Pop
  @return: tuple with first element a boolean indicating wheter dir
1803 b1206984 Iustin Pop
      creation was successful or not
1804 778b75bb Manuel Franceschini

1805 778b75bb Manuel Franceschini
  """
1806 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
1807 778b75bb Manuel Franceschini
  result = True,
1808 778b75bb Manuel Franceschini
  if not file_storage_dir:
1809 778b75bb Manuel Franceschini
    result = False,
1810 778b75bb Manuel Franceschini
  else:
1811 778b75bb Manuel Franceschini
    if os.path.exists(file_storage_dir):
1812 778b75bb Manuel Franceschini
      if not os.path.isdir(file_storage_dir):
1813 18682bca Iustin Pop
        logging.error("'%s' is not a directory", file_storage_dir)
1814 778b75bb Manuel Franceschini
        result = False,
1815 778b75bb Manuel Franceschini
    else:
1816 778b75bb Manuel Franceschini
      try:
1817 778b75bb Manuel Franceschini
        os.makedirs(file_storage_dir, 0750)
1818 778b75bb Manuel Franceschini
      except OSError, err:
1819 18682bca Iustin Pop
        logging.error("Cannot create file storage directory '%s': %s",
1820 18682bca Iustin Pop
                      file_storage_dir, err)
1821 778b75bb Manuel Franceschini
        result = False,
1822 778b75bb Manuel Franceschini
  return result
1823 778b75bb Manuel Franceschini
1824 778b75bb Manuel Franceschini
1825 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
1826 778b75bb Manuel Franceschini
  """Remove file storage directory.
1827 778b75bb Manuel Franceschini

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

1830 10c2650b Iustin Pop
  @type file_storage_dir: str
1831 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
1832 10c2650b Iustin Pop
  @rtype: tuple (success,)
1833 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
1834 10c2650b Iustin Pop
      whether the operation was successfull
1835 778b75bb Manuel Franceschini

1836 778b75bb Manuel Franceschini
  """
1837 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
1838 778b75bb Manuel Franceschini
  result = True,
1839 778b75bb Manuel Franceschini
  if not file_storage_dir:
1840 778b75bb Manuel Franceschini
    result = False,
1841 778b75bb Manuel Franceschini
  else:
1842 778b75bb Manuel Franceschini
    if os.path.exists(file_storage_dir):
1843 778b75bb Manuel Franceschini
      if not os.path.isdir(file_storage_dir):
1844 18682bca Iustin Pop
        logging.error("'%s' is not a directory", file_storage_dir)
1845 778b75bb Manuel Franceschini
        result = False,
1846 778b75bb Manuel Franceschini
      # deletes dir only if empty, otherwise we want to return False
1847 778b75bb Manuel Franceschini
      try:
1848 778b75bb Manuel Franceschini
        os.rmdir(file_storage_dir)
1849 778b75bb Manuel Franceschini
      except OSError, err:
1850 18682bca Iustin Pop
        logging.exception("Cannot remove file storage directory '%s'",
1851 18682bca Iustin Pop
                          file_storage_dir)
1852 778b75bb Manuel Franceschini
        result = False,
1853 778b75bb Manuel Franceschini
  return result
1854 778b75bb Manuel Franceschini
1855 778b75bb Manuel Franceschini
1856 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
1857 778b75bb Manuel Franceschini
  """Rename the file storage directory.
1858 778b75bb Manuel Franceschini

1859 10c2650b Iustin Pop
  @type old_file_storage_dir: str
1860 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
1861 10c2650b Iustin Pop
  @type new_file_storage_dir: str
1862 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
1863 10c2650b Iustin Pop
  @rtype: tuple (success,)
1864 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
1865 10c2650b Iustin Pop
      whether the operation was successful
1866 778b75bb Manuel Franceschini

1867 778b75bb Manuel Franceschini
  """
1868 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
1869 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
1870 778b75bb Manuel Franceschini
  result = True,
1871 778b75bb Manuel Franceschini
  if not old_file_storage_dir or not new_file_storage_dir:
1872 778b75bb Manuel Franceschini
    result = False,
1873 778b75bb Manuel Franceschini
  else:
1874 778b75bb Manuel Franceschini
    if not os.path.exists(new_file_storage_dir):
1875 778b75bb Manuel Franceschini
      if os.path.isdir(old_file_storage_dir):
1876 778b75bb Manuel Franceschini
        try:
1877 778b75bb Manuel Franceschini
          os.rename(old_file_storage_dir, new_file_storage_dir)
1878 778b75bb Manuel Franceschini
        except OSError, err:
1879 18682bca Iustin Pop
          logging.exception("Cannot rename '%s' to '%s'",
1880 18682bca Iustin Pop
                            old_file_storage_dir, new_file_storage_dir)
1881 778b75bb Manuel Franceschini
          result =  False,
1882 778b75bb Manuel Franceschini
      else:
1883 18682bca Iustin Pop
        logging.error("'%s' is not a directory", old_file_storage_dir)
1884 778b75bb Manuel Franceschini
        result = False,
1885 778b75bb Manuel Franceschini
    else:
1886 778b75bb Manuel Franceschini
      if os.path.exists(old_file_storage_dir):
1887 18682bca Iustin Pop
        logging.error("Cannot rename '%s' to '%s'. Both locations exist.",
1888 18682bca Iustin Pop
                      old_file_storage_dir, new_file_storage_dir)
1889 778b75bb Manuel Franceschini
        result = False,
1890 778b75bb Manuel Franceschini
  return result
1891 778b75bb Manuel Franceschini
1892 778b75bb Manuel Franceschini
1893 dc31eae3 Michael Hanselmann
def _IsJobQueueFile(file_name):
1894 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
1895 ca52cdeb Michael Hanselmann

1896 10c2650b Iustin Pop
  @type file_name: str
1897 10c2650b Iustin Pop
  @param file_name: the file name we should check
1898 10c2650b Iustin Pop
  @rtype: boolean
1899 10c2650b Iustin Pop
  @return: whether the file is under the queue directory
1900 10c2650b Iustin Pop

1901 ca52cdeb Michael Hanselmann
  """
1902 ca52cdeb Michael Hanselmann
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
1903 dc31eae3 Michael Hanselmann
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
1904 dc31eae3 Michael Hanselmann
1905 dc31eae3 Michael Hanselmann
  if not result:
1906 ca52cdeb Michael Hanselmann
    logging.error("'%s' is not a file in the queue directory",
1907 ca52cdeb Michael Hanselmann
                  file_name)
1908 dc31eae3 Michael Hanselmann
1909 dc31eae3 Michael Hanselmann
  return result
1910 dc31eae3 Michael Hanselmann
1911 dc31eae3 Michael Hanselmann
1912 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
1913 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
1914 dc31eae3 Michael Hanselmann

1915 10c2650b Iustin Pop
  This is just a wrapper over L{utils.WriteFile}, with proper
1916 10c2650b Iustin Pop
  checking.
1917 10c2650b Iustin Pop

1918 10c2650b Iustin Pop
  @type file_name: str
1919 10c2650b Iustin Pop
  @param file_name: the job file name
1920 10c2650b Iustin Pop
  @type content: str
1921 10c2650b Iustin Pop
  @param content: the new job contents
1922 10c2650b Iustin Pop
  @rtype: boolean
1923 10c2650b Iustin Pop
  @return: the success of the operation
1924 10c2650b Iustin Pop

1925 dc31eae3 Michael Hanselmann
  """
1926 dc31eae3 Michael Hanselmann
  if not _IsJobQueueFile(file_name):
1927 ca52cdeb Michael Hanselmann
    return False
1928 ca52cdeb Michael Hanselmann
1929 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
1930 ca52cdeb Michael Hanselmann
  utils.WriteFile(file_name, data=content)
1931 ca52cdeb Michael Hanselmann
1932 ca52cdeb Michael Hanselmann
  return True
1933 ca52cdeb Michael Hanselmann
1934 ca52cdeb Michael Hanselmann
1935 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
1936 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
1937 af5ebcb1 Michael Hanselmann

1938 10c2650b Iustin Pop
  This is just a wrapper over L{os.rename} with proper checking.
1939 10c2650b Iustin Pop

1940 10c2650b Iustin Pop
  @type old: str
1941 10c2650b Iustin Pop
  @param old: the old (actual) file name
1942 10c2650b Iustin Pop
  @type new: str
1943 10c2650b Iustin Pop
  @param new: the desired file name
1944 10c2650b Iustin Pop
  @rtype: boolean
1945 10c2650b Iustin Pop
  @return: the success of the operation
1946 10c2650b Iustin Pop

1947 af5ebcb1 Michael Hanselmann
  """
1948 af5ebcb1 Michael Hanselmann
  if not (_IsJobQueueFile(old) and _IsJobQueueFile(new)):
1949 af5ebcb1 Michael Hanselmann
    return False
1950 af5ebcb1 Michael Hanselmann
1951 af5ebcb1 Michael Hanselmann
  os.rename(old, new)
1952 af5ebcb1 Michael Hanselmann
1953 af5ebcb1 Michael Hanselmann
  return True
1954 af5ebcb1 Michael Hanselmann
1955 af5ebcb1 Michael Hanselmann
1956 5d672980 Iustin Pop
def JobQueueSetDrainFlag(drain_flag):
1957 5d672980 Iustin Pop
  """Set the drain flag for the queue.
1958 5d672980 Iustin Pop

1959 5d672980 Iustin Pop
  This will set or unset the queue drain flag.
1960 5d672980 Iustin Pop

1961 10c2650b Iustin Pop
  @type drain_flag: boolean
1962 5d672980 Iustin Pop
  @param drain_flag: if True, will set the drain flag, otherwise reset it.
1963 10c2650b Iustin Pop
  @rtype: boolean
1964 10c2650b Iustin Pop
  @return: always True
1965 10c2650b Iustin Pop
  @warning: the function always returns True
1966 5d672980 Iustin Pop

1967 5d672980 Iustin Pop
  """
1968 5d672980 Iustin Pop
  if drain_flag:
1969 5d672980 Iustin Pop
    utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True)
1970 5d672980 Iustin Pop
  else:
1971 5d672980 Iustin Pop
    utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
1972 5d672980 Iustin Pop
1973 5d672980 Iustin Pop
  return True
1974 5d672980 Iustin Pop
1975 5d672980 Iustin Pop
1976 d61cbe76 Iustin Pop
def CloseBlockDevices(disks):
1977 d61cbe76 Iustin Pop
  """Closes the given block devices.
1978 d61cbe76 Iustin Pop

1979 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
1980 10c2650b Iustin Pop
  DRBD).
1981 10c2650b Iustin Pop

1982 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
1983 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
1984 10c2650b Iustin Pop
  @rtype: tuple (success, message)
1985 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
1986 10c2650b Iustin Pop
      indicates the succes of the operation, and message
1987 10c2650b Iustin Pop
      which will contain the error details in case we
1988 10c2650b Iustin Pop
      failed
1989 d61cbe76 Iustin Pop

1990 d61cbe76 Iustin Pop
  """
1991 d61cbe76 Iustin Pop
  bdevs = []
1992 d61cbe76 Iustin Pop
  for cf in disks:
1993 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
1994 d61cbe76 Iustin Pop
    if rd is None:
1995 d61cbe76 Iustin Pop
      return (False, "Can't find device %s" % cf)
1996 d61cbe76 Iustin Pop
    bdevs.append(rd)
1997 d61cbe76 Iustin Pop
1998 d61cbe76 Iustin Pop
  msg = []
1999 d61cbe76 Iustin Pop
  for rd in bdevs:
2000 d61cbe76 Iustin Pop
    try:
2001 d61cbe76 Iustin Pop
      rd.Close()
2002 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
2003 d61cbe76 Iustin Pop
      msg.append(str(err))
2004 d61cbe76 Iustin Pop
  if msg:
2005 d61cbe76 Iustin Pop
    return (False, "Can't make devices secondary: %s" % ",".join(msg))
2006 d61cbe76 Iustin Pop
  else:
2007 d61cbe76 Iustin Pop
    return (True, "All devices secondary")
2008 d61cbe76 Iustin Pop
2009 d61cbe76 Iustin Pop
2010 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
2011 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
2012 6217e295 Iustin Pop

2013 6217e295 Iustin Pop
  @type hvname: string
2014 6217e295 Iustin Pop
  @param hvname: the hypervisor name
2015 6217e295 Iustin Pop
  @type hvparams: dict
2016 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
2017 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2018 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2019 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2020 10c2650b Iustin Pop
      which will contain the error details in case we
2021 10c2650b Iustin Pop
      failed
2022 6217e295 Iustin Pop

2023 6217e295 Iustin Pop
  """
2024 6217e295 Iustin Pop
  try:
2025 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
2026 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
2027 6217e295 Iustin Pop
    return (True, "Validation passed")
2028 6217e295 Iustin Pop
  except errors.HypervisorError, err:
2029 6217e295 Iustin Pop
    return (False, str(err))
2030 6217e295 Iustin Pop
2031 6217e295 Iustin Pop
2032 a8083063 Iustin Pop
class HooksRunner(object):
2033 a8083063 Iustin Pop
  """Hook runner.
2034 a8083063 Iustin Pop

2035 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
2036 10c2650b Iustin Pop
  on the master side.
2037 a8083063 Iustin Pop

2038 a8083063 Iustin Pop
  """
2039 a8083063 Iustin Pop
  RE_MASK = re.compile("^[a-zA-Z0-9_-]+$")
2040 a8083063 Iustin Pop
2041 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
2042 a8083063 Iustin Pop
    """Constructor for hooks runner.
2043 a8083063 Iustin Pop

2044 10c2650b Iustin Pop
    @type hooks_base_dir: str or None
2045 10c2650b Iustin Pop
    @param hooks_base_dir: if not None, this overrides the
2046 10c2650b Iustin Pop
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
2047 a8083063 Iustin Pop

2048 a8083063 Iustin Pop
    """
2049 a8083063 Iustin Pop
    if hooks_base_dir is None:
2050 a8083063 Iustin Pop
      hooks_base_dir = constants.HOOKS_BASE_DIR
2051 a8083063 Iustin Pop
    self._BASE_DIR = hooks_base_dir
2052 a8083063 Iustin Pop
2053 a8083063 Iustin Pop
  @staticmethod
2054 a8083063 Iustin Pop
  def ExecHook(script, env):
2055 a8083063 Iustin Pop
    """Exec one hook script.
2056 a8083063 Iustin Pop

2057 10c2650b Iustin Pop
    @type script: str
2058 10c2650b Iustin Pop
    @param script: the full path to the script
2059 10c2650b Iustin Pop
    @type env: dict
2060 10c2650b Iustin Pop
    @param env: the environment with which to exec the script
2061 10c2650b Iustin Pop
    @rtype: tuple (success, message)
2062 10c2650b Iustin Pop
    @return: a tuple of success and message, where success
2063 10c2650b Iustin Pop
        indicates the succes of the operation, and message
2064 10c2650b Iustin Pop
        which will contain the error details in case we
2065 10c2650b Iustin Pop
        failed
2066 a8083063 Iustin Pop

2067 a8083063 Iustin Pop
    """
2068 a8083063 Iustin Pop
    # exec the process using subprocess and log the output
2069 a8083063 Iustin Pop
    fdstdin = None
2070 a8083063 Iustin Pop
    try:
2071 a8083063 Iustin Pop
      fdstdin = open("/dev/null", "r")
2072 a8083063 Iustin Pop
      child = subprocess.Popen([script], stdin=fdstdin, stdout=subprocess.PIPE,
2073 a8083063 Iustin Pop
                               stderr=subprocess.STDOUT, close_fds=True,
2074 147af04d Iustin Pop
                               shell=False, cwd="/", env=env)
2075 a8083063 Iustin Pop
      output = ""
2076 a8083063 Iustin Pop
      try:
2077 a8083063 Iustin Pop
        output = child.stdout.read(4096)
2078 a8083063 Iustin Pop
        child.stdout.close()
2079 a8083063 Iustin Pop
      except EnvironmentError, err:
2080 a8083063 Iustin Pop
        output += "Hook script error: %s" % str(err)
2081 a8083063 Iustin Pop
2082 a8083063 Iustin Pop
      while True:
2083 a8083063 Iustin Pop
        try:
2084 a8083063 Iustin Pop
          result = child.wait()
2085 a8083063 Iustin Pop
          break
2086 a8083063 Iustin Pop
        except EnvironmentError, err:
2087 a8083063 Iustin Pop
          if err.errno == errno.EINTR:
2088 a8083063 Iustin Pop
            continue
2089 a8083063 Iustin Pop
          raise
2090 a8083063 Iustin Pop
    finally:
2091 a8083063 Iustin Pop
      # try not to leak fds
2092 a8083063 Iustin Pop
      for fd in (fdstdin, ):
2093 a8083063 Iustin Pop
        if fd is not None:
2094 a8083063 Iustin Pop
          try:
2095 a8083063 Iustin Pop
            fd.close()
2096 a8083063 Iustin Pop
          except EnvironmentError, err:
2097 a8083063 Iustin Pop
            # just log the error
2098 18682bca Iustin Pop
            #logging.exception("Error while closing fd %s", fd)
2099 a8083063 Iustin Pop
            pass
2100 a8083063 Iustin Pop
2101 a8083063 Iustin Pop
    return result == 0, output
2102 a8083063 Iustin Pop
2103 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
2104 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
2105 a8083063 Iustin Pop

2106 10c2650b Iustin Pop
    @type hpath: str
2107 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
2108 10c2650b Iustin Pop
        holds the scripts
2109 10c2650b Iustin Pop
    @type phase: str
2110 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
2111 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
2112 10c2650b Iustin Pop
    @type env: dict
2113 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
2114 10c2650b Iustin Pop
    @rtype: list
2115 10c2650b Iustin Pop
    @return: list of 3-element tuples:
2116 10c2650b Iustin Pop
      - script path
2117 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
2118 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
2119 10c2650b Iustin Pop
      - output of the script
2120 10c2650b Iustin Pop

2121 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
2122 10c2650b Iustin Pop
        parameters
2123 a8083063 Iustin Pop

2124 a8083063 Iustin Pop
    """
2125 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
2126 a8083063 Iustin Pop
      suffix = "pre"
2127 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
2128 a8083063 Iustin Pop
      suffix = "post"
2129 a8083063 Iustin Pop
    else:
2130 3ecf6786 Iustin Pop
      raise errors.ProgrammerError("Unknown hooks phase: '%s'" % phase)
2131 a8083063 Iustin Pop
    rr = []
2132 a8083063 Iustin Pop
2133 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
2134 a8083063 Iustin Pop
    dir_name = "%s/%s" % (self._BASE_DIR, subdir)
2135 a8083063 Iustin Pop
    try:
2136 eedbda4b Michael Hanselmann
      dir_contents = utils.ListVisibleFiles(dir_name)
2137 a8083063 Iustin Pop
    except OSError, err:
2138 10c2650b Iustin Pop
      # FIXME: must log output in case of failures
2139 a8083063 Iustin Pop
      return rr
2140 a8083063 Iustin Pop
2141 a8083063 Iustin Pop
    # we use the standard python sort order,
2142 a8083063 Iustin Pop
    # so 00name is the recommended naming scheme
2143 a8083063 Iustin Pop
    dir_contents.sort()
2144 a8083063 Iustin Pop
    for relname in dir_contents:
2145 a8083063 Iustin Pop
      fname = os.path.join(dir_name, relname)
2146 a8083063 Iustin Pop
      if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and
2147 a8083063 Iustin Pop
          self.RE_MASK.match(relname) is not None):
2148 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
2149 a8083063 Iustin Pop
        output = ""
2150 a8083063 Iustin Pop
      else:
2151 a8083063 Iustin Pop
        result, output = self.ExecHook(fname, env)
2152 a8083063 Iustin Pop
        if not result:
2153 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
2154 a8083063 Iustin Pop
        else:
2155 a8083063 Iustin Pop
          rrval = constants.HKR_SUCCESS
2156 a8083063 Iustin Pop
      rr.append(("%s/%s" % (subdir, relname), rrval, output))
2157 a8083063 Iustin Pop
2158 a8083063 Iustin Pop
    return rr
2159 3f78eef2 Iustin Pop
2160 3f78eef2 Iustin Pop
2161 8d528b7c Iustin Pop
class IAllocatorRunner(object):
2162 8d528b7c Iustin Pop
  """IAllocator runner.
2163 8d528b7c Iustin Pop

2164 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
2165 8d528b7c Iustin Pop
  the master side.
2166 8d528b7c Iustin Pop

2167 8d528b7c Iustin Pop
  """
2168 8d528b7c Iustin Pop
  def Run(self, name, idata):
2169 8d528b7c Iustin Pop
    """Run an iallocator script.
2170 8d528b7c Iustin Pop

2171 10c2650b Iustin Pop
    @type name: str
2172 10c2650b Iustin Pop
    @param name: the iallocator script name
2173 10c2650b Iustin Pop
    @type idata: str
2174 10c2650b Iustin Pop
    @param idata: the allocator input data
2175 10c2650b Iustin Pop

2176 10c2650b Iustin Pop
    @rtype: tuple
2177 10c2650b Iustin Pop
    @return: four element tuple of:
2178 8d528b7c Iustin Pop
       - run status (one of the IARUN_ constants)
2179 8d528b7c Iustin Pop
       - stdout
2180 8d528b7c Iustin Pop
       - stderr
2181 10c2650b Iustin Pop
       - fail reason (as from L{utils.RunResult})
2182 8d528b7c Iustin Pop

2183 8d528b7c Iustin Pop
    """
2184 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
2185 8d528b7c Iustin Pop
                                  os.path.isfile)
2186 8d528b7c Iustin Pop
    if alloc_script is None:
2187 8d528b7c Iustin Pop
      return (constants.IARUN_NOTFOUND, None, None, None)
2188 8d528b7c Iustin Pop
2189 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
2190 8d528b7c Iustin Pop
    try:
2191 8d528b7c Iustin Pop
      os.write(fd, idata)
2192 8d528b7c Iustin Pop
      os.close(fd)
2193 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
2194 8d528b7c Iustin Pop
      if result.failed:
2195 8d528b7c Iustin Pop
        return (constants.IARUN_FAILURE, result.stdout, result.stderr,
2196 8d528b7c Iustin Pop
                result.fail_reason)
2197 8d528b7c Iustin Pop
    finally:
2198 8d528b7c Iustin Pop
      os.unlink(fin_name)
2199 8d528b7c Iustin Pop
2200 8d528b7c Iustin Pop
    return (constants.IARUN_SUCCESS, result.stdout, result.stderr, None)
2201 8d528b7c Iustin Pop
2202 8d528b7c Iustin Pop
2203 3f78eef2 Iustin Pop
class DevCacheManager(object):
2204 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
2205 3f78eef2 Iustin Pop

2206 3f78eef2 Iustin Pop
  """
2207 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
2208 3f78eef2 Iustin Pop
  _ROOT_DIR = constants.BDEV_CACHE_DIR
2209 3f78eef2 Iustin Pop
2210 3f78eef2 Iustin Pop
  @classmethod
2211 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
2212 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
2213 3f78eef2 Iustin Pop

2214 3f78eef2 Iustin Pop
    This replaces slashes with underscores and strips the /dev
2215 10c2650b Iustin Pop
    prefix. It then returns the full path to the cache file.
2216 10c2650b Iustin Pop

2217 10c2650b Iustin Pop
    @type dev_path: str
2218 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
2219 10c2650b Iustin Pop
    @rtype: str
2220 10c2650b Iustin Pop
    @return: the converted path name
2221 3f78eef2 Iustin Pop

2222 3f78eef2 Iustin Pop
    """
2223 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
2224 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
2225 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
2226 3f78eef2 Iustin Pop
    fpath = "%s/bdev_%s" % (cls._ROOT_DIR, dev_path)
2227 3f78eef2 Iustin Pop
    return fpath
2228 3f78eef2 Iustin Pop
2229 3f78eef2 Iustin Pop
  @classmethod
2230 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
2231 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
2232 3f78eef2 Iustin Pop

2233 10c2650b Iustin Pop
    @type dev_path: str
2234 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
2235 10c2650b Iustin Pop
    @type owner: str
2236 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
2237 10c2650b Iustin Pop
    @type on_primary: bool
2238 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
2239 10c2650b Iustin Pop
        node nor not
2240 10c2650b Iustin Pop
    @type iv_name: str
2241 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
2242 10c2650b Iustin Pop
        device, as in L{objects.Disk.iv_name}
2243 10c2650b Iustin Pop

2244 10c2650b Iustin Pop
    @rtype: None
2245 10c2650b Iustin Pop

2246 3f78eef2 Iustin Pop
    """
2247 cf5a8306 Iustin Pop
    if dev_path is None:
2248 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
2249 cf5a8306 Iustin Pop
      return
2250 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
2251 3f78eef2 Iustin Pop
    if on_primary:
2252 3f78eef2 Iustin Pop
      state = "primary"
2253 3f78eef2 Iustin Pop
    else:
2254 3f78eef2 Iustin Pop
      state = "secondary"
2255 3f78eef2 Iustin Pop
    if iv_name is None:
2256 3f78eef2 Iustin Pop
      iv_name = "not_visible"
2257 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
2258 3f78eef2 Iustin Pop
    try:
2259 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
2260 3f78eef2 Iustin Pop
    except EnvironmentError, err:
2261 18682bca Iustin Pop
      logging.exception("Can't update bdev cache for %s", dev_path)
2262 3f78eef2 Iustin Pop
2263 3f78eef2 Iustin Pop
  @classmethod
2264 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
2265 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
2266 3f78eef2 Iustin Pop

2267 10c2650b Iustin Pop
    This is just a wrapper over L{utils.RemoveFile} with a converted
2268 10c2650b Iustin Pop
    path name and logging.
2269 10c2650b Iustin Pop

2270 10c2650b Iustin Pop
    @type dev_path: str
2271 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
2272 10c2650b Iustin Pop

2273 10c2650b Iustin Pop
    @rtype: None
2274 10c2650b Iustin Pop

2275 3f78eef2 Iustin Pop
    """
2276 cf5a8306 Iustin Pop
    if dev_path is None:
2277 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
2278 cf5a8306 Iustin Pop
      return
2279 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
2280 3f78eef2 Iustin Pop
    try:
2281 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
2282 3f78eef2 Iustin Pop
    except EnvironmentError, err:
2283 18682bca Iustin Pop
      logging.exception("Can't update bdev cache for %s", dev_path)