Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ cd42d0ad

History | View | Annotate | Download (77.9 kB)

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

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

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

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

68 10c2650b Iustin Pop
  """
69 62c9ec92 Iustin Pop
  return ssh.SshRunner(cluster_name)
70 c92b310a Michael Hanselmann
71 c92b310a Michael Hanselmann
72 12bce260 Michael Hanselmann
def _Decompress(data):
73 12bce260 Michael Hanselmann
  """Unpacks data compressed by the RPC client.
74 12bce260 Michael Hanselmann

75 12bce260 Michael Hanselmann
  @type data: list or tuple
76 12bce260 Michael Hanselmann
  @param data: Data sent by RPC client
77 12bce260 Michael Hanselmann
  @rtype: str
78 12bce260 Michael Hanselmann
  @return: Decompressed data
79 12bce260 Michael Hanselmann

80 12bce260 Michael Hanselmann
  """
81 52e2f66e Michael Hanselmann
  assert isinstance(data, (list, tuple))
82 12bce260 Michael Hanselmann
  assert len(data) == 2
83 12bce260 Michael Hanselmann
  (encoding, content) = data
84 12bce260 Michael Hanselmann
  if encoding == constants.RPC_ENCODING_NONE:
85 12bce260 Michael Hanselmann
    return content
86 12bce260 Michael Hanselmann
  elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
87 12bce260 Michael Hanselmann
    return zlib.decompress(base64.b64decode(content))
88 12bce260 Michael Hanselmann
  else:
89 12bce260 Michael Hanselmann
    raise AssertionError("Unknown data encoding")
90 12bce260 Michael Hanselmann
91 12bce260 Michael Hanselmann
92 3bc6be5c Iustin Pop
def _CleanDirectory(path, exclude=None):
93 76ab5558 Michael Hanselmann
  """Removes all regular files in a directory.
94 76ab5558 Michael Hanselmann

95 10c2650b Iustin Pop
  @type path: str
96 10c2650b Iustin Pop
  @param path: the directory to clean
97 76ab5558 Michael Hanselmann
  @type exclude: list
98 10c2650b Iustin Pop
  @param exclude: list of files to be excluded, defaults
99 10c2650b Iustin Pop
      to the empty list
100 76ab5558 Michael Hanselmann

101 76ab5558 Michael Hanselmann
  """
102 3956cee1 Michael Hanselmann
  if not os.path.isdir(path):
103 3956cee1 Michael Hanselmann
    return
104 3bc6be5c Iustin Pop
  if exclude is None:
105 3bc6be5c Iustin Pop
    exclude = []
106 3bc6be5c Iustin Pop
  else:
107 3bc6be5c Iustin Pop
    # Normalize excluded paths
108 3bc6be5c Iustin Pop
    exclude = [os.path.normpath(i) for i in exclude]
109 76ab5558 Michael Hanselmann
110 3956cee1 Michael Hanselmann
  for rel_name in utils.ListVisibleFiles(path):
111 76ab5558 Michael Hanselmann
    full_name = os.path.normpath(os.path.join(path, rel_name))
112 76ab5558 Michael Hanselmann
    if full_name in exclude:
113 76ab5558 Michael Hanselmann
      continue
114 3956cee1 Michael Hanselmann
    if os.path.isfile(full_name) and not os.path.islink(full_name):
115 3956cee1 Michael Hanselmann
      utils.RemoveFile(full_name)
116 3956cee1 Michael Hanselmann
117 3956cee1 Michael Hanselmann
118 1bc59f76 Michael Hanselmann
def JobQueuePurge():
119 10c2650b Iustin Pop
  """Removes job queue files and archived jobs.
120 10c2650b Iustin Pop

121 10c2650b Iustin Pop
  @rtype: None
122 24fc781f Michael Hanselmann

123 24fc781f Michael Hanselmann
  """
124 1bc59f76 Michael Hanselmann
  _CleanDirectory(constants.QUEUE_DIR, exclude=[constants.JOB_QUEUE_LOCK_FILE])
125 24fc781f Michael Hanselmann
  _CleanDirectory(constants.JOB_QUEUE_ARCHIVE_DIR)
126 24fc781f Michael Hanselmann
127 24fc781f Michael Hanselmann
128 bd1e4562 Iustin Pop
def GetMasterInfo():
129 bd1e4562 Iustin Pop
  """Returns master information.
130 bd1e4562 Iustin Pop

131 bd1e4562 Iustin Pop
  This is an utility function to compute master information, either
132 bd1e4562 Iustin Pop
  for consumption here or from the node daemon.
133 bd1e4562 Iustin Pop

134 bd1e4562 Iustin Pop
  @rtype: tuple
135 10c2650b Iustin Pop
  @return: (master_netdev, master_ip, master_name) if we have a good
136 10c2650b Iustin Pop
      configuration, otherwise (None, None, None)
137 b1b6ea87 Iustin Pop

138 b1b6ea87 Iustin Pop
  """
139 b1b6ea87 Iustin Pop
  try:
140 c657dcc9 Michael Hanselmann
    cfg = _GetConfig()
141 c657dcc9 Michael Hanselmann
    master_netdev = cfg.GetMasterNetdev()
142 c657dcc9 Michael Hanselmann
    master_ip = cfg.GetMasterIP()
143 c657dcc9 Michael Hanselmann
    master_node = cfg.GetMasterNode()
144 b1b6ea87 Iustin Pop
  except errors.ConfigurationError, err:
145 b1b6ea87 Iustin Pop
    logging.exception("Cluster configuration incomplete")
146 0a70a72a Iustin Pop
    return (None, None, None)
147 bd1e4562 Iustin Pop
  return (master_netdev, master_ip, master_node)
148 b1b6ea87 Iustin Pop
149 b1b6ea87 Iustin Pop
150 1c65840b Iustin Pop
def StartMaster(start_daemons):
151 a8083063 Iustin Pop
  """Activate local node as master node.
152 a8083063 Iustin Pop

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

157 10c2650b Iustin Pop
  @type start_daemons: boolean
158 10c2650b Iustin Pop
  @param start_daemons: whther to also start the master
159 10c2650b Iustin Pop
      daemons (ganeti-masterd and ganeti-rapi)
160 10c2650b Iustin Pop
  @rtype: None
161 a8083063 Iustin Pop

162 a8083063 Iustin Pop
  """
163 b1b6ea87 Iustin Pop
  ok = True
164 bd1e4562 Iustin Pop
  master_netdev, master_ip, _ = GetMasterInfo()
165 b1b6ea87 Iustin Pop
  if not master_netdev:
166 a8083063 Iustin Pop
    return False
167 a8083063 Iustin Pop
168 b1b6ea87 Iustin Pop
  if utils.TcpPing(master_ip, constants.DEFAULT_NODED_PORT):
169 caad16e2 Iustin Pop
    if utils.OwnIpAddress(master_ip):
170 b1b6ea87 Iustin Pop
      # we already have the ip:
171 b1b6ea87 Iustin Pop
      logging.debug("Already started")
172 b1b6ea87 Iustin Pop
    else:
173 b1b6ea87 Iustin Pop
      logging.error("Someone else has the master ip, not activating")
174 b1b6ea87 Iustin Pop
      ok = False
175 b1b6ea87 Iustin Pop
  else:
176 b1b6ea87 Iustin Pop
    result = utils.RunCmd(["ip", "address", "add", "%s/32" % master_ip,
177 b1b6ea87 Iustin Pop
                           "dev", master_netdev, "label",
178 b1b6ea87 Iustin Pop
                           "%s:0" % master_netdev])
179 b1b6ea87 Iustin Pop
    if result.failed:
180 b1b6ea87 Iustin Pop
      logging.error("Can't activate master IP: %s", result.output)
181 b1b6ea87 Iustin Pop
      ok = False
182 b1b6ea87 Iustin Pop
183 b1b6ea87 Iustin Pop
    result = utils.RunCmd(["arping", "-q", "-U", "-c 3", "-I", master_netdev,
184 b1b6ea87 Iustin Pop
                           "-s", master_ip, master_ip])
185 b1b6ea87 Iustin Pop
    # we'll ignore the exit code of arping
186 b1b6ea87 Iustin Pop
187 b1b6ea87 Iustin Pop
  # and now start the master and rapi daemons
188 b1b6ea87 Iustin Pop
  if start_daemons:
189 b1b6ea87 Iustin Pop
    for daemon in 'ganeti-masterd', 'ganeti-rapi':
190 b1b6ea87 Iustin Pop
      result = utils.RunCmd([daemon])
191 b1b6ea87 Iustin Pop
      if result.failed:
192 b1b6ea87 Iustin Pop
        logging.error("Can't start daemon %s: %s", daemon, result.output)
193 b1b6ea87 Iustin Pop
        ok = False
194 b1b6ea87 Iustin Pop
  return ok
195 a8083063 Iustin Pop
196 a8083063 Iustin Pop
197 1c65840b Iustin Pop
def StopMaster(stop_daemons):
198 a8083063 Iustin Pop
  """Deactivate this node as master.
199 a8083063 Iustin Pop

200 1c65840b Iustin Pop
  The function will always try to deactivate the IP address of the
201 10c2650b Iustin Pop
  master. It will also stop the master daemons depending on the
202 10c2650b Iustin Pop
  stop_daemons parameter.
203 10c2650b Iustin Pop

204 10c2650b Iustin Pop
  @type stop_daemons: boolean
205 10c2650b Iustin Pop
  @param stop_daemons: whether to also stop the master daemons
206 10c2650b Iustin Pop
      (ganeti-masterd and ganeti-rapi)
207 10c2650b Iustin Pop
  @rtype: None
208 a8083063 Iustin Pop

209 a8083063 Iustin Pop
  """
210 bd1e4562 Iustin Pop
  master_netdev, master_ip, _ = GetMasterInfo()
211 b1b6ea87 Iustin Pop
  if not master_netdev:
212 b1b6ea87 Iustin Pop
    return False
213 a8083063 Iustin Pop
214 b1b6ea87 Iustin Pop
  result = utils.RunCmd(["ip", "address", "del", "%s/32" % master_ip,
215 b1b6ea87 Iustin Pop
                         "dev", master_netdev])
216 a8083063 Iustin Pop
  if result.failed:
217 3b9e6a30 Iustin Pop
    logging.error("Can't remove the master IP, error: %s", result.output)
218 b1b6ea87 Iustin Pop
    # but otherwise ignore the failure
219 b1b6ea87 Iustin Pop
220 b1b6ea87 Iustin Pop
  if stop_daemons:
221 b1b6ea87 Iustin Pop
    # stop/kill the rapi and the master daemon
222 b1b6ea87 Iustin Pop
    for daemon in constants.RAPI_PID, constants.MASTERD_PID:
223 b1b6ea87 Iustin Pop
      utils.KillProcess(utils.ReadPidFile(utils.DaemonPidFileName(daemon)))
224 a8083063 Iustin Pop
225 a8083063 Iustin Pop
  return True
226 a8083063 Iustin Pop
227 a8083063 Iustin Pop
228 9716fdce Iustin Pop
def AddNode(dsa, dsapub, rsa, rsapub, sshkey, sshpub):
229 7900ed01 Iustin Pop
  """Joins this node to the cluster.
230 a8083063 Iustin Pop

231 7900ed01 Iustin Pop
  This does the following:
232 7900ed01 Iustin Pop
      - updates the hostkeys of the machine (rsa and dsa)
233 7900ed01 Iustin Pop
      - adds the ssh private key to the user
234 7900ed01 Iustin Pop
      - adds the ssh public key to the users' authorized_keys file
235 a8083063 Iustin Pop

236 10c2650b Iustin Pop
  @type dsa: str
237 10c2650b Iustin Pop
  @param dsa: the DSA private key to write
238 10c2650b Iustin Pop
  @type dsapub: str
239 10c2650b Iustin Pop
  @param dsapub: the DSA public key to write
240 10c2650b Iustin Pop
  @type rsa: str
241 10c2650b Iustin Pop
  @param rsa: the RSA private key to write
242 10c2650b Iustin Pop
  @type rsapub: str
243 10c2650b Iustin Pop
  @param rsapub: the RSA public key to write
244 10c2650b Iustin Pop
  @type sshkey: str
245 10c2650b Iustin Pop
  @param sshkey: the SSH private key to write
246 10c2650b Iustin Pop
  @type sshpub: str
247 10c2650b Iustin Pop
  @param sshpub: the SSH public key to write
248 10c2650b Iustin Pop
  @rtype: boolean
249 10c2650b Iustin Pop
  @return: the success of the operation
250 10c2650b Iustin Pop

251 7900ed01 Iustin Pop
  """
252 70d9e3d8 Iustin Pop
  sshd_keys =  [(constants.SSH_HOST_RSA_PRIV, rsa, 0600),
253 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_RSA_PUB, rsapub, 0644),
254 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_DSA_PRIV, dsa, 0600),
255 70d9e3d8 Iustin Pop
                (constants.SSH_HOST_DSA_PUB, dsapub, 0644)]
256 7900ed01 Iustin Pop
  for name, content, mode in sshd_keys:
257 70d9e3d8 Iustin Pop
    utils.WriteFile(name, data=content, mode=mode)
258 a8083063 Iustin Pop
259 70d9e3d8 Iustin Pop
  try:
260 70d9e3d8 Iustin Pop
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS,
261 70d9e3d8 Iustin Pop
                                                    mkdir=True)
262 70d9e3d8 Iustin Pop
  except errors.OpExecError, err:
263 18682bca Iustin Pop
    logging.exception("Error while processing user ssh files")
264 70d9e3d8 Iustin Pop
    return False
265 a8083063 Iustin Pop
266 70d9e3d8 Iustin Pop
  for name, content in [(priv_key, sshkey), (pub_key, sshpub)]:
267 70d9e3d8 Iustin Pop
    utils.WriteFile(name, data=content, mode=0600)
268 a8083063 Iustin Pop
269 70d9e3d8 Iustin Pop
  utils.AddAuthorizedKey(auth_keys, sshpub)
270 a8083063 Iustin Pop
271 f491c3a8 Michael Hanselmann
  utils.RunCmd([constants.SSH_INITD_SCRIPT, "restart"])
272 a8083063 Iustin Pop
273 a8083063 Iustin Pop
  return True
274 a8083063 Iustin Pop
275 a8083063 Iustin Pop
276 a8083063 Iustin Pop
def LeaveCluster():
277 10c2650b Iustin Pop
  """Cleans up and remove the current node.
278 10c2650b Iustin Pop

279 10c2650b Iustin Pop
  This function cleans up and prepares the current node to be removed
280 10c2650b Iustin Pop
  from the cluster.
281 10c2650b Iustin Pop

282 10c2650b Iustin Pop
  If processing is successful, then it raises an
283 c41eea6e Iustin Pop
  L{errors.QuitGanetiException} which is used as a special case to
284 10c2650b Iustin Pop
  shutdown the node daemon.
285 a8083063 Iustin Pop

286 a8083063 Iustin Pop
  """
287 f78346f5 Michael Hanselmann
  _CleanDirectory(constants.DATA_DIR)
288 1bc59f76 Michael Hanselmann
  JobQueuePurge()
289 f78346f5 Michael Hanselmann
290 70d9e3d8 Iustin Pop
  try:
291 70d9e3d8 Iustin Pop
    priv_key, pub_key, auth_keys = ssh.GetUserFiles(constants.GANETI_RUNAS)
292 18682bca Iustin Pop
  except errors.OpExecError:
293 18682bca Iustin Pop
    logging.exception("Error while processing ssh files")
294 7900ed01 Iustin Pop
    return
295 7900ed01 Iustin Pop
296 70d9e3d8 Iustin Pop
  f = open(pub_key, 'r')
297 a8083063 Iustin Pop
  try:
298 70d9e3d8 Iustin Pop
    utils.RemoveAuthorizedKey(auth_keys, f.read(8192))
299 a8083063 Iustin Pop
  finally:
300 a8083063 Iustin Pop
    f.close()
301 a8083063 Iustin Pop
302 70d9e3d8 Iustin Pop
  utils.RemoveFile(priv_key)
303 70d9e3d8 Iustin Pop
  utils.RemoveFile(pub_key)
304 a8083063 Iustin Pop
305 6d8b6238 Guido Trotter
  # Return a reassuring string to the caller, and quit
306 6d8b6238 Guido Trotter
  raise errors.QuitGanetiException(False, 'Shutdown scheduled')
307 6d8b6238 Guido Trotter
308 a8083063 Iustin Pop
309 e69d05fd Iustin Pop
def GetNodeInfo(vgname, hypervisor_type):
310 2f8598a5 Alexander Schreiber
  """Gives back a hash with different informations about the node.
311 a8083063 Iustin Pop

312 e69d05fd Iustin Pop
  @type vgname: C{string}
313 e69d05fd Iustin Pop
  @param vgname: the name of the volume group to ask for disk space information
314 e69d05fd Iustin Pop
  @type hypervisor_type: C{str}
315 e69d05fd Iustin Pop
  @param hypervisor_type: the name of the hypervisor to ask for
316 e69d05fd Iustin Pop
      memory information
317 e69d05fd Iustin Pop
  @rtype: C{dict}
318 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
319 e69d05fd Iustin Pop
      - vg_size is the size of the configured volume group in MiB
320 e69d05fd Iustin Pop
      - vg_free is the free size of the volume group in MiB
321 e69d05fd Iustin Pop
      - memory_dom0 is the memory allocated for domain0 in MiB
322 e69d05fd Iustin Pop
      - memory_free is the currently available (free) ram in MiB
323 e69d05fd Iustin Pop
      - memory_total is the total number of ram in MiB
324 a8083063 Iustin Pop

325 098c0958 Michael Hanselmann
  """
326 a8083063 Iustin Pop
  outputarray = {}
327 a8083063 Iustin Pop
  vginfo = _GetVGInfo(vgname)
328 a8083063 Iustin Pop
  outputarray['vg_size'] = vginfo['vg_size']
329 a8083063 Iustin Pop
  outputarray['vg_free'] = vginfo['vg_free']
330 a8083063 Iustin Pop
331 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(hypervisor_type)
332 a8083063 Iustin Pop
  hyp_info = hyper.GetNodeInfo()
333 a8083063 Iustin Pop
  if hyp_info is not None:
334 a8083063 Iustin Pop
    outputarray.update(hyp_info)
335 a8083063 Iustin Pop
336 3ef10550 Michael Hanselmann
  f = open("/proc/sys/kernel/random/boot_id", 'r')
337 3ef10550 Michael Hanselmann
  try:
338 3ef10550 Michael Hanselmann
    outputarray["bootid"] = f.read(128).rstrip("\n")
339 3ef10550 Michael Hanselmann
  finally:
340 3ef10550 Michael Hanselmann
    f.close()
341 3ef10550 Michael Hanselmann
342 a8083063 Iustin Pop
  return outputarray
343 a8083063 Iustin Pop
344 a8083063 Iustin Pop
345 62c9ec92 Iustin Pop
def VerifyNode(what, cluster_name):
346 a8083063 Iustin Pop
  """Verify the status of the local node.
347 a8083063 Iustin Pop

348 e69d05fd Iustin Pop
  Based on the input L{what} parameter, various checks are done on the
349 e69d05fd Iustin Pop
  local node.
350 e69d05fd Iustin Pop

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

354 e69d05fd Iustin Pop
  If the I{nodelist} key is present, we check that we have
355 e69d05fd Iustin Pop
  connectivity via ssh with the target nodes (and check the hostname
356 e69d05fd Iustin Pop
  report).
357 a8083063 Iustin Pop

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

362 e69d05fd Iustin Pop
  @type what: C{dict}
363 e69d05fd Iustin Pop
  @param what: a dictionary of things to check:
364 e69d05fd Iustin Pop
      - filelist: list of files for which to compute checksums
365 e69d05fd Iustin Pop
      - nodelist: list of nodes we should check ssh communication with
366 e69d05fd Iustin Pop
      - node-net-test: list of nodes we should check node daemon port
367 e69d05fd Iustin Pop
        connectivity with
368 e69d05fd Iustin Pop
      - hypervisor: list with hypervisors to run the verify for
369 10c2650b Iustin Pop
  @rtype: dict
370 10c2650b Iustin Pop
  @return: a dictionary with the same keys as the input dict, and
371 10c2650b Iustin Pop
      values representing the result of the checks
372 a8083063 Iustin Pop

373 a8083063 Iustin Pop
  """
374 a8083063 Iustin Pop
  result = {}
375 a8083063 Iustin Pop
376 25361b9a Iustin Pop
  if constants.NV_HYPERVISOR in what:
377 25361b9a Iustin Pop
    result[constants.NV_HYPERVISOR] = tmp = {}
378 25361b9a Iustin Pop
    for hv_name in what[constants.NV_HYPERVISOR]:
379 25361b9a Iustin Pop
      tmp[hv_name] = hypervisor.GetHypervisor(hv_name).Verify()
380 25361b9a Iustin Pop
381 25361b9a Iustin Pop
  if constants.NV_FILELIST in what:
382 25361b9a Iustin Pop
    result[constants.NV_FILELIST] = utils.FingerprintFiles(
383 25361b9a Iustin Pop
      what[constants.NV_FILELIST])
384 25361b9a Iustin Pop
385 25361b9a Iustin Pop
  if constants.NV_NODELIST in what:
386 25361b9a Iustin Pop
    result[constants.NV_NODELIST] = tmp = {}
387 25361b9a Iustin Pop
    random.shuffle(what[constants.NV_NODELIST])
388 25361b9a Iustin Pop
    for node in what[constants.NV_NODELIST]:
389 62c9ec92 Iustin Pop
      success, message = _GetSshRunner(cluster_name).VerifyNodeHostname(node)
390 a8083063 Iustin Pop
      if not success:
391 25361b9a Iustin Pop
        tmp[node] = message
392 25361b9a Iustin Pop
393 25361b9a Iustin Pop
  if constants.NV_NODENETTEST in what:
394 25361b9a Iustin Pop
    result[constants.NV_NODENETTEST] = tmp = {}
395 9d4bfc96 Iustin Pop
    my_name = utils.HostInfo().name
396 9d4bfc96 Iustin Pop
    my_pip = my_sip = None
397 25361b9a Iustin Pop
    for name, pip, sip in what[constants.NV_NODENETTEST]:
398 9d4bfc96 Iustin Pop
      if name == my_name:
399 9d4bfc96 Iustin Pop
        my_pip = pip
400 9d4bfc96 Iustin Pop
        my_sip = sip
401 9d4bfc96 Iustin Pop
        break
402 9d4bfc96 Iustin Pop
    if not my_pip:
403 25361b9a Iustin Pop
      tmp[my_name] = ("Can't find my own primary/secondary IP"
404 25361b9a Iustin Pop
                      " in the node list")
405 9d4bfc96 Iustin Pop
    else:
406 c657dcc9 Michael Hanselmann
      port = utils.GetNodeDaemonPort()
407 25361b9a Iustin Pop
      for name, pip, sip in what[constants.NV_NODENETTEST]:
408 9d4bfc96 Iustin Pop
        fail = []
409 9d4bfc96 Iustin Pop
        if not utils.TcpPing(pip, port, source=my_pip):
410 9d4bfc96 Iustin Pop
          fail.append("primary")
411 9d4bfc96 Iustin Pop
        if sip != pip:
412 9d4bfc96 Iustin Pop
          if not utils.TcpPing(sip, port, source=my_sip):
413 9d4bfc96 Iustin Pop
            fail.append("secondary")
414 9d4bfc96 Iustin Pop
        if fail:
415 25361b9a Iustin Pop
          tmp[name] = ("failure using the %s interface(s)" %
416 25361b9a Iustin Pop
                       " and ".join(fail))
417 25361b9a Iustin Pop
418 25361b9a Iustin Pop
  if constants.NV_LVLIST in what:
419 25361b9a Iustin Pop
    result[constants.NV_LVLIST] = GetVolumeList(what[constants.NV_LVLIST])
420 25361b9a Iustin Pop
421 25361b9a Iustin Pop
  if constants.NV_INSTANCELIST in what:
422 25361b9a Iustin Pop
    result[constants.NV_INSTANCELIST] = GetInstanceList(
423 25361b9a Iustin Pop
      what[constants.NV_INSTANCELIST])
424 25361b9a Iustin Pop
425 25361b9a Iustin Pop
  if constants.NV_VGLIST in what:
426 25361b9a Iustin Pop
    result[constants.NV_VGLIST] = ListVolumeGroups()
427 25361b9a Iustin Pop
428 25361b9a Iustin Pop
  if constants.NV_VERSION in what:
429 25361b9a Iustin Pop
    result[constants.NV_VERSION] = constants.PROTOCOL_VERSION
430 25361b9a Iustin Pop
431 25361b9a Iustin Pop
  if constants.NV_HVINFO in what:
432 25361b9a Iustin Pop
    hyper = hypervisor.GetHypervisor(what[constants.NV_HVINFO])
433 25361b9a Iustin Pop
    result[constants.NV_HVINFO] = hyper.GetNodeInfo()
434 9d4bfc96 Iustin Pop
435 6d2e83d5 Iustin Pop
  if constants.NV_DRBDLIST in what:
436 6d2e83d5 Iustin Pop
    try:
437 6d2e83d5 Iustin Pop
      used_minors = bdev.DRBD8.GetUsedDevs().keys()
438 6d2e83d5 Iustin Pop
    except errors.BlockDeviceErrors:
439 6d2e83d5 Iustin Pop
      logging.warning("Can't get used minors list", exc_info=True)
440 6d2e83d5 Iustin Pop
      used_minors = []
441 6d2e83d5 Iustin Pop
    result[constants.NV_DRBDLIST] = used_minors
442 6d2e83d5 Iustin Pop
443 a8083063 Iustin Pop
  return result
444 a8083063 Iustin Pop
445 a8083063 Iustin Pop
446 a8083063 Iustin Pop
def GetVolumeList(vg_name):
447 a8083063 Iustin Pop
  """Compute list of logical volumes and their size.
448 a8083063 Iustin Pop

449 10c2650b Iustin Pop
  @type vg_name: str
450 10c2650b Iustin Pop
  @param vg_name: the volume group whose LVs we should list
451 10c2650b Iustin Pop
  @rtype: dict
452 10c2650b Iustin Pop
  @return:
453 10c2650b Iustin Pop
      dictionary of all partions (key) with value being a tuple of
454 10c2650b Iustin Pop
      their size (in MiB), inactive and online status::
455 10c2650b Iustin Pop

456 10c2650b Iustin Pop
        {'test1': ('20.06', True, True)}
457 10c2650b Iustin Pop

458 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
459 10c2650b Iustin Pop
      details.
460 a8083063 Iustin Pop

461 a8083063 Iustin Pop
  """
462 cb2037a2 Iustin Pop
  lvs = {}
463 cb2037a2 Iustin Pop
  sep = '|'
464 cb2037a2 Iustin Pop
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
465 cb2037a2 Iustin Pop
                         "--separator=%s" % sep,
466 cb2037a2 Iustin Pop
                         "-olv_name,lv_size,lv_attr", vg_name])
467 a8083063 Iustin Pop
  if result.failed:
468 18682bca Iustin Pop
    logging.error("Failed to list logical volumes, lvs output: %s",
469 18682bca Iustin Pop
                  result.output)
470 b63ed789 Iustin Pop
    return result.output
471 cb2037a2 Iustin Pop
472 df4c2628 Iustin Pop
  valid_line_re = re.compile("^ *([^|]+)\|([0-9.]+)\|([^|]{6})\|?$")
473 cb2037a2 Iustin Pop
  for line in result.stdout.splitlines():
474 df4c2628 Iustin Pop
    line = line.strip()
475 df4c2628 Iustin Pop
    match = valid_line_re.match(line)
476 df4c2628 Iustin Pop
    if not match:
477 18682bca Iustin Pop
      logging.error("Invalid line returned from lvs output: '%s'", line)
478 df4c2628 Iustin Pop
      continue
479 df4c2628 Iustin Pop
    name, size, attr = match.groups()
480 cb2037a2 Iustin Pop
    inactive = attr[4] == '-'
481 cb2037a2 Iustin Pop
    online = attr[5] == 'o'
482 cb2037a2 Iustin Pop
    lvs[name] = (size, inactive, online)
483 cb2037a2 Iustin Pop
484 cb2037a2 Iustin Pop
  return lvs
485 a8083063 Iustin Pop
486 a8083063 Iustin Pop
487 a8083063 Iustin Pop
def ListVolumeGroups():
488 2f8598a5 Alexander Schreiber
  """List the volume groups and their size.
489 a8083063 Iustin Pop

490 10c2650b Iustin Pop
  @rtype: dict
491 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
492 10c2650b Iustin Pop
      size of the volume
493 a8083063 Iustin Pop

494 a8083063 Iustin Pop
  """
495 a8083063 Iustin Pop
  return utils.ListVolumeGroups()
496 a8083063 Iustin Pop
497 a8083063 Iustin Pop
498 dcb93971 Michael Hanselmann
def NodeVolumes():
499 dcb93971 Michael Hanselmann
  """List all volumes on this node.
500 dcb93971 Michael Hanselmann

501 10c2650b Iustin Pop
  @rtype: list
502 10c2650b Iustin Pop
  @return:
503 10c2650b Iustin Pop
    A list of dictionaries, each having four keys:
504 10c2650b Iustin Pop
      - name: the logical volume name,
505 10c2650b Iustin Pop
      - size: the size of the logical volume
506 10c2650b Iustin Pop
      - dev: the physical device on which the LV lives
507 10c2650b Iustin Pop
      - vg: the volume group to which it belongs
508 10c2650b Iustin Pop

509 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
510 10c2650b Iustin Pop
    error.
511 10c2650b Iustin Pop

512 10c2650b Iustin Pop
    Note that since a logical volume can live on multiple physical
513 10c2650b Iustin Pop
    volumes, the resulting list might include a logical volume
514 10c2650b Iustin Pop
    multiple times.
515 10c2650b Iustin Pop

516 dcb93971 Michael Hanselmann
  """
517 dcb93971 Michael Hanselmann
  result = utils.RunCmd(["lvs", "--noheadings", "--units=m", "--nosuffix",
518 dcb93971 Michael Hanselmann
                         "--separator=|",
519 dcb93971 Michael Hanselmann
                         "--options=lv_name,lv_size,devices,vg_name"])
520 dcb93971 Michael Hanselmann
  if result.failed:
521 18682bca Iustin Pop
    logging.error("Failed to list logical volumes, lvs output: %s",
522 18682bca Iustin Pop
                  result.output)
523 3f5bd234 Iustin Pop
    return []
524 dcb93971 Michael Hanselmann
525 dcb93971 Michael Hanselmann
  def parse_dev(dev):
526 dcb93971 Michael Hanselmann
    if '(' in dev:
527 dcb93971 Michael Hanselmann
      return dev.split('(')[0]
528 dcb93971 Michael Hanselmann
    else:
529 dcb93971 Michael Hanselmann
      return dev
530 dcb93971 Michael Hanselmann
531 dcb93971 Michael Hanselmann
  def map_line(line):
532 dcb93971 Michael Hanselmann
    return {
533 dcb93971 Michael Hanselmann
      'name': line[0].strip(),
534 dcb93971 Michael Hanselmann
      'size': line[1].strip(),
535 dcb93971 Michael Hanselmann
      'dev': parse_dev(line[2].strip()),
536 dcb93971 Michael Hanselmann
      'vg': line[3].strip(),
537 dcb93971 Michael Hanselmann
    }
538 dcb93971 Michael Hanselmann
539 a17a7623 Iustin Pop
  return [map_line(line.split('|')) for line in result.stdout.splitlines()
540 a17a7623 Iustin Pop
          if line.count('|') >= 3]
541 dcb93971 Michael Hanselmann
542 dcb93971 Michael Hanselmann
543 a8083063 Iustin Pop
def BridgesExist(bridges_list):
544 2f8598a5 Alexander Schreiber
  """Check if a list of bridges exist on the current node.
545 a8083063 Iustin Pop

546 b1206984 Iustin Pop
  @rtype: boolean
547 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
548 a8083063 Iustin Pop

549 a8083063 Iustin Pop
  """
550 a8083063 Iustin Pop
  for bridge in bridges_list:
551 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
552 a8083063 Iustin Pop
      return False
553 a8083063 Iustin Pop
554 a8083063 Iustin Pop
  return True
555 a8083063 Iustin Pop
556 a8083063 Iustin Pop
557 e69d05fd Iustin Pop
def GetInstanceList(hypervisor_list):
558 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
559 a8083063 Iustin Pop

560 e69d05fd Iustin Pop
  @type hypervisor_list: list
561 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
562 e69d05fd Iustin Pop

563 e69d05fd Iustin Pop
  @rtype: list
564 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
565 10c2650b Iustin Pop
    - instance1.example.com
566 10c2650b Iustin Pop
    - instance2.example.com
567 a8083063 Iustin Pop

568 098c0958 Michael Hanselmann
  """
569 e69d05fd Iustin Pop
  results = []
570 e69d05fd Iustin Pop
  for hname in hypervisor_list:
571 e69d05fd Iustin Pop
    try:
572 e69d05fd Iustin Pop
      names = hypervisor.GetHypervisor(hname).ListInstances()
573 e69d05fd Iustin Pop
      results.extend(names)
574 e69d05fd Iustin Pop
    except errors.HypervisorError, err:
575 e69d05fd Iustin Pop
      logging.exception("Error enumerating instances for hypevisor %s", hname)
576 e69d05fd Iustin Pop
      # FIXME: should we somehow not propagate this to the master?
577 e69d05fd Iustin Pop
      raise
578 a8083063 Iustin Pop
579 e69d05fd Iustin Pop
  return results
580 a8083063 Iustin Pop
581 a8083063 Iustin Pop
582 e69d05fd Iustin Pop
def GetInstanceInfo(instance, hname):
583 2f8598a5 Alexander Schreiber
  """Gives back the informations about an instance as a dictionary.
584 a8083063 Iustin Pop

585 e69d05fd Iustin Pop
  @type instance: string
586 e69d05fd Iustin Pop
  @param instance: the instance name
587 e69d05fd Iustin Pop
  @type hname: string
588 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
589 a8083063 Iustin Pop

590 e69d05fd Iustin Pop
  @rtype: dict
591 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
592 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
593 e69d05fd Iustin Pop
      - state: xen state of instance (string)
594 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
595 a8083063 Iustin Pop

596 098c0958 Michael Hanselmann
  """
597 a8083063 Iustin Pop
  output = {}
598 a8083063 Iustin Pop
599 e69d05fd Iustin Pop
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
600 a8083063 Iustin Pop
  if iinfo is not None:
601 a8083063 Iustin Pop
    output['memory'] = iinfo[2]
602 a8083063 Iustin Pop
    output['state'] = iinfo[4]
603 a8083063 Iustin Pop
    output['time'] = iinfo[5]
604 a8083063 Iustin Pop
605 a8083063 Iustin Pop
  return output
606 a8083063 Iustin Pop
607 a8083063 Iustin Pop
608 56e7640c Iustin Pop
def GetInstanceMigratable(instance):
609 56e7640c Iustin Pop
  """Gives whether an instance can be migrated.
610 56e7640c Iustin Pop

611 56e7640c Iustin Pop
  @type instance: L{objects.Instance}
612 56e7640c Iustin Pop
  @param instance: object representing the instance to be checked.
613 56e7640c Iustin Pop

614 56e7640c Iustin Pop
  @rtype: tuple
615 56e7640c Iustin Pop
  @return: tuple of (result, description) where:
616 56e7640c Iustin Pop
      - result: whether the instance can be migrated or not
617 56e7640c Iustin Pop
      - description: a description of the issue, if relevant
618 56e7640c Iustin Pop

619 56e7640c Iustin Pop
  """
620 56e7640c Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
621 56e7640c Iustin Pop
  if instance.name not in hyper.ListInstances():
622 56e7640c Iustin Pop
    return (False, 'not running')
623 56e7640c Iustin Pop
624 56e7640c Iustin Pop
  for idx in range(len(instance.disks)):
625 56e7640c Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance.name, idx)
626 56e7640c Iustin Pop
    if not os.path.islink(link_name):
627 56e7640c Iustin Pop
      return (False, 'not restarted since ganeti 1.2.5')
628 56e7640c Iustin Pop
629 56e7640c Iustin Pop
  return (True, '')
630 56e7640c Iustin Pop
631 56e7640c Iustin Pop
632 e69d05fd Iustin Pop
def GetAllInstancesInfo(hypervisor_list):
633 a8083063 Iustin Pop
  """Gather data about all instances.
634 a8083063 Iustin Pop

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

639 e69d05fd Iustin Pop
  @type hypervisor_list: list
640 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
641 e69d05fd Iustin Pop

642 955db481 Guido Trotter
  @rtype: dict
643 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
644 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
645 e69d05fd Iustin Pop
      - state: xen state of instance (string)
646 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
647 10c2650b Iustin Pop
      - vcpus: the number of vcpus
648 a8083063 Iustin Pop

649 098c0958 Michael Hanselmann
  """
650 a8083063 Iustin Pop
  output = {}
651 a8083063 Iustin Pop
652 e69d05fd Iustin Pop
  for hname in hypervisor_list:
653 e69d05fd Iustin Pop
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
654 e69d05fd Iustin Pop
    if iinfo:
655 e69d05fd Iustin Pop
      for name, inst_id, memory, vcpus, state, times in iinfo:
656 f23b5ae8 Iustin Pop
        value = {
657 e69d05fd Iustin Pop
          'memory': memory,
658 e69d05fd Iustin Pop
          'vcpus': vcpus,
659 e69d05fd Iustin Pop
          'state': state,
660 e69d05fd Iustin Pop
          'time': times,
661 e69d05fd Iustin Pop
          }
662 f23b5ae8 Iustin Pop
        if name in output and output[name] != value:
663 f23b5ae8 Iustin Pop
          raise errors.HypervisorError("Instance %s running duplicate"
664 f23b5ae8 Iustin Pop
                                       " with different parameters" % name)
665 f23b5ae8 Iustin Pop
        output[name] = value
666 a8083063 Iustin Pop
667 a8083063 Iustin Pop
  return output
668 a8083063 Iustin Pop
669 a8083063 Iustin Pop
670 d15a9ad3 Guido Trotter
def AddOSToInstance(instance):
671 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
672 a8083063 Iustin Pop

673 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
674 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
675 10c2650b Iustin Pop
  @rtype: boolean
676 10c2650b Iustin Pop
  @return: the success of the operation
677 a8083063 Iustin Pop

678 a8083063 Iustin Pop
  """
679 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
680 a8083063 Iustin Pop
681 58f6e5ca Guido Trotter
  create_env = OSEnvironment(instance)
682 a8083063 Iustin Pop
683 a8083063 Iustin Pop
  logfile = "%s/add-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
684 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
685 decd5f45 Iustin Pop
686 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.create_script], env=create_env,
687 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile,)
688 decd5f45 Iustin Pop
  if result.failed:
689 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
690 d868edb4 Iustin Pop
                  " output: %s", result.cmd, result.fail_reason, logfile,
691 18682bca Iustin Pop
                  result.output)
692 20e01edd Iustin Pop
    lines = [val.encode("string_escape")
693 20e01edd Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
694 20e01edd Iustin Pop
    return (False, "OS create script failed (%s), last lines in the"
695 20e01edd Iustin Pop
            " log file:\n%s" % (result.fail_reason, "\n".join(lines)))
696 decd5f45 Iustin Pop
697 20e01edd Iustin Pop
  return (True, "Successfully installed")
698 decd5f45 Iustin Pop
699 decd5f45 Iustin Pop
700 d15a9ad3 Guido Trotter
def RunRenameInstance(instance, old_name):
701 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
702 decd5f45 Iustin Pop

703 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
704 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
705 d15a9ad3 Guido Trotter
  @type old_name: string
706 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
707 10c2650b Iustin Pop
  @rtype: boolean
708 10c2650b Iustin Pop
  @return: the success of the operation
709 decd5f45 Iustin Pop

710 decd5f45 Iustin Pop
  """
711 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
712 decd5f45 Iustin Pop
713 ff38b6c0 Guido Trotter
  rename_env = OSEnvironment(instance)
714 ff38b6c0 Guido Trotter
  rename_env['OLD_INSTANCE_NAME'] = old_name
715 decd5f45 Iustin Pop
716 decd5f45 Iustin Pop
  logfile = "%s/rename-%s-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
717 decd5f45 Iustin Pop
                                           old_name,
718 decd5f45 Iustin Pop
                                           instance.name, int(time.time()))
719 a8083063 Iustin Pop
720 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
721 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile)
722 a8083063 Iustin Pop
723 a8083063 Iustin Pop
  if result.failed:
724 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
725 d868edb4 Iustin Pop
                  result.cmd, result.fail_reason, result.output)
726 96841384 Iustin Pop
    lines = [val.encode("string_escape")
727 96841384 Iustin Pop
             for val in utils.TailFile(logfile, lines=20)]
728 96841384 Iustin Pop
    return (False, "OS rename script failed (%s), last lines in the"
729 96841384 Iustin Pop
            " log file:\n%s" % (result.fail_reason, "\n".join(lines)))
730 a8083063 Iustin Pop
731 96841384 Iustin Pop
  return (True, "Rename successful")
732 a8083063 Iustin Pop
733 a8083063 Iustin Pop
734 a8083063 Iustin Pop
def _GetVGInfo(vg_name):
735 a8083063 Iustin Pop
  """Get informations about the volume group.
736 a8083063 Iustin Pop

737 10c2650b Iustin Pop
  @type vg_name: str
738 10c2650b Iustin Pop
  @param vg_name: the volume group which we query
739 10c2650b Iustin Pop
  @rtype: dict
740 10c2650b Iustin Pop
  @return:
741 10c2650b Iustin Pop
    A dictionary with the following keys:
742 10c2650b Iustin Pop
      - C{vg_size} is the total size of the volume group in MiB
743 10c2650b Iustin Pop
      - C{vg_free} is the free size of the volume group in MiB
744 10c2650b Iustin Pop
      - C{pv_count} are the number of physical disks in that VG
745 a8083063 Iustin Pop

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

749 a8083063 Iustin Pop
  """
750 f4d377e7 Iustin Pop
  retdic = dict.fromkeys(["vg_size", "vg_free", "pv_count"])
751 f4d377e7 Iustin Pop
752 a8083063 Iustin Pop
  retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings",
753 a8083063 Iustin Pop
                         "--nosuffix", "--units=m", "--separator=:", vg_name])
754 a8083063 Iustin Pop
755 a8083063 Iustin Pop
  if retval.failed:
756 18682bca Iustin Pop
    logging.error("volume group %s not present", vg_name)
757 f4d377e7 Iustin Pop
    return retdic
758 d87ae7d2 Iustin Pop
  valarr = retval.stdout.strip().rstrip(':').split(':')
759 f4d377e7 Iustin Pop
  if len(valarr) == 3:
760 f4d377e7 Iustin Pop
    try:
761 f4d377e7 Iustin Pop
      retdic = {
762 f4d377e7 Iustin Pop
        "vg_size": int(round(float(valarr[0]), 0)),
763 f4d377e7 Iustin Pop
        "vg_free": int(round(float(valarr[1]), 0)),
764 f4d377e7 Iustin Pop
        "pv_count": int(valarr[2]),
765 f4d377e7 Iustin Pop
        }
766 f4d377e7 Iustin Pop
    except ValueError, err:
767 18682bca Iustin Pop
      logging.exception("Fail to parse vgs output")
768 f4d377e7 Iustin Pop
  else:
769 18682bca Iustin Pop
    logging.error("vgs output has the wrong number of fields (expected"
770 18682bca Iustin Pop
                  " three): %s", str(valarr))
771 a8083063 Iustin Pop
  return retdic
772 a8083063 Iustin Pop
773 a8083063 Iustin Pop
774 5282084b Iustin Pop
def _GetBlockDevSymlinkPath(instance_name, idx):
775 5282084b Iustin Pop
  return os.path.join(constants.DISK_LINKS_DIR,
776 5282084b Iustin Pop
                      "%s:%d" % (instance_name, idx))
777 5282084b Iustin Pop
778 5282084b Iustin Pop
779 5282084b Iustin Pop
def _SymlinkBlockDev(instance_name, device_path, idx):
780 9332fd8a Iustin Pop
  """Set up symlinks to a instance's block device.
781 9332fd8a Iustin Pop

782 9332fd8a Iustin Pop
  This is an auxiliary function run when an instance is start (on the primary
783 9332fd8a Iustin Pop
  node) or when an instance is migrated (on the target node).
784 9332fd8a Iustin Pop

785 9332fd8a Iustin Pop

786 5282084b Iustin Pop
  @param instance_name: the name of the target instance
787 5282084b Iustin Pop
  @param device_path: path of the physical block device, on the node
788 5282084b Iustin Pop
  @param idx: the disk index
789 5282084b Iustin Pop
  @return: absolute path to the disk's symlink
790 9332fd8a Iustin Pop

791 9332fd8a Iustin Pop
  """
792 5282084b Iustin Pop
  link_name = _GetBlockDevSymlinkPath(instance_name, idx)
793 9332fd8a Iustin Pop
  try:
794 9332fd8a Iustin Pop
    os.symlink(device_path, link_name)
795 5282084b Iustin Pop
  except OSError, err:
796 5282084b Iustin Pop
    if err.errno == errno.EEXIST:
797 9332fd8a Iustin Pop
      if (not os.path.islink(link_name) or
798 9332fd8a Iustin Pop
          os.readlink(link_name) != device_path):
799 9332fd8a Iustin Pop
        os.remove(link_name)
800 9332fd8a Iustin Pop
        os.symlink(device_path, link_name)
801 9332fd8a Iustin Pop
    else:
802 9332fd8a Iustin Pop
      raise
803 9332fd8a Iustin Pop
804 9332fd8a Iustin Pop
  return link_name
805 9332fd8a Iustin Pop
806 9332fd8a Iustin Pop
807 5282084b Iustin Pop
def _RemoveBlockDevLinks(instance_name, disks):
808 3c9c571d Iustin Pop
  """Remove the block device symlinks belonging to the given instance.
809 3c9c571d Iustin Pop

810 3c9c571d Iustin Pop
  """
811 5282084b Iustin Pop
  for idx, disk in enumerate(disks):
812 5282084b Iustin Pop
    link_name = _GetBlockDevSymlinkPath(instance_name, idx)
813 5282084b Iustin Pop
    if os.path.islink(link_name):
814 3c9c571d Iustin Pop
      try:
815 03dfa658 Iustin Pop
        os.remove(link_name)
816 03dfa658 Iustin Pop
      except OSError:
817 03dfa658 Iustin Pop
        logging.exception("Can't remove symlink '%s'", link_name)
818 3c9c571d Iustin Pop
819 3c9c571d Iustin Pop
820 9332fd8a Iustin Pop
def _GatherAndLinkBlockDevs(instance):
821 a8083063 Iustin Pop
  """Set up an instance's block device(s).
822 a8083063 Iustin Pop

823 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
824 a8083063 Iustin Pop
  devices must be already assembled.
825 a8083063 Iustin Pop

826 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
827 10c2650b Iustin Pop
  @param instance: the instance whose disks we shoul assemble
828 069cfbf1 Iustin Pop
  @rtype: list
829 069cfbf1 Iustin Pop
  @return: list of (disk_object, device_path)
830 10c2650b Iustin Pop

831 a8083063 Iustin Pop
  """
832 a8083063 Iustin Pop
  block_devices = []
833 9332fd8a Iustin Pop
  for idx, disk in enumerate(instance.disks):
834 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
835 a8083063 Iustin Pop
    if device is None:
836 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
837 a8083063 Iustin Pop
                                    str(disk))
838 a8083063 Iustin Pop
    device.Open()
839 9332fd8a Iustin Pop
    try:
840 5282084b Iustin Pop
      link_name = _SymlinkBlockDev(instance.name, device.dev_path, idx)
841 9332fd8a Iustin Pop
    except OSError, e:
842 9332fd8a Iustin Pop
      raise errors.BlockDeviceError("Cannot create block device symlink: %s" %
843 9332fd8a Iustin Pop
                                    e.strerror)
844 9332fd8a Iustin Pop
845 9332fd8a Iustin Pop
    block_devices.append((disk, link_name))
846 9332fd8a Iustin Pop
847 a8083063 Iustin Pop
  return block_devices
848 a8083063 Iustin Pop
849 a8083063 Iustin Pop
850 a8083063 Iustin Pop
def StartInstance(instance, extra_args):
851 a8083063 Iustin Pop
  """Start an instance.
852 a8083063 Iustin Pop

853 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
854 e69d05fd Iustin Pop
  @param instance: the instance object
855 e69d05fd Iustin Pop
  @rtype: boolean
856 e69d05fd Iustin Pop
  @return: whether the startup was successful or not
857 a8083063 Iustin Pop

858 098c0958 Michael Hanselmann
  """
859 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
860 a8083063 Iustin Pop
861 a8083063 Iustin Pop
  if instance.name in running_instances:
862 dd279568 Iustin Pop
    return (True, "Already running")
863 a8083063 Iustin Pop
864 a8083063 Iustin Pop
  try:
865 ec596c24 Iustin Pop
    block_devices = _GatherAndLinkBlockDevs(instance)
866 ec596c24 Iustin Pop
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
867 a8083063 Iustin Pop
    hyper.StartInstance(instance, block_devices, extra_args)
868 ec596c24 Iustin Pop
  except errors.BlockDeviceError, err:
869 ec596c24 Iustin Pop
    logging.exception("Failed to start instance")
870 dd279568 Iustin Pop
    return (False, "Block device error: %s" % str(err))
871 a8083063 Iustin Pop
  except errors.HypervisorError, err:
872 18682bca Iustin Pop
    logging.exception("Failed to start instance")
873 5282084b Iustin Pop
    _RemoveBlockDevLinks(instance.name, instance.disks)
874 dd279568 Iustin Pop
    return (False, "Hypervisor error: %s" % str(err))
875 a8083063 Iustin Pop
876 dd279568 Iustin Pop
  return (True, "Instance started successfully")
877 a8083063 Iustin Pop
878 a8083063 Iustin Pop
879 a8083063 Iustin Pop
def ShutdownInstance(instance):
880 a8083063 Iustin Pop
  """Shut an instance down.
881 a8083063 Iustin Pop

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

884 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
885 e69d05fd Iustin Pop
  @param instance: the instance object
886 e69d05fd Iustin Pop
  @rtype: boolean
887 e69d05fd Iustin Pop
  @return: whether the startup was successful or not
888 a8083063 Iustin Pop

889 098c0958 Michael Hanselmann
  """
890 e69d05fd Iustin Pop
  hv_name = instance.hypervisor
891 e69d05fd Iustin Pop
  running_instances = GetInstanceList([hv_name])
892 a8083063 Iustin Pop
893 a8083063 Iustin Pop
  if instance.name not in running_instances:
894 a8083063 Iustin Pop
    return True
895 a8083063 Iustin Pop
896 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(hv_name)
897 a8083063 Iustin Pop
  try:
898 a8083063 Iustin Pop
    hyper.StopInstance(instance)
899 a8083063 Iustin Pop
  except errors.HypervisorError, err:
900 920aae98 Guido Trotter
    logging.error("Failed to stop instance: %s" % err)
901 a8083063 Iustin Pop
    return False
902 a8083063 Iustin Pop
903 a8083063 Iustin Pop
  # test every 10secs for 2min
904 a8083063 Iustin Pop
905 a8083063 Iustin Pop
  time.sleep(1)
906 a8083063 Iustin Pop
  for dummy in range(11):
907 e69d05fd Iustin Pop
    if instance.name not in GetInstanceList([hv_name]):
908 a8083063 Iustin Pop
      break
909 a8083063 Iustin Pop
    time.sleep(10)
910 a8083063 Iustin Pop
  else:
911 a8083063 Iustin Pop
    # the shutdown did not succeed
912 18682bca Iustin Pop
    logging.error("shutdown of '%s' unsuccessful, using destroy", instance)
913 a8083063 Iustin Pop
914 a8083063 Iustin Pop
    try:
915 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
916 a8083063 Iustin Pop
    except errors.HypervisorError, err:
917 920aae98 Guido Trotter
      logging.exception("Failed to stop instance: %s" % err)
918 a8083063 Iustin Pop
      return False
919 a8083063 Iustin Pop
920 a8083063 Iustin Pop
    time.sleep(1)
921 e69d05fd Iustin Pop
    if instance.name in GetInstanceList([hv_name]):
922 18682bca Iustin Pop
      logging.error("could not shutdown instance '%s' even by destroy",
923 18682bca Iustin Pop
                    instance.name)
924 a8083063 Iustin Pop
      return False
925 a8083063 Iustin Pop
926 5282084b Iustin Pop
  _RemoveBlockDevLinks(instance.name, instance.disks)
927 3c9c571d Iustin Pop
928 a8083063 Iustin Pop
  return True
929 a8083063 Iustin Pop
930 a8083063 Iustin Pop
931 007a2f3e Alexander Schreiber
def RebootInstance(instance, reboot_type, extra_args):
932 007a2f3e Alexander Schreiber
  """Reboot an instance.
933 007a2f3e Alexander Schreiber

934 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
935 10c2650b Iustin Pop
  @param instance: the instance object to reboot
936 10c2650b Iustin Pop
  @type reboot_type: str
937 10c2650b Iustin Pop
  @param reboot_type: the type of reboot, one the following
938 10c2650b Iustin Pop
    constants:
939 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
940 10c2650b Iustin Pop
        instance OS, do not recreate the VM
941 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
942 10c2650b Iustin Pop
        restart the VM (at the hypervisor level)
943 10c2650b Iustin Pop
      - the other reboot type (L{constants.INSTANCE_REBOOT_HARD})
944 10c2650b Iustin Pop
        is not accepted here, since that mode is handled
945 10c2650b Iustin Pop
        differently
946 10c2650b Iustin Pop
  @rtype: boolean
947 10c2650b Iustin Pop
  @return: the success of the operation
948 007a2f3e Alexander Schreiber

949 007a2f3e Alexander Schreiber
  """
950 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
951 007a2f3e Alexander Schreiber
952 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
953 18682bca Iustin Pop
    logging.error("Cannot reboot instance that is not running")
954 007a2f3e Alexander Schreiber
    return False
955 007a2f3e Alexander Schreiber
956 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
957 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
958 007a2f3e Alexander Schreiber
    try:
959 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
960 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
961 18682bca Iustin Pop
      logging.exception("Failed to soft reboot instance")
962 007a2f3e Alexander Schreiber
      return False
963 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
964 007a2f3e Alexander Schreiber
    try:
965 007a2f3e Alexander Schreiber
      ShutdownInstance(instance)
966 007a2f3e Alexander Schreiber
      StartInstance(instance, extra_args)
967 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
968 18682bca Iustin Pop
      logging.exception("Failed to hard reboot instance")
969 007a2f3e Alexander Schreiber
      return False
970 007a2f3e Alexander Schreiber
  else:
971 007a2f3e Alexander Schreiber
    raise errors.ParameterError("reboot_type invalid")
972 007a2f3e Alexander Schreiber
973 007a2f3e Alexander Schreiber
  return True
974 007a2f3e Alexander Schreiber
975 007a2f3e Alexander Schreiber
976 6906a9d8 Guido Trotter
def MigrationInfo(instance):
977 6906a9d8 Guido Trotter
  """Gather information about an instance to be migrated.
978 6906a9d8 Guido Trotter

979 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
980 6906a9d8 Guido Trotter
  @param instance: the instance definition
981 6906a9d8 Guido Trotter

982 6906a9d8 Guido Trotter
  """
983 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
984 cd42d0ad Guido Trotter
  try:
985 cd42d0ad Guido Trotter
    info = hyper.MigrationInfo(instance)
986 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
987 cd42d0ad Guido Trotter
    msg = "Failed to fetch migration information"
988 cd42d0ad Guido Trotter
    logging.exception(msg)
989 cd42d0ad Guido Trotter
    return (False, '%s: %s' % (msg, err))
990 cd42d0ad Guido Trotter
  return (True, info)
991 6906a9d8 Guido Trotter
992 6906a9d8 Guido Trotter
993 6906a9d8 Guido Trotter
def AcceptInstance(instance, info, target):
994 6906a9d8 Guido Trotter
  """Prepare the node to accept an instance.
995 6906a9d8 Guido Trotter

996 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
997 6906a9d8 Guido Trotter
  @param instance: the instance definition
998 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
999 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1000 6906a9d8 Guido Trotter
  @type target: string
1001 6906a9d8 Guido Trotter
  @param target: target host (usually ip), on this node
1002 6906a9d8 Guido Trotter

1003 6906a9d8 Guido Trotter
  """
1004 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1005 cd42d0ad Guido Trotter
  try:
1006 cd42d0ad Guido Trotter
    hyper.AcceptInstance(instance, info, target)
1007 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1008 cd42d0ad Guido Trotter
    msg = "Failed to accept instance"
1009 cd42d0ad Guido Trotter
    logging.exception(msg)
1010 cd42d0ad Guido Trotter
    return (False, '%s: %s' % (msg, err))
1011 6906a9d8 Guido Trotter
  return (True, "Accept successfull")
1012 6906a9d8 Guido Trotter
1013 6906a9d8 Guido Trotter
1014 6906a9d8 Guido Trotter
def FinalizeMigration(instance, info, success):
1015 6906a9d8 Guido Trotter
  """Finalize any preparation to accept an instance.
1016 6906a9d8 Guido Trotter

1017 6906a9d8 Guido Trotter
  @type instance: L{objects.Instance}
1018 6906a9d8 Guido Trotter
  @param instance: the instance definition
1019 6906a9d8 Guido Trotter
  @type info: string/data (opaque)
1020 6906a9d8 Guido Trotter
  @param info: migration information, from the source node
1021 6906a9d8 Guido Trotter
  @type success: boolean
1022 6906a9d8 Guido Trotter
  @param success: whether the migration was a success or a failure
1023 6906a9d8 Guido Trotter

1024 6906a9d8 Guido Trotter
  """
1025 cd42d0ad Guido Trotter
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1026 cd42d0ad Guido Trotter
  try:
1027 cd42d0ad Guido Trotter
    hyper.FinalizeMigration(instance, info, success)
1028 cd42d0ad Guido Trotter
  except errors.HypervisorError, err:
1029 cd42d0ad Guido Trotter
    msg = "Failed to finalize migration"
1030 cd42d0ad Guido Trotter
    logging.exception(msg)
1031 cd42d0ad Guido Trotter
    return (False, '%s: %s' % (msg, err))
1032 6906a9d8 Guido Trotter
  return (True, "Migration Finalized")
1033 6906a9d8 Guido Trotter
1034 6906a9d8 Guido Trotter
1035 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
1036 2a10865c Iustin Pop
  """Migrates an instance to another node.
1037 2a10865c Iustin Pop

1038 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1039 9f0e6b37 Iustin Pop
  @param instance: the instance definition
1040 9f0e6b37 Iustin Pop
  @type target: string
1041 9f0e6b37 Iustin Pop
  @param target: the target node name
1042 9f0e6b37 Iustin Pop
  @type live: boolean
1043 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
1044 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
1045 9f0e6b37 Iustin Pop
  @rtype: tuple
1046 9f0e6b37 Iustin Pop
  @return: a tuple of (success, msg) where:
1047 9f0e6b37 Iustin Pop
      - succes is a boolean denoting the success/failure of the operation
1048 9f0e6b37 Iustin Pop
      - msg is a string with details in case of failure
1049 9f0e6b37 Iustin Pop

1050 2a10865c Iustin Pop
  """
1051 53c776b5 Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
1052 2a10865c Iustin Pop
1053 2a10865c Iustin Pop
  try:
1054 9f0e6b37 Iustin Pop
    hyper.MigrateInstance(instance.name, target, live)
1055 2a10865c Iustin Pop
  except errors.HypervisorError, err:
1056 53c776b5 Iustin Pop
    msg = "Failed to migrate instance"
1057 53c776b5 Iustin Pop
    logging.exception(msg)
1058 53c776b5 Iustin Pop
    return (False, "%s: %s" % (msg, err))
1059 2a10865c Iustin Pop
  return (True, "Migration successfull")
1060 2a10865c Iustin Pop
1061 2a10865c Iustin Pop
1062 3f78eef2 Iustin Pop
def CreateBlockDevice(disk, size, owner, on_primary, info):
1063 a8083063 Iustin Pop
  """Creates a block device for an instance.
1064 a8083063 Iustin Pop

1065 b1206984 Iustin Pop
  @type disk: L{objects.Disk}
1066 b1206984 Iustin Pop
  @param disk: the object describing the disk we should create
1067 b1206984 Iustin Pop
  @type size: int
1068 b1206984 Iustin Pop
  @param size: the size of the physical underlying device, in MiB
1069 b1206984 Iustin Pop
  @type owner: str
1070 b1206984 Iustin Pop
  @param owner: the name of the instance for which disk is created,
1071 b1206984 Iustin Pop
      used for device cache data
1072 b1206984 Iustin Pop
  @type on_primary: boolean
1073 b1206984 Iustin Pop
  @param on_primary:  indicates if it is the primary node or not
1074 b1206984 Iustin Pop
  @type info: string
1075 b1206984 Iustin Pop
  @param info: string that will be sent to the physical device
1076 b1206984 Iustin Pop
      creation, used for example to set (LVM) tags on LVs
1077 b1206984 Iustin Pop

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

1082 a8083063 Iustin Pop
  """
1083 a8083063 Iustin Pop
  clist = []
1084 a8083063 Iustin Pop
  if disk.children:
1085 a8083063 Iustin Pop
    for child in disk.children:
1086 3f78eef2 Iustin Pop
      crdev = _RecursiveAssembleBD(child, owner, on_primary)
1087 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
1088 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
1089 a8083063 Iustin Pop
        # be assembled
1090 a8083063 Iustin Pop
        crdev.Open()
1091 a8083063 Iustin Pop
      clist.append(crdev)
1092 a8083063 Iustin Pop
1093 dab69e97 Iustin Pop
  try:
1094 dab69e97 Iustin Pop
    device = bdev.Create(disk.dev_type, disk.physical_id, clist, size)
1095 dab69e97 Iustin Pop
  except errors.GenericError, err:
1096 dab69e97 Iustin Pop
    return False, "Can't create block device: %s" % str(err)
1097 6c626518 Iustin Pop
1098 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
1099 cf5a8306 Iustin Pop
    if not device.Assemble():
1100 dab69e97 Iustin Pop
      errorstring = "Can't assemble device after creation, very unusual event"
1101 18682bca Iustin Pop
      logging.error(errorstring)
1102 dab69e97 Iustin Pop
      return False, errorstring
1103 e31c43f7 Michael Hanselmann
    device.SetSyncSpeed(constants.SYNC_SPEED)
1104 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
1105 a8083063 Iustin Pop
      device.Open(force=True)
1106 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
1107 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
1108 a0c3fea1 Michael Hanselmann
1109 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
1110 a0c3fea1 Michael Hanselmann
1111 a8083063 Iustin Pop
  physical_id = device.unique_id
1112 dab69e97 Iustin Pop
  return True, physical_id
1113 a8083063 Iustin Pop
1114 a8083063 Iustin Pop
1115 a8083063 Iustin Pop
def RemoveBlockDevice(disk):
1116 a8083063 Iustin Pop
  """Remove a block device.
1117 a8083063 Iustin Pop

1118 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
1119 10c2650b Iustin Pop

1120 c41eea6e Iustin Pop
  @type disk: L{objects.Disk}
1121 10c2650b Iustin Pop
  @param disk: the disk object we should remove
1122 10c2650b Iustin Pop
  @rtype: boolean
1123 10c2650b Iustin Pop
  @return: the success of the operation
1124 a8083063 Iustin Pop

1125 a8083063 Iustin Pop
  """
1126 a8083063 Iustin Pop
  try:
1127 bca2e7f4 Iustin Pop
    rdev = _RecursiveFindBD(disk)
1128 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
1129 a8083063 Iustin Pop
    # probably can't attach
1130 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
1131 a8083063 Iustin Pop
    rdev = None
1132 a8083063 Iustin Pop
  if rdev is not None:
1133 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
1134 a8083063 Iustin Pop
    result = rdev.Remove()
1135 3f78eef2 Iustin Pop
    if result:
1136 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1137 a8083063 Iustin Pop
  else:
1138 a8083063 Iustin Pop
    result = True
1139 a8083063 Iustin Pop
  if disk.children:
1140 a8083063 Iustin Pop
    for child in disk.children:
1141 a8083063 Iustin Pop
      result = result and RemoveBlockDevice(child)
1142 a8083063 Iustin Pop
  return result
1143 a8083063 Iustin Pop
1144 a8083063 Iustin Pop
1145 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
1146 a8083063 Iustin Pop
  """Activate a block device for an instance.
1147 a8083063 Iustin Pop

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

1150 10c2650b Iustin Pop
  @note: this function is called recursively.
1151 a8083063 Iustin Pop

1152 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1153 10c2650b Iustin Pop
  @param disk: the disk we try to assemble
1154 10c2650b Iustin Pop
  @type owner: str
1155 10c2650b Iustin Pop
  @param owner: the name of the instance which owns the disk
1156 10c2650b Iustin Pop
  @type as_primary: boolean
1157 10c2650b Iustin Pop
  @param as_primary: if we should make the block device
1158 10c2650b Iustin Pop
      read/write
1159 a8083063 Iustin Pop

1160 10c2650b Iustin Pop
  @return: the assembled device or None (in case no device
1161 10c2650b Iustin Pop
      was assembled)
1162 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: in case there is an error
1163 10c2650b Iustin Pop
      during the activation of the children or the device
1164 10c2650b Iustin Pop
      itself
1165 a8083063 Iustin Pop

1166 a8083063 Iustin Pop
  """
1167 a8083063 Iustin Pop
  children = []
1168 a8083063 Iustin Pop
  if disk.children:
1169 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
1170 fc1dc9d7 Iustin Pop
    if mcn == -1:
1171 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
1172 fc1dc9d7 Iustin Pop
    else:
1173 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
1174 a8083063 Iustin Pop
    for chld_disk in disk.children:
1175 fc1dc9d7 Iustin Pop
      try:
1176 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1177 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
1178 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
1179 fc1dc9d7 Iustin Pop
          raise
1180 fc1dc9d7 Iustin Pop
        cdev = None
1181 18682bca Iustin Pop
        logging.debug("Error in child activation: %s", str(err))
1182 fc1dc9d7 Iustin Pop
      children.append(cdev)
1183 a8083063 Iustin Pop
1184 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
1185 f96e3c4f Iustin Pop
    r_dev = bdev.Assemble(disk.dev_type, disk.physical_id, children)
1186 e31c43f7 Michael Hanselmann
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1187 a8083063 Iustin Pop
    result = r_dev
1188 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
1189 a8083063 Iustin Pop
      r_dev.Open()
1190 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1191 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
1192 3f78eef2 Iustin Pop
1193 a8083063 Iustin Pop
  else:
1194 a8083063 Iustin Pop
    result = True
1195 a8083063 Iustin Pop
  return result
1196 a8083063 Iustin Pop
1197 a8083063 Iustin Pop
1198 3f78eef2 Iustin Pop
def AssembleBlockDevice(disk, owner, as_primary):
1199 a8083063 Iustin Pop
  """Activate a block device for an instance.
1200 a8083063 Iustin Pop

1201 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
1202 a8083063 Iustin Pop

1203 b1206984 Iustin Pop
  @rtype: str or boolean
1204 b1206984 Iustin Pop
  @return: a C{/dev/...} path for primary nodes, and
1205 b1206984 Iustin Pop
      C{True} for secondary nodes
1206 a8083063 Iustin Pop

1207 a8083063 Iustin Pop
  """
1208 3f78eef2 Iustin Pop
  result = _RecursiveAssembleBD(disk, owner, as_primary)
1209 a8083063 Iustin Pop
  if isinstance(result, bdev.BlockDev):
1210 a8083063 Iustin Pop
    result = result.dev_path
1211 a8083063 Iustin Pop
  return result
1212 a8083063 Iustin Pop
1213 a8083063 Iustin Pop
1214 a8083063 Iustin Pop
def ShutdownBlockDevice(disk):
1215 a8083063 Iustin Pop
  """Shut down a block device.
1216 a8083063 Iustin Pop

1217 c41eea6e Iustin Pop
  First, if the device is assembled (Attach() is successfull), then
1218 c41eea6e Iustin Pop
  the device is shutdown. Then the children of the device are
1219 c41eea6e Iustin Pop
  shutdown.
1220 a8083063 Iustin Pop

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

1225 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1226 10c2650b Iustin Pop
  @param disk: the description of the disk we should
1227 10c2650b Iustin Pop
      shutdown
1228 10c2650b Iustin Pop
  @rtype: boolean
1229 10c2650b Iustin Pop
  @return: the success of the operation
1230 10c2650b Iustin Pop

1231 a8083063 Iustin Pop
  """
1232 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1233 a8083063 Iustin Pop
  if r_dev is not None:
1234 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
1235 a8083063 Iustin Pop
    result = r_dev.Shutdown()
1236 3f78eef2 Iustin Pop
    if result:
1237 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1238 a8083063 Iustin Pop
  else:
1239 a8083063 Iustin Pop
    result = True
1240 a8083063 Iustin Pop
  if disk.children:
1241 a8083063 Iustin Pop
    for child in disk.children:
1242 a8083063 Iustin Pop
      result = result and ShutdownBlockDevice(child)
1243 a8083063 Iustin Pop
  return result
1244 a8083063 Iustin Pop
1245 a8083063 Iustin Pop
1246 153d9724 Iustin Pop
def MirrorAddChildren(parent_cdev, new_cdevs):
1247 153d9724 Iustin Pop
  """Extend a mirrored block device.
1248 a8083063 Iustin Pop

1249 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1250 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
1251 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1252 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
1253 10c2650b Iustin Pop
  @rtype: boolean
1254 10c2650b Iustin Pop
  @return: the success of the operation
1255 10c2650b Iustin Pop

1256 a8083063 Iustin Pop
  """
1257 bca2e7f4 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1258 153d9724 Iustin Pop
  if parent_bdev is None:
1259 18682bca Iustin Pop
    logging.error("Can't find parent device")
1260 a8083063 Iustin Pop
    return False
1261 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1262 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
1263 18682bca Iustin Pop
    logging.error("Can't find new device(s) to add: %s:%s",
1264 18682bca Iustin Pop
                  new_bdevs, new_cdevs)
1265 a8083063 Iustin Pop
    return False
1266 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
1267 a8083063 Iustin Pop
  return True
1268 a8083063 Iustin Pop
1269 a8083063 Iustin Pop
1270 153d9724 Iustin Pop
def MirrorRemoveChildren(parent_cdev, new_cdevs):
1271 153d9724 Iustin Pop
  """Shrink a mirrored block device.
1272 a8083063 Iustin Pop

1273 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1274 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
1275 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1276 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
1277 10c2650b Iustin Pop
  @rtype: boolean
1278 10c2650b Iustin Pop
  @return: the success of the operation
1279 10c2650b Iustin Pop

1280 a8083063 Iustin Pop
  """
1281 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1282 153d9724 Iustin Pop
  if parent_bdev is None:
1283 18682bca Iustin Pop
    logging.error("Can't find parent in remove children: %s", parent_cdev)
1284 a8083063 Iustin Pop
    return False
1285 e739bd57 Iustin Pop
  devs = []
1286 e739bd57 Iustin Pop
  for disk in new_cdevs:
1287 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
1288 e739bd57 Iustin Pop
    if rpath is None:
1289 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
1290 e739bd57 Iustin Pop
      if bd is None:
1291 18682bca Iustin Pop
        logging.error("Can't find dynamic device %s while removing children",
1292 18682bca Iustin Pop
                      disk)
1293 e739bd57 Iustin Pop
        return False
1294 e739bd57 Iustin Pop
      else:
1295 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
1296 e739bd57 Iustin Pop
    else:
1297 e739bd57 Iustin Pop
      devs.append(rpath)
1298 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
1299 a8083063 Iustin Pop
  return True
1300 a8083063 Iustin Pop
1301 a8083063 Iustin Pop
1302 a8083063 Iustin Pop
def GetMirrorStatus(disks):
1303 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
1304 a8083063 Iustin Pop

1305 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
1306 10c2650b Iustin Pop
  @param disks: the list of disks which we should query
1307 10c2650b Iustin Pop
  @rtype: disk
1308 10c2650b Iustin Pop
  @return:
1309 10c2650b Iustin Pop
      a list of (mirror_done, estimated_time) tuples, which
1310 c41eea6e Iustin Pop
      are the result of L{bdev.BlockDev.CombinedSyncStatus}
1311 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if any of the disks cannot be
1312 10c2650b Iustin Pop
      found
1313 a8083063 Iustin Pop

1314 a8083063 Iustin Pop
  """
1315 a8083063 Iustin Pop
  stats = []
1316 a8083063 Iustin Pop
  for dsk in disks:
1317 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
1318 a8083063 Iustin Pop
    if rbd is None:
1319 3ecf6786 Iustin Pop
      raise errors.BlockDeviceError("Can't find device %s" % str(dsk))
1320 a8083063 Iustin Pop
    stats.append(rbd.CombinedSyncStatus())
1321 a8083063 Iustin Pop
  return stats
1322 a8083063 Iustin Pop
1323 a8083063 Iustin Pop
1324 bca2e7f4 Iustin Pop
def _RecursiveFindBD(disk):
1325 a8083063 Iustin Pop
  """Check if a device is activated.
1326 a8083063 Iustin Pop

1327 a8083063 Iustin Pop
  If so, return informations about the real device.
1328 a8083063 Iustin Pop

1329 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1330 10c2650b Iustin Pop
  @param disk: the disk object we need to find
1331 a8083063 Iustin Pop

1332 10c2650b Iustin Pop
  @return: None if the device can't be found,
1333 10c2650b Iustin Pop
      otherwise the device instance
1334 a8083063 Iustin Pop

1335 a8083063 Iustin Pop
  """
1336 a8083063 Iustin Pop
  children = []
1337 a8083063 Iustin Pop
  if disk.children:
1338 a8083063 Iustin Pop
    for chdisk in disk.children:
1339 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
1340 a8083063 Iustin Pop
1341 a8083063 Iustin Pop
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children)
1342 a8083063 Iustin Pop
1343 a8083063 Iustin Pop
1344 a8083063 Iustin Pop
def FindBlockDevice(disk):
1345 a8083063 Iustin Pop
  """Check if a device is activated.
1346 a8083063 Iustin Pop

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

1349 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1350 10c2650b Iustin Pop
  @param disk: the disk to find
1351 10c2650b Iustin Pop
  @rtype: None or tuple
1352 10c2650b Iustin Pop
  @return: None if the disk cannot be found, otherwise a
1353 10c2650b Iustin Pop
      tuple (device_path, major, minor, sync_percent,
1354 10c2650b Iustin Pop
      estimated_time, is_degraded)
1355 a8083063 Iustin Pop

1356 a8083063 Iustin Pop
  """
1357 a8083063 Iustin Pop
  rbd = _RecursiveFindBD(disk)
1358 a8083063 Iustin Pop
  if rbd is None:
1359 a8083063 Iustin Pop
    return rbd
1360 0834c866 Iustin Pop
  return (rbd.dev_path, rbd.major, rbd.minor) + rbd.GetSyncStatus()
1361 a8083063 Iustin Pop
1362 a8083063 Iustin Pop
1363 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1364 a8083063 Iustin Pop
  """Write a file to the filesystem.
1365 a8083063 Iustin Pop

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

1369 10c2650b Iustin Pop
  @type file_name: str
1370 10c2650b Iustin Pop
  @param file_name: the target file name
1371 10c2650b Iustin Pop
  @type data: str
1372 10c2650b Iustin Pop
  @param data: the new contents of the file
1373 10c2650b Iustin Pop
  @type mode: int
1374 10c2650b Iustin Pop
  @param mode: the mode to give the file (can be None)
1375 10c2650b Iustin Pop
  @type uid: int
1376 10c2650b Iustin Pop
  @param uid: the owner of the file (can be -1 for default)
1377 10c2650b Iustin Pop
  @type gid: int
1378 10c2650b Iustin Pop
  @param gid: the group of the file (can be -1 for default)
1379 10c2650b Iustin Pop
  @type atime: float
1380 10c2650b Iustin Pop
  @param atime: the atime to set on the file (can be None)
1381 10c2650b Iustin Pop
  @type mtime: float
1382 10c2650b Iustin Pop
  @param mtime: the mtime to set on the file (can be None)
1383 10c2650b Iustin Pop
  @rtype: boolean
1384 10c2650b Iustin Pop
  @return: the success of the operation; errors are logged
1385 10c2650b Iustin Pop
      in the node daemon log
1386 10c2650b Iustin Pop

1387 a8083063 Iustin Pop
  """
1388 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
1389 18682bca Iustin Pop
    logging.error("Filename passed to UploadFile is not absolute: '%s'",
1390 18682bca Iustin Pop
                  file_name)
1391 a8083063 Iustin Pop
    return False
1392 a8083063 Iustin Pop
1393 97628462 Iustin Pop
  allowed_files = [
1394 97628462 Iustin Pop
    constants.CLUSTER_CONF_FILE,
1395 97628462 Iustin Pop
    constants.ETC_HOSTS,
1396 97628462 Iustin Pop
    constants.SSH_KNOWN_HOSTS_FILE,
1397 90fae627 Guido Trotter
    constants.VNC_PASSWORD_FILE,
1398 97628462 Iustin Pop
    ]
1399 afee8008 Michael Hanselmann
1400 553f1c1d Michael Hanselmann
  if file_name not in allowed_files:
1401 18682bca Iustin Pop
    logging.error("Filename passed to UploadFile not in allowed"
1402 18682bca Iustin Pop
                 " upload targets: '%s'", file_name)
1403 a8083063 Iustin Pop
    return False
1404 a8083063 Iustin Pop
1405 12bce260 Michael Hanselmann
  raw_data = _Decompress(data)
1406 12bce260 Michael Hanselmann
1407 12bce260 Michael Hanselmann
  utils.WriteFile(file_name, data=raw_data, mode=mode, uid=uid, gid=gid,
1408 41a57aab Michael Hanselmann
                  atime=atime, mtime=mtime)
1409 a8083063 Iustin Pop
  return True
1410 a8083063 Iustin Pop
1411 386b57af Iustin Pop
1412 03d1dba2 Michael Hanselmann
def WriteSsconfFiles(values):
1413 89b14f05 Iustin Pop
  """Update all ssconf files.
1414 89b14f05 Iustin Pop

1415 89b14f05 Iustin Pop
  Wrapper around the SimpleStore.WriteFiles.
1416 89b14f05 Iustin Pop

1417 89b14f05 Iustin Pop
  """
1418 89b14f05 Iustin Pop
  ssconf.SimpleStore().WriteFiles(values)
1419 6ddc95ec Michael Hanselmann
1420 6ddc95ec Michael Hanselmann
1421 a8083063 Iustin Pop
def _ErrnoOrStr(err):
1422 a8083063 Iustin Pop
  """Format an EnvironmentError exception.
1423 a8083063 Iustin Pop

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

1428 10c2650b Iustin Pop
  @type err: L{EnvironmentError}
1429 10c2650b Iustin Pop
  @param err: the exception to format
1430 a8083063 Iustin Pop

1431 a8083063 Iustin Pop
  """
1432 a8083063 Iustin Pop
  if hasattr(err, 'errno'):
1433 a8083063 Iustin Pop
    detail = errno.errorcode[err.errno]
1434 a8083063 Iustin Pop
  else:
1435 a8083063 Iustin Pop
    detail = str(err)
1436 a8083063 Iustin Pop
  return detail
1437 a8083063 Iustin Pop
1438 5d0fe286 Iustin Pop
1439 c26dabd7 Guido Trotter
def _OSOndiskVersion(name, os_dir):
1440 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
1441 a8083063 Iustin Pop

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

1445 10c2650b Iustin Pop
  @type name: str
1446 10c2650b Iustin Pop
  @param name: the OS name we should look for
1447 10c2650b Iustin Pop
  @type os_dir: str
1448 10c2650b Iustin Pop
  @param os_dir: the directory inwhich we should look for the OS
1449 10c2650b Iustin Pop
  @rtype: int or None
1450 10c2650b Iustin Pop
  @return:
1451 10c2650b Iustin Pop
      Either an integer denoting the version or None in the
1452 10c2650b Iustin Pop
      case when this is not a valid OS name.
1453 10c2650b Iustin Pop
  @raise errors.InvalidOS: if the OS cannot be found
1454 a8083063 Iustin Pop

1455 a8083063 Iustin Pop
  """
1456 a8083063 Iustin Pop
  api_file = os.path.sep.join([os_dir, "ganeti_api_version"])
1457 a8083063 Iustin Pop
1458 a8083063 Iustin Pop
  try:
1459 a8083063 Iustin Pop
    st = os.stat(api_file)
1460 a8083063 Iustin Pop
  except EnvironmentError, err:
1461 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "'ganeti_api_version' file not"
1462 3ecf6786 Iustin Pop
                           " found (%s)" % _ErrnoOrStr(err))
1463 a8083063 Iustin Pop
1464 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1465 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "'ganeti_api_version' file is not"
1466 3ecf6786 Iustin Pop
                           " a regular file")
1467 a8083063 Iustin Pop
1468 a8083063 Iustin Pop
  try:
1469 a8083063 Iustin Pop
    f = open(api_file)
1470 a8083063 Iustin Pop
    try:
1471 082a7f91 Guido Trotter
      api_versions = f.readlines()
1472 a8083063 Iustin Pop
    finally:
1473 a8083063 Iustin Pop
      f.close()
1474 a8083063 Iustin Pop
  except EnvironmentError, err:
1475 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "error while reading the"
1476 3ecf6786 Iustin Pop
                           " API version (%s)" % _ErrnoOrStr(err))
1477 a8083063 Iustin Pop
1478 082a7f91 Guido Trotter
  api_versions = [version.strip() for version in api_versions]
1479 a8083063 Iustin Pop
  try:
1480 082a7f91 Guido Trotter
    api_versions = [int(version) for version in api_versions]
1481 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
1482 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir,
1483 305a7297 Guido Trotter
                           "API version is not integer (%s)" % str(err))
1484 a8083063 Iustin Pop
1485 082a7f91 Guido Trotter
  return api_versions
1486 a8083063 Iustin Pop
1487 386b57af Iustin Pop
1488 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
1489 a8083063 Iustin Pop
  """Compute the validity for all OSes.
1490 a8083063 Iustin Pop

1491 10c2650b Iustin Pop
  @type top_dirs: list
1492 10c2650b Iustin Pop
  @param top_dirs: the list of directories in which to
1493 10c2650b Iustin Pop
      search (if not given defaults to
1494 10c2650b Iustin Pop
      L{constants.OS_SEARCH_PATH})
1495 10c2650b Iustin Pop
  @rtype: list of L{objects.OS}
1496 10c2650b Iustin Pop
  @return: an OS object for each name in all the given
1497 10c2650b Iustin Pop
      directories
1498 a8083063 Iustin Pop

1499 a8083063 Iustin Pop
  """
1500 7c3d51d4 Guido Trotter
  if top_dirs is None:
1501 7c3d51d4 Guido Trotter
    top_dirs = constants.OS_SEARCH_PATH
1502 a8083063 Iustin Pop
1503 a8083063 Iustin Pop
  result = []
1504 65fe4693 Iustin Pop
  for dir_name in top_dirs:
1505 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
1506 7c3d51d4 Guido Trotter
      try:
1507 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
1508 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
1509 18682bca Iustin Pop
        logging.exception("Can't list the OS directory %s", dir_name)
1510 7c3d51d4 Guido Trotter
        break
1511 7c3d51d4 Guido Trotter
      for name in f_names:
1512 7c3d51d4 Guido Trotter
        try:
1513 65fe4693 Iustin Pop
          os_inst = OSFromDisk(name, base_dir=dir_name)
1514 7c3d51d4 Guido Trotter
          result.append(os_inst)
1515 7c3d51d4 Guido Trotter
        except errors.InvalidOS, err:
1516 8fa42c7c Guido Trotter
          result.append(objects.OS.FromInvalidOS(err))
1517 a8083063 Iustin Pop
1518 a8083063 Iustin Pop
  return result
1519 a8083063 Iustin Pop
1520 a8083063 Iustin Pop
1521 56bcd3f4 Guido Trotter
def OSFromDisk(name, base_dir=None):
1522 a8083063 Iustin Pop
  """Create an OS instance from disk.
1523 a8083063 Iustin Pop

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

1528 8ee4dc80 Guido Trotter
  @type base_dir: string
1529 8ee4dc80 Guido Trotter
  @keyword base_dir: Base directory containing OS installations.
1530 8ee4dc80 Guido Trotter
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1531 10c2650b Iustin Pop
  @rtype: L{objects.OS}
1532 10c2650b Iustin Pop
  @return: the OS instance if we find a valid one
1533 10c2650b Iustin Pop
  @raise errors.InvalidOS: if we don't find a valid OS
1534 7c3d51d4 Guido Trotter

1535 a8083063 Iustin Pop
  """
1536 56bcd3f4 Guido Trotter
  if base_dir is None:
1537 57c177af Iustin Pop
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1538 c34c0cfd Iustin Pop
    if os_dir is None:
1539 c34c0cfd Iustin Pop
      raise errors.InvalidOS(name, None, "OS dir not found in search path")
1540 c34c0cfd Iustin Pop
  else:
1541 c34c0cfd Iustin Pop
    os_dir = os.path.sep.join([base_dir, name])
1542 a8083063 Iustin Pop
1543 082a7f91 Guido Trotter
  api_versions = _OSOndiskVersion(name, os_dir)
1544 a8083063 Iustin Pop
1545 082a7f91 Guido Trotter
  if constants.OS_API_VERSION not in api_versions:
1546 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "API version mismatch"
1547 305a7297 Guido Trotter
                           " (found %s want %s)"
1548 082a7f91 Guido Trotter
                           % (api_versions, constants.OS_API_VERSION))
1549 a8083063 Iustin Pop
1550 a8083063 Iustin Pop
  # OS Scripts dictionary, we will populate it with the actual script names
1551 62dbbe7e Guido Trotter
  os_scripts = dict.fromkeys(constants.OS_SCRIPTS)
1552 a8083063 Iustin Pop
1553 a8083063 Iustin Pop
  for script in os_scripts:
1554 a8083063 Iustin Pop
    os_scripts[script] = os.path.sep.join([os_dir, script])
1555 a8083063 Iustin Pop
1556 a8083063 Iustin Pop
    try:
1557 a8083063 Iustin Pop
      st = os.stat(os_scripts[script])
1558 a8083063 Iustin Pop
    except EnvironmentError, err:
1559 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' script missing (%s)" %
1560 3ecf6786 Iustin Pop
                             (script, _ErrnoOrStr(err)))
1561 a8083063 Iustin Pop
1562 a8083063 Iustin Pop
    if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1563 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' script not executable" %
1564 305a7297 Guido Trotter
                             script)
1565 a8083063 Iustin Pop
1566 a8083063 Iustin Pop
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1567 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' is not a regular file" %
1568 305a7297 Guido Trotter
                             script)
1569 a8083063 Iustin Pop
1570 a8083063 Iustin Pop
1571 8fa42c7c Guido Trotter
  return objects.OS(name=name, path=os_dir, status=constants.OS_VALID_STATUS,
1572 62dbbe7e Guido Trotter
                    create_script=os_scripts[constants.OS_SCRIPT_CREATE],
1573 62dbbe7e Guido Trotter
                    export_script=os_scripts[constants.OS_SCRIPT_EXPORT],
1574 62dbbe7e Guido Trotter
                    import_script=os_scripts[constants.OS_SCRIPT_IMPORT],
1575 62dbbe7e Guido Trotter
                    rename_script=os_scripts[constants.OS_SCRIPT_RENAME],
1576 082a7f91 Guido Trotter
                    api_versions=api_versions)
1577 a8083063 Iustin Pop
1578 2266edb2 Guido Trotter
def OSEnvironment(instance, debug=0):
1579 2266edb2 Guido Trotter
  """Calculate the environment for an os script.
1580 2266edb2 Guido Trotter

1581 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1582 2266edb2 Guido Trotter
  @param instance: target instance for the os script run
1583 2266edb2 Guido Trotter
  @type debug: integer
1584 10c2650b Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
1585 2266edb2 Guido Trotter
  @rtype: dict
1586 2266edb2 Guido Trotter
  @return: dict of environment variables
1587 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if the block device
1588 10c2650b Iustin Pop
      cannot be found
1589 2266edb2 Guido Trotter

1590 2266edb2 Guido Trotter
  """
1591 2266edb2 Guido Trotter
  result = {}
1592 2266edb2 Guido Trotter
  result['OS_API_VERSION'] = '%d' % constants.OS_API_VERSION
1593 2266edb2 Guido Trotter
  result['INSTANCE_NAME'] = instance.name
1594 2266edb2 Guido Trotter
  result['HYPERVISOR'] = instance.hypervisor
1595 2266edb2 Guido Trotter
  result['DISK_COUNT'] = '%d' % len(instance.disks)
1596 2266edb2 Guido Trotter
  result['NIC_COUNT'] = '%d' % len(instance.nics)
1597 2266edb2 Guido Trotter
  result['DEBUG_LEVEL'] = '%d' % debug
1598 2266edb2 Guido Trotter
  for idx, disk in enumerate(instance.disks):
1599 2266edb2 Guido Trotter
    real_disk = _RecursiveFindBD(disk)
1600 2266edb2 Guido Trotter
    if real_disk is None:
1601 2266edb2 Guido Trotter
      raise errors.BlockDeviceError("Block device '%s' is not set up" %
1602 2266edb2 Guido Trotter
                                    str(disk))
1603 2266edb2 Guido Trotter
    real_disk.Open()
1604 2266edb2 Guido Trotter
    result['DISK_%d_PATH' % idx] = real_disk.dev_path
1605 2266edb2 Guido Trotter
    # FIXME: When disks will have read-only mode, populate this
1606 2266edb2 Guido Trotter
    result['DISK_%d_ACCESS' % idx] = 'W'
1607 2266edb2 Guido Trotter
    if constants.HV_DISK_TYPE in instance.hvparams:
1608 2266edb2 Guido Trotter
      result['DISK_%d_FRONTEND_TYPE' % idx] = \
1609 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_DISK_TYPE]
1610 2266edb2 Guido Trotter
    if disk.dev_type in constants.LDS_BLOCK:
1611 2266edb2 Guido Trotter
      result['DISK_%d_BACKEND_TYPE' % idx] = 'block'
1612 2266edb2 Guido Trotter
    elif disk.dev_type == constants.LD_FILE:
1613 2266edb2 Guido Trotter
      result['DISK_%d_BACKEND_TYPE' % idx] = \
1614 2266edb2 Guido Trotter
        'file:%s' % disk.physical_id[0]
1615 2266edb2 Guido Trotter
  for idx, nic in enumerate(instance.nics):
1616 2266edb2 Guido Trotter
    result['NIC_%d_MAC' % idx] = nic.mac
1617 2266edb2 Guido Trotter
    if nic.ip:
1618 2266edb2 Guido Trotter
      result['NIC_%d_IP' % idx] = nic.ip
1619 2266edb2 Guido Trotter
    result['NIC_%d_BRIDGE' % idx] = nic.bridge
1620 2266edb2 Guido Trotter
    if constants.HV_NIC_TYPE in instance.hvparams:
1621 2266edb2 Guido Trotter
      result['NIC_%d_FRONTEND_TYPE' % idx] = \
1622 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_NIC_TYPE]
1623 2266edb2 Guido Trotter
1624 2266edb2 Guido Trotter
  return result
1625 a8083063 Iustin Pop
1626 594609c0 Iustin Pop
def GrowBlockDevice(disk, amount):
1627 594609c0 Iustin Pop
  """Grow a stack of block devices.
1628 594609c0 Iustin Pop

1629 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
1630 10c2650b Iustin Pop
  first ones to resize.
1631 594609c0 Iustin Pop

1632 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1633 10c2650b Iustin Pop
  @param disk: the disk to be grown
1634 10c2650b Iustin Pop
  @rtype: (status, result)
1635 10c2650b Iustin Pop
  @return: a tuple with the status of the operation
1636 10c2650b Iustin Pop
      (True/False), and the errors message if status
1637 10c2650b Iustin Pop
      is False
1638 594609c0 Iustin Pop

1639 594609c0 Iustin Pop
  """
1640 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1641 594609c0 Iustin Pop
  if r_dev is None:
1642 594609c0 Iustin Pop
    return False, "Cannot find block device %s" % (disk,)
1643 594609c0 Iustin Pop
1644 594609c0 Iustin Pop
  try:
1645 594609c0 Iustin Pop
    r_dev.Grow(amount)
1646 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
1647 594609c0 Iustin Pop
    return False, str(err)
1648 594609c0 Iustin Pop
1649 594609c0 Iustin Pop
  return True, None
1650 594609c0 Iustin Pop
1651 594609c0 Iustin Pop
1652 a8083063 Iustin Pop
def SnapshotBlockDevice(disk):
1653 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
1654 a8083063 Iustin Pop

1655 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
1656 a8083063 Iustin Pop
  just for the leaf lvm backend device.
1657 a8083063 Iustin Pop

1658 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
1659 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
1660 e9e9263d Guido Trotter
  @rtype: string
1661 e9e9263d Guido Trotter
  @return: snapshot disk path
1662 a8083063 Iustin Pop

1663 098c0958 Michael Hanselmann
  """
1664 a8083063 Iustin Pop
  if disk.children:
1665 a8083063 Iustin Pop
    if len(disk.children) == 1:
1666 a8083063 Iustin Pop
      # only one child, let's recurse on it
1667 a8083063 Iustin Pop
      return SnapshotBlockDevice(disk.children[0])
1668 a8083063 Iustin Pop
    else:
1669 a8083063 Iustin Pop
      # more than one child, choose one that matches
1670 a8083063 Iustin Pop
      for child in disk.children:
1671 a8083063 Iustin Pop
        if child.size == disk.size:
1672 a8083063 Iustin Pop
          # return implies breaking the loop
1673 a8083063 Iustin Pop
          return SnapshotBlockDevice(child)
1674 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
1675 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
1676 a8083063 Iustin Pop
    if r_dev is not None:
1677 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
1678 a8083063 Iustin Pop
      return r_dev.Snapshot(disk.size)
1679 a8083063 Iustin Pop
    else:
1680 a8083063 Iustin Pop
      return None
1681 a8083063 Iustin Pop
  else:
1682 3ecf6786 Iustin Pop
    raise errors.ProgrammerError("Cannot snapshot non-lvm block device"
1683 f4bc1f2c Michael Hanselmann
                                 " '%s' of type '%s'" %
1684 3ecf6786 Iustin Pop
                                 (disk.unique_id, disk.dev_type))
1685 a8083063 Iustin Pop
1686 a8083063 Iustin Pop
1687 74c47259 Iustin Pop
def ExportSnapshot(disk, dest_node, instance, cluster_name, idx):
1688 a8083063 Iustin Pop
  """Export a block device snapshot to a remote node.
1689 a8083063 Iustin Pop

1690 74c47259 Iustin Pop
  @type disk: L{objects.Disk}
1691 74c47259 Iustin Pop
  @param disk: the description of the disk to export
1692 74c47259 Iustin Pop
  @type dest_node: str
1693 74c47259 Iustin Pop
  @param dest_node: the destination node to export to
1694 74c47259 Iustin Pop
  @type instance: L{objects.Instance}
1695 74c47259 Iustin Pop
  @param instance: the instance object to whom the disk belongs
1696 74c47259 Iustin Pop
  @type cluster_name: str
1697 74c47259 Iustin Pop
  @param cluster_name: the cluster name, needed for SSH hostalias
1698 74c47259 Iustin Pop
  @type idx: int
1699 74c47259 Iustin Pop
  @param idx: the index of the disk in the instance's disk list,
1700 74c47259 Iustin Pop
      used to export to the OS scripts environment
1701 10c2650b Iustin Pop
  @rtype: boolean
1702 74c47259 Iustin Pop
  @return: the success of the operation
1703 a8083063 Iustin Pop

1704 098c0958 Michael Hanselmann
  """
1705 0607699d Guido Trotter
  export_env = OSEnvironment(instance)
1706 d324e3fc Guido Trotter
1707 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1708 a8083063 Iustin Pop
  export_script = inst_os.export_script
1709 a8083063 Iustin Pop
1710 a8083063 Iustin Pop
  logfile = "%s/exp-%s-%s-%s.log" % (constants.LOG_OS_DIR, inst_os.name,
1711 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
1712 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
1713 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
1714 0607699d Guido Trotter
  real_disk = _RecursiveFindBD(disk)
1715 0607699d Guido Trotter
  if real_disk is None:
1716 a8083063 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
1717 a8083063 Iustin Pop
                                  str(disk))
1718 0607699d Guido Trotter
  real_disk.Open()
1719 0607699d Guido Trotter
1720 0607699d Guido Trotter
  export_env['EXPORT_DEVICE'] = real_disk.dev_path
1721 74c47259 Iustin Pop
  export_env['EXPORT_INDEX'] = str(idx)
1722 a8083063 Iustin Pop
1723 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1724 a8083063 Iustin Pop
  destfile = disk.physical_id[1]
1725 a8083063 Iustin Pop
1726 a8083063 Iustin Pop
  # the target command is built out of three individual commands,
1727 a8083063 Iustin Pop
  # which are joined by pipes; we check each individual command for
1728 a8083063 Iustin Pop
  # valid parameters
1729 0607699d Guido Trotter
  expcmd = utils.BuildShellCmd("cd %s; %s 2>%s", inst_os.path,
1730 0607699d Guido Trotter
                               export_script, logfile)
1731 a8083063 Iustin Pop
1732 a8083063 Iustin Pop
  comprcmd = "gzip"
1733 a8083063 Iustin Pop
1734 72f0f7fd Iustin Pop
  destcmd = utils.BuildShellCmd("mkdir -p %s && cat > %s/%s",
1735 00003458 Guido Trotter
                                destdir, destdir, destfile)
1736 62c9ec92 Iustin Pop
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1737 62c9ec92 Iustin Pop
                                                   constants.GANETI_RUNAS,
1738 62c9ec92 Iustin Pop
                                                   destcmd)
1739 a8083063 Iustin Pop
1740 a8083063 Iustin Pop
  # all commands have been checked, so we're safe to combine them
1741 72f0f7fd Iustin Pop
  command = '|'.join([expcmd, comprcmd, utils.ShellQuoteArgs(remotecmd)])
1742 a8083063 Iustin Pop
1743 0607699d Guido Trotter
  result = utils.RunCmd(command, env=export_env)
1744 a8083063 Iustin Pop
1745 a8083063 Iustin Pop
  if result.failed:
1746 18682bca Iustin Pop
    logging.error("os snapshot export command '%s' returned error: %s"
1747 18682bca Iustin Pop
                  " output: %s", command, result.fail_reason, result.output)
1748 a8083063 Iustin Pop
    return False
1749 a8083063 Iustin Pop
1750 a8083063 Iustin Pop
  return True
1751 a8083063 Iustin Pop
1752 a8083063 Iustin Pop
1753 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
1754 a8083063 Iustin Pop
  """Write out the export configuration information.
1755 a8083063 Iustin Pop

1756 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1757 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
1758 10c2650b Iustin Pop
      saving configuration
1759 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
1760 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
1761 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
1762 a8083063 Iustin Pop

1763 10c2650b Iustin Pop
  @rtype: boolean
1764 10c2650b Iustin Pop
  @return: the success of the operation
1765 a8083063 Iustin Pop

1766 098c0958 Michael Hanselmann
  """
1767 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1768 a8083063 Iustin Pop
  finaldestdir = os.path.join(constants.EXPORT_DIR, instance.name)
1769 a8083063 Iustin Pop
1770 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1771 a8083063 Iustin Pop
1772 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
1773 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'version', '0')
1774 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
1775 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'source', instance.primary_node)
1776 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'os', instance.os)
1777 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'compression', 'gzip')
1778 a8083063 Iustin Pop
1779 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
1780 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'name', instance.name)
1781 51de46bf Iustin Pop
  config.set(constants.INISECT_INS, 'memory', '%d' %
1782 51de46bf Iustin Pop
             instance.beparams[constants.BE_MEMORY])
1783 51de46bf Iustin Pop
  config.set(constants.INISECT_INS, 'vcpus', '%d' %
1784 51de46bf Iustin Pop
             instance.beparams[constants.BE_VCPUS])
1785 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
1786 66f93869 Manuel Franceschini
1787 95268cc3 Iustin Pop
  nic_total = 0
1788 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
1789 95268cc3 Iustin Pop
    nic_total += 1
1790 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_mac' %
1791 a8083063 Iustin Pop
               nic_count, '%s' % nic.mac)
1792 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
1793 38206f3c Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_bridge' % nic_count,
1794 38206f3c Iustin Pop
               '%s' % nic.bridge)
1795 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
1796 95268cc3 Iustin Pop
  config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_total)
1797 a8083063 Iustin Pop
1798 726d7d68 Iustin Pop
  disk_total = 0
1799 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
1800 19d7f90a Guido Trotter
    if disk:
1801 726d7d68 Iustin Pop
      disk_total += 1
1802 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
1803 19d7f90a Guido Trotter
                 ('%s' % disk.iv_name))
1804 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
1805 19d7f90a Guido Trotter
                 ('%s' % disk.physical_id[1]))
1806 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
1807 19d7f90a Guido Trotter
                 ('%d' % disk.size))
1808 a8083063 Iustin Pop
1809 726d7d68 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_total)
1810 a8083063 Iustin Pop
1811 726d7d68 Iustin Pop
  utils.WriteFile(os.path.join(destdir, constants.EXPORT_CONF_FILE),
1812 726d7d68 Iustin Pop
                  data=config.Dumps())
1813 a8083063 Iustin Pop
  shutil.rmtree(finaldestdir, True)
1814 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
1815 a8083063 Iustin Pop
1816 a8083063 Iustin Pop
  return True
1817 a8083063 Iustin Pop
1818 a8083063 Iustin Pop
1819 a8083063 Iustin Pop
def ExportInfo(dest):
1820 a8083063 Iustin Pop
  """Get export configuration information.
1821 a8083063 Iustin Pop

1822 10c2650b Iustin Pop
  @type dest: str
1823 10c2650b Iustin Pop
  @param dest: directory containing the export
1824 a8083063 Iustin Pop

1825 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
1826 10c2650b Iustin Pop
  @return: a serializable config file containing the
1827 10c2650b Iustin Pop
      export info
1828 a8083063 Iustin Pop

1829 a8083063 Iustin Pop
  """
1830 a8083063 Iustin Pop
  cff = os.path.join(dest, constants.EXPORT_CONF_FILE)
1831 a8083063 Iustin Pop
1832 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1833 a8083063 Iustin Pop
  config.read(cff)
1834 a8083063 Iustin Pop
1835 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
1836 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
1837 a8083063 Iustin Pop
    return None
1838 a8083063 Iustin Pop
1839 a8083063 Iustin Pop
  return config
1840 a8083063 Iustin Pop
1841 a8083063 Iustin Pop
1842 6c0af70e Guido Trotter
def ImportOSIntoInstance(instance, src_node, src_images, cluster_name):
1843 a8083063 Iustin Pop
  """Import an os image into an instance.
1844 a8083063 Iustin Pop

1845 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1846 6c0af70e Guido Trotter
  @param instance: instance to import the disks into
1847 6c0af70e Guido Trotter
  @type src_node: string
1848 6c0af70e Guido Trotter
  @param src_node: source node for the disk images
1849 6c0af70e Guido Trotter
  @type src_images: list of string
1850 6c0af70e Guido Trotter
  @param src_images: absolute paths of the disk images
1851 6c0af70e Guido Trotter
  @rtype: list of boolean
1852 6c0af70e Guido Trotter
  @return: each boolean represent the success of importing the n-th disk
1853 a8083063 Iustin Pop

1854 a8083063 Iustin Pop
  """
1855 6c0af70e Guido Trotter
  import_env = OSEnvironment(instance)
1856 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1857 a8083063 Iustin Pop
  import_script = inst_os.import_script
1858 a8083063 Iustin Pop
1859 a8083063 Iustin Pop
  logfile = "%s/import-%s-%s-%s.log" % (constants.LOG_OS_DIR, instance.os,
1860 a8083063 Iustin Pop
                                        instance.name, int(time.time()))
1861 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
1862 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
1863 a8083063 Iustin Pop
1864 a8083063 Iustin Pop
  comprcmd = "gunzip"
1865 d868edb4 Iustin Pop
  impcmd = utils.BuildShellCmd("(cd %s; %s >%s 2>&1)", inst_os.path,
1866 d868edb4 Iustin Pop
                               import_script, logfile)
1867 a8083063 Iustin Pop
1868 6c0af70e Guido Trotter
  final_result = []
1869 6c0af70e Guido Trotter
  for idx, image in enumerate(src_images):
1870 6c0af70e Guido Trotter
    if image:
1871 6c0af70e Guido Trotter
      destcmd = utils.BuildShellCmd('cat %s', image)
1872 6c0af70e Guido Trotter
      remotecmd = _GetSshRunner(cluster_name).BuildCmd(src_node,
1873 6c0af70e Guido Trotter
                                                       constants.GANETI_RUNAS,
1874 6c0af70e Guido Trotter
                                                       destcmd)
1875 6c0af70e Guido Trotter
      command = '|'.join([utils.ShellQuoteArgs(remotecmd), comprcmd, impcmd])
1876 6c0af70e Guido Trotter
      import_env['IMPORT_DEVICE'] = import_env['DISK_%d_PATH' % idx]
1877 74c47259 Iustin Pop
      import_env['IMPORT_INDEX'] = str(idx)
1878 6c0af70e Guido Trotter
      result = utils.RunCmd(command, env=import_env)
1879 6c0af70e Guido Trotter
      if result.failed:
1880 726d7d68 Iustin Pop
        logging.error("Disk import command '%s' returned error: %s"
1881 726d7d68 Iustin Pop
                      " output: %s", command, result.fail_reason,
1882 726d7d68 Iustin Pop
                      result.output)
1883 6c0af70e Guido Trotter
        final_result.append(False)
1884 6c0af70e Guido Trotter
      else:
1885 6c0af70e Guido Trotter
        final_result.append(True)
1886 6c0af70e Guido Trotter
    else:
1887 6c0af70e Guido Trotter
      final_result.append(True)
1888 a8083063 Iustin Pop
1889 6c0af70e Guido Trotter
  return final_result
1890 a8083063 Iustin Pop
1891 a8083063 Iustin Pop
1892 a8083063 Iustin Pop
def ListExports():
1893 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
1894 098c0958 Michael Hanselmann

1895 10c2650b Iustin Pop
  @rtype: list
1896 10c2650b Iustin Pop
  @return: list of the exports
1897 10c2650b Iustin Pop

1898 a8083063 Iustin Pop
  """
1899 a8083063 Iustin Pop
  if os.path.isdir(constants.EXPORT_DIR):
1900 eedbda4b Michael Hanselmann
    return utils.ListVisibleFiles(constants.EXPORT_DIR)
1901 a8083063 Iustin Pop
  else:
1902 a8083063 Iustin Pop
    return []
1903 a8083063 Iustin Pop
1904 a8083063 Iustin Pop
1905 a8083063 Iustin Pop
def RemoveExport(export):
1906 a8083063 Iustin Pop
  """Remove an existing export from the node.
1907 a8083063 Iustin Pop

1908 10c2650b Iustin Pop
  @type export: str
1909 10c2650b Iustin Pop
  @param export: the name of the export to remove
1910 10c2650b Iustin Pop
  @rtype: boolean
1911 10c2650b Iustin Pop
  @return: the success of the operation
1912 a8083063 Iustin Pop

1913 098c0958 Michael Hanselmann
  """
1914 a8083063 Iustin Pop
  target = os.path.join(constants.EXPORT_DIR, export)
1915 a8083063 Iustin Pop
1916 a8083063 Iustin Pop
  shutil.rmtree(target)
1917 a8083063 Iustin Pop
  # TODO: catch some of the relevant exceptions and provide a pretty
1918 a8083063 Iustin Pop
  # error message if rmtree fails.
1919 a8083063 Iustin Pop
1920 a8083063 Iustin Pop
  return True
1921 a8083063 Iustin Pop
1922 a8083063 Iustin Pop
1923 f3e513ad Iustin Pop
def RenameBlockDevices(devlist):
1924 f3e513ad Iustin Pop
  """Rename a list of block devices.
1925 f3e513ad Iustin Pop

1926 10c2650b Iustin Pop
  @type devlist: list of tuples
1927 10c2650b Iustin Pop
  @param devlist: list of tuples of the form  (disk,
1928 10c2650b Iustin Pop
      new_logical_id, new_physical_id); disk is an
1929 10c2650b Iustin Pop
      L{objects.Disk} object describing the current disk,
1930 10c2650b Iustin Pop
      and new logical_id/physical_id is the name we
1931 10c2650b Iustin Pop
      rename it to
1932 10c2650b Iustin Pop
  @rtype: boolean
1933 10c2650b Iustin Pop
  @return: True if all renames succeeded, False otherwise
1934 f3e513ad Iustin Pop

1935 f3e513ad Iustin Pop
  """
1936 f3e513ad Iustin Pop
  result = True
1937 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
1938 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
1939 f3e513ad Iustin Pop
    if dev is None:
1940 f3e513ad Iustin Pop
      result = False
1941 f3e513ad Iustin Pop
      continue
1942 f3e513ad Iustin Pop
    try:
1943 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
1944 f3e513ad Iustin Pop
      dev.Rename(unique_id)
1945 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
1946 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
1947 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
1948 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
1949 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
1950 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
1951 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
1952 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
1953 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
1954 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
1955 f3e513ad Iustin Pop
      result = False
1956 f3e513ad Iustin Pop
  return result
1957 f3e513ad Iustin Pop
1958 f3e513ad Iustin Pop
1959 778b75bb Manuel Franceschini
def _TransformFileStorageDir(file_storage_dir):
1960 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
1961 778b75bb Manuel Franceschini

1962 778b75bb Manuel Franceschini
  Checks wheter the given file_storage_dir is within the cluster-wide
1963 778b75bb Manuel Franceschini
  default file_storage_dir stored in SimpleStore. Only paths under that
1964 778b75bb Manuel Franceschini
  directory are allowed.
1965 778b75bb Manuel Franceschini

1966 b1206984 Iustin Pop
  @type file_storage_dir: str
1967 b1206984 Iustin Pop
  @param file_storage_dir: the path to check
1968 d61cbe76 Iustin Pop

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

1971 778b75bb Manuel Franceschini
  """
1972 c657dcc9 Michael Hanselmann
  cfg = _GetConfig()
1973 778b75bb Manuel Franceschini
  file_storage_dir = os.path.normpath(file_storage_dir)
1974 c657dcc9 Michael Hanselmann
  base_file_storage_dir = cfg.GetFileStorageDir()
1975 778b75bb Manuel Franceschini
  if (not os.path.commonprefix([file_storage_dir, base_file_storage_dir]) ==
1976 778b75bb Manuel Franceschini
      base_file_storage_dir):
1977 18682bca Iustin Pop
    logging.error("file storage directory '%s' is not under base file"
1978 18682bca Iustin Pop
                  " storage directory '%s'",
1979 18682bca Iustin Pop
                  file_storage_dir, base_file_storage_dir)
1980 778b75bb Manuel Franceschini
    return None
1981 778b75bb Manuel Franceschini
  return file_storage_dir
1982 778b75bb Manuel Franceschini
1983 778b75bb Manuel Franceschini
1984 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
1985 778b75bb Manuel Franceschini
  """Create file storage directory.
1986 778b75bb Manuel Franceschini

1987 b1206984 Iustin Pop
  @type file_storage_dir: str
1988 b1206984 Iustin Pop
  @param file_storage_dir: directory to create
1989 778b75bb Manuel Franceschini

1990 b1206984 Iustin Pop
  @rtype: tuple
1991 b1206984 Iustin Pop
  @return: tuple with first element a boolean indicating wheter dir
1992 b1206984 Iustin Pop
      creation was successful or not
1993 778b75bb Manuel Franceschini

1994 778b75bb Manuel Franceschini
  """
1995 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
1996 778b75bb Manuel Franceschini
  result = True,
1997 778b75bb Manuel Franceschini
  if not file_storage_dir:
1998 778b75bb Manuel Franceschini
    result = False,
1999 778b75bb Manuel Franceschini
  else:
2000 778b75bb Manuel Franceschini
    if os.path.exists(file_storage_dir):
2001 778b75bb Manuel Franceschini
      if not os.path.isdir(file_storage_dir):
2002 18682bca Iustin Pop
        logging.error("'%s' is not a directory", file_storage_dir)
2003 778b75bb Manuel Franceschini
        result = False,
2004 778b75bb Manuel Franceschini
    else:
2005 778b75bb Manuel Franceschini
      try:
2006 778b75bb Manuel Franceschini
        os.makedirs(file_storage_dir, 0750)
2007 778b75bb Manuel Franceschini
      except OSError, err:
2008 18682bca Iustin Pop
        logging.error("Cannot create file storage directory '%s': %s",
2009 18682bca Iustin Pop
                      file_storage_dir, err)
2010 778b75bb Manuel Franceschini
        result = False,
2011 778b75bb Manuel Franceschini
  return result
2012 778b75bb Manuel Franceschini
2013 778b75bb Manuel Franceschini
2014 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
2015 778b75bb Manuel Franceschini
  """Remove file storage directory.
2016 778b75bb Manuel Franceschini

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

2019 10c2650b Iustin Pop
  @type file_storage_dir: str
2020 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
2021 10c2650b Iustin Pop
  @rtype: tuple (success,)
2022 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2023 10c2650b Iustin Pop
      whether the operation was successfull
2024 778b75bb Manuel Franceschini

2025 778b75bb Manuel Franceschini
  """
2026 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
2027 778b75bb Manuel Franceschini
  result = True,
2028 778b75bb Manuel Franceschini
  if not file_storage_dir:
2029 778b75bb Manuel Franceschini
    result = False,
2030 778b75bb Manuel Franceschini
  else:
2031 778b75bb Manuel Franceschini
    if os.path.exists(file_storage_dir):
2032 778b75bb Manuel Franceschini
      if not os.path.isdir(file_storage_dir):
2033 18682bca Iustin Pop
        logging.error("'%s' is not a directory", file_storage_dir)
2034 778b75bb Manuel Franceschini
        result = False,
2035 778b75bb Manuel Franceschini
      # deletes dir only if empty, otherwise we want to return False
2036 778b75bb Manuel Franceschini
      try:
2037 778b75bb Manuel Franceschini
        os.rmdir(file_storage_dir)
2038 778b75bb Manuel Franceschini
      except OSError, err:
2039 18682bca Iustin Pop
        logging.exception("Cannot remove file storage directory '%s'",
2040 18682bca Iustin Pop
                          file_storage_dir)
2041 778b75bb Manuel Franceschini
        result = False,
2042 778b75bb Manuel Franceschini
  return result
2043 778b75bb Manuel Franceschini
2044 778b75bb Manuel Franceschini
2045 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
2046 778b75bb Manuel Franceschini
  """Rename the file storage directory.
2047 778b75bb Manuel Franceschini

2048 10c2650b Iustin Pop
  @type old_file_storage_dir: str
2049 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
2050 10c2650b Iustin Pop
  @type new_file_storage_dir: str
2051 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
2052 10c2650b Iustin Pop
  @rtype: tuple (success,)
2053 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
2054 10c2650b Iustin Pop
      whether the operation was successful
2055 778b75bb Manuel Franceschini

2056 778b75bb Manuel Franceschini
  """
2057 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
2058 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
2059 778b75bb Manuel Franceschini
  result = True,
2060 778b75bb Manuel Franceschini
  if not old_file_storage_dir or not new_file_storage_dir:
2061 778b75bb Manuel Franceschini
    result = False,
2062 778b75bb Manuel Franceschini
  else:
2063 778b75bb Manuel Franceschini
    if not os.path.exists(new_file_storage_dir):
2064 778b75bb Manuel Franceschini
      if os.path.isdir(old_file_storage_dir):
2065 778b75bb Manuel Franceschini
        try:
2066 778b75bb Manuel Franceschini
          os.rename(old_file_storage_dir, new_file_storage_dir)
2067 778b75bb Manuel Franceschini
        except OSError, err:
2068 18682bca Iustin Pop
          logging.exception("Cannot rename '%s' to '%s'",
2069 18682bca Iustin Pop
                            old_file_storage_dir, new_file_storage_dir)
2070 778b75bb Manuel Franceschini
          result =  False,
2071 778b75bb Manuel Franceschini
      else:
2072 18682bca Iustin Pop
        logging.error("'%s' is not a directory", old_file_storage_dir)
2073 778b75bb Manuel Franceschini
        result = False,
2074 778b75bb Manuel Franceschini
    else:
2075 778b75bb Manuel Franceschini
      if os.path.exists(old_file_storage_dir):
2076 18682bca Iustin Pop
        logging.error("Cannot rename '%s' to '%s'. Both locations exist.",
2077 18682bca Iustin Pop
                      old_file_storage_dir, new_file_storage_dir)
2078 778b75bb Manuel Franceschini
        result = False,
2079 778b75bb Manuel Franceschini
  return result
2080 778b75bb Manuel Franceschini
2081 778b75bb Manuel Franceschini
2082 dc31eae3 Michael Hanselmann
def _IsJobQueueFile(file_name):
2083 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
2084 ca52cdeb Michael Hanselmann

2085 10c2650b Iustin Pop
  @type file_name: str
2086 10c2650b Iustin Pop
  @param file_name: the file name we should check
2087 10c2650b Iustin Pop
  @rtype: boolean
2088 10c2650b Iustin Pop
  @return: whether the file is under the queue directory
2089 10c2650b Iustin Pop

2090 ca52cdeb Michael Hanselmann
  """
2091 ca52cdeb Michael Hanselmann
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
2092 dc31eae3 Michael Hanselmann
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
2093 dc31eae3 Michael Hanselmann
2094 dc31eae3 Michael Hanselmann
  if not result:
2095 ca52cdeb Michael Hanselmann
    logging.error("'%s' is not a file in the queue directory",
2096 ca52cdeb Michael Hanselmann
                  file_name)
2097 dc31eae3 Michael Hanselmann
2098 dc31eae3 Michael Hanselmann
  return result
2099 dc31eae3 Michael Hanselmann
2100 dc31eae3 Michael Hanselmann
2101 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
2102 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
2103 dc31eae3 Michael Hanselmann

2104 10c2650b Iustin Pop
  This is just a wrapper over L{utils.WriteFile}, with proper
2105 10c2650b Iustin Pop
  checking.
2106 10c2650b Iustin Pop

2107 10c2650b Iustin Pop
  @type file_name: str
2108 10c2650b Iustin Pop
  @param file_name: the job file name
2109 10c2650b Iustin Pop
  @type content: str
2110 10c2650b Iustin Pop
  @param content: the new job contents
2111 10c2650b Iustin Pop
  @rtype: boolean
2112 10c2650b Iustin Pop
  @return: the success of the operation
2113 10c2650b Iustin Pop

2114 dc31eae3 Michael Hanselmann
  """
2115 dc31eae3 Michael Hanselmann
  if not _IsJobQueueFile(file_name):
2116 ca52cdeb Michael Hanselmann
    return False
2117 ca52cdeb Michael Hanselmann
2118 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
2119 12bce260 Michael Hanselmann
  utils.WriteFile(file_name, data=_Decompress(content))
2120 ca52cdeb Michael Hanselmann
2121 ca52cdeb Michael Hanselmann
  return True
2122 ca52cdeb Michael Hanselmann
2123 ca52cdeb Michael Hanselmann
2124 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
2125 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
2126 af5ebcb1 Michael Hanselmann

2127 c41eea6e Iustin Pop
  This is just a wrapper over os.rename with proper checking.
2128 10c2650b Iustin Pop

2129 10c2650b Iustin Pop
  @type old: str
2130 10c2650b Iustin Pop
  @param old: the old (actual) file name
2131 10c2650b Iustin Pop
  @type new: str
2132 10c2650b Iustin Pop
  @param new: the desired file name
2133 10c2650b Iustin Pop
  @rtype: boolean
2134 10c2650b Iustin Pop
  @return: the success of the operation
2135 10c2650b Iustin Pop

2136 af5ebcb1 Michael Hanselmann
  """
2137 af5ebcb1 Michael Hanselmann
  if not (_IsJobQueueFile(old) and _IsJobQueueFile(new)):
2138 af5ebcb1 Michael Hanselmann
    return False
2139 af5ebcb1 Michael Hanselmann
2140 58b22b6e Michael Hanselmann
  utils.RenameFile(old, new, mkdir=True)
2141 af5ebcb1 Michael Hanselmann
2142 af5ebcb1 Michael Hanselmann
  return True
2143 af5ebcb1 Michael Hanselmann
2144 af5ebcb1 Michael Hanselmann
2145 5d672980 Iustin Pop
def JobQueueSetDrainFlag(drain_flag):
2146 5d672980 Iustin Pop
  """Set the drain flag for the queue.
2147 5d672980 Iustin Pop

2148 5d672980 Iustin Pop
  This will set or unset the queue drain flag.
2149 5d672980 Iustin Pop

2150 10c2650b Iustin Pop
  @type drain_flag: boolean
2151 5d672980 Iustin Pop
  @param drain_flag: if True, will set the drain flag, otherwise reset it.
2152 10c2650b Iustin Pop
  @rtype: boolean
2153 10c2650b Iustin Pop
  @return: always True
2154 10c2650b Iustin Pop
  @warning: the function always returns True
2155 5d672980 Iustin Pop

2156 5d672980 Iustin Pop
  """
2157 5d672980 Iustin Pop
  if drain_flag:
2158 5d672980 Iustin Pop
    utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True)
2159 5d672980 Iustin Pop
  else:
2160 5d672980 Iustin Pop
    utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
2161 5d672980 Iustin Pop
2162 5d672980 Iustin Pop
  return True
2163 5d672980 Iustin Pop
2164 5d672980 Iustin Pop
2165 b2e7666a Iustin Pop
def CloseBlockDevices(instance_name, disks):
2166 d61cbe76 Iustin Pop
  """Closes the given block devices.
2167 d61cbe76 Iustin Pop

2168 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
2169 10c2650b Iustin Pop
  DRBD).
2170 10c2650b Iustin Pop

2171 b2e7666a Iustin Pop
  @param instance_name: if the argument is not empty, the symlinks
2172 b2e7666a Iustin Pop
      of this instance will be removed
2173 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
2174 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
2175 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2176 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2177 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2178 10c2650b Iustin Pop
      which will contain the error details in case we
2179 10c2650b Iustin Pop
      failed
2180 d61cbe76 Iustin Pop

2181 d61cbe76 Iustin Pop
  """
2182 d61cbe76 Iustin Pop
  bdevs = []
2183 d61cbe76 Iustin Pop
  for cf in disks:
2184 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
2185 d61cbe76 Iustin Pop
    if rd is None:
2186 d61cbe76 Iustin Pop
      return (False, "Can't find device %s" % cf)
2187 d61cbe76 Iustin Pop
    bdevs.append(rd)
2188 d61cbe76 Iustin Pop
2189 d61cbe76 Iustin Pop
  msg = []
2190 d61cbe76 Iustin Pop
  for rd in bdevs:
2191 d61cbe76 Iustin Pop
    try:
2192 d61cbe76 Iustin Pop
      rd.Close()
2193 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
2194 d61cbe76 Iustin Pop
      msg.append(str(err))
2195 d61cbe76 Iustin Pop
  if msg:
2196 d61cbe76 Iustin Pop
    return (False, "Can't make devices secondary: %s" % ",".join(msg))
2197 d61cbe76 Iustin Pop
  else:
2198 b2e7666a Iustin Pop
    if instance_name:
2199 5282084b Iustin Pop
      _RemoveBlockDevLinks(instance_name, disks)
2200 d61cbe76 Iustin Pop
    return (True, "All devices secondary")
2201 d61cbe76 Iustin Pop
2202 d61cbe76 Iustin Pop
2203 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
2204 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
2205 6217e295 Iustin Pop

2206 6217e295 Iustin Pop
  @type hvname: string
2207 6217e295 Iustin Pop
  @param hvname: the hypervisor name
2208 6217e295 Iustin Pop
  @type hvparams: dict
2209 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
2210 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2211 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2212 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2213 10c2650b Iustin Pop
      which will contain the error details in case we
2214 10c2650b Iustin Pop
      failed
2215 6217e295 Iustin Pop

2216 6217e295 Iustin Pop
  """
2217 6217e295 Iustin Pop
  try:
2218 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
2219 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
2220 6217e295 Iustin Pop
    return (True, "Validation passed")
2221 6217e295 Iustin Pop
  except errors.HypervisorError, err:
2222 6217e295 Iustin Pop
    return (False, str(err))
2223 6217e295 Iustin Pop
2224 6217e295 Iustin Pop
2225 56aa9fd5 Iustin Pop
def DemoteFromMC():
2226 56aa9fd5 Iustin Pop
  """Demotes the current node from master candidate role.
2227 56aa9fd5 Iustin Pop

2228 56aa9fd5 Iustin Pop
  """
2229 56aa9fd5 Iustin Pop
  # try to ensure we're not the master by mistake
2230 56aa9fd5 Iustin Pop
  master, myself = ssconf.GetMasterAndMyself()
2231 56aa9fd5 Iustin Pop
  if master == myself:
2232 56aa9fd5 Iustin Pop
    return (False, "ssconf status shows I'm the master node, will not demote")
2233 56aa9fd5 Iustin Pop
  pid_file = utils.DaemonPidFileName(constants.MASTERD_PID)
2234 56aa9fd5 Iustin Pop
  if utils.IsProcessAlive(utils.ReadPidFile(pid_file)):
2235 56aa9fd5 Iustin Pop
    return (False, "The master daemon is running, will not demote")
2236 56aa9fd5 Iustin Pop
  try:
2237 56aa9fd5 Iustin Pop
    utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2238 56aa9fd5 Iustin Pop
  except EnvironmentError, err:
2239 56aa9fd5 Iustin Pop
    if err.errno != errno.ENOENT:
2240 56aa9fd5 Iustin Pop
      return (False, "Error while backing up cluster file: %s" % str(err))
2241 56aa9fd5 Iustin Pop
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2242 56aa9fd5 Iustin Pop
  return (True, "Done")
2243 56aa9fd5 Iustin Pop
2244 56aa9fd5 Iustin Pop
2245 6b93ec9d Iustin Pop
def _FindDisks(nodes_ip, disks):
2246 6b93ec9d Iustin Pop
  """Sets the physical ID on disks and returns the block devices.
2247 6b93ec9d Iustin Pop

2248 6b93ec9d Iustin Pop
  """
2249 6b93ec9d Iustin Pop
  # set the correct physical ID
2250 6b93ec9d Iustin Pop
  my_name = utils.HostInfo().name
2251 6b93ec9d Iustin Pop
  for cf in disks:
2252 6b93ec9d Iustin Pop
    cf.SetPhysicalID(my_name, nodes_ip)
2253 6b93ec9d Iustin Pop
2254 6b93ec9d Iustin Pop
  bdevs = []
2255 6b93ec9d Iustin Pop
2256 6b93ec9d Iustin Pop
  for cf in disks:
2257 6b93ec9d Iustin Pop
    rd = _RecursiveFindBD(cf)
2258 6b93ec9d Iustin Pop
    if rd is None:
2259 6b93ec9d Iustin Pop
      return (False, "Can't find device %s" % cf)
2260 6b93ec9d Iustin Pop
    bdevs.append(rd)
2261 6b93ec9d Iustin Pop
  return (True, bdevs)
2262 6b93ec9d Iustin Pop
2263 6b93ec9d Iustin Pop
2264 6b93ec9d Iustin Pop
def DrbdDisconnectNet(nodes_ip, disks):
2265 6b93ec9d Iustin Pop
  """Disconnects the network on a list of drbd devices.
2266 6b93ec9d Iustin Pop

2267 6b93ec9d Iustin Pop
  """
2268 6b93ec9d Iustin Pop
  status, bdevs = _FindDisks(nodes_ip, disks)
2269 6b93ec9d Iustin Pop
  if not status:
2270 6b93ec9d Iustin Pop
    return status, bdevs
2271 6b93ec9d Iustin Pop
2272 6b93ec9d Iustin Pop
  # disconnect disks
2273 6b93ec9d Iustin Pop
  for rd in bdevs:
2274 6b93ec9d Iustin Pop
    try:
2275 6b93ec9d Iustin Pop
      rd.DisconnectNet()
2276 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
2277 6b93ec9d Iustin Pop
      logging.exception("Failed to go into standalone mode")
2278 6b93ec9d Iustin Pop
      return (False, "Can't change network configuration: %s" % str(err))
2279 6b93ec9d Iustin Pop
  return (True, "All disks are now disconnected")
2280 6b93ec9d Iustin Pop
2281 6b93ec9d Iustin Pop
2282 6b93ec9d Iustin Pop
def DrbdAttachNet(nodes_ip, disks, instance_name, multimaster):
2283 6b93ec9d Iustin Pop
  """Attaches the network on a list of drbd devices.
2284 6b93ec9d Iustin Pop

2285 6b93ec9d Iustin Pop
  """
2286 6b93ec9d Iustin Pop
  status, bdevs = _FindDisks(nodes_ip, disks)
2287 6b93ec9d Iustin Pop
  if not status:
2288 6b93ec9d Iustin Pop
    return status, bdevs
2289 6b93ec9d Iustin Pop
2290 6b93ec9d Iustin Pop
  if multimaster:
2291 53c776b5 Iustin Pop
    for idx, rd in enumerate(bdevs):
2292 6b93ec9d Iustin Pop
      try:
2293 53c776b5 Iustin Pop
        _SymlinkBlockDev(instance_name, rd.dev_path, idx)
2294 6b93ec9d Iustin Pop
      except EnvironmentError, err:
2295 6b93ec9d Iustin Pop
        return (False, "Can't create symlink: %s" % str(err))
2296 6b93ec9d Iustin Pop
  # reconnect disks, switch to new master configuration and if
2297 6b93ec9d Iustin Pop
  # needed primary mode
2298 6b93ec9d Iustin Pop
  for rd in bdevs:
2299 6b93ec9d Iustin Pop
    try:
2300 6b93ec9d Iustin Pop
      rd.AttachNet(multimaster)
2301 6b93ec9d Iustin Pop
    except errors.BlockDeviceError, err:
2302 6b93ec9d Iustin Pop
      return (False, "Can't change network configuration: %s" % str(err))
2303 6b93ec9d Iustin Pop
  # wait until the disks are connected; we need to retry the re-attach
2304 6b93ec9d Iustin Pop
  # if the device becomes standalone, as this might happen if the one
2305 6b93ec9d Iustin Pop
  # node disconnects and reconnects in a different mode before the
2306 6b93ec9d Iustin Pop
  # other node reconnects; in this case, one or both of the nodes will
2307 6b93ec9d Iustin Pop
  # decide it has wrong configuration and switch to standalone
2308 6b93ec9d Iustin Pop
  RECONNECT_TIMEOUT = 2 * 60
2309 6b93ec9d Iustin Pop
  sleep_time = 0.100 # start with 100 miliseconds
2310 6b93ec9d Iustin Pop
  timeout_limit = time.time() + RECONNECT_TIMEOUT
2311 6b93ec9d Iustin Pop
  while time.time() < timeout_limit:
2312 6b93ec9d Iustin Pop
    all_connected = True
2313 6b93ec9d Iustin Pop
    for rd in bdevs:
2314 6b93ec9d Iustin Pop
      stats = rd.GetProcStatus()
2315 6b93ec9d Iustin Pop
      if not (stats.is_connected or stats.is_in_resync):
2316 6b93ec9d Iustin Pop
        all_connected = False
2317 6b93ec9d Iustin Pop
      if stats.is_standalone:
2318 6b93ec9d Iustin Pop
        # peer had different config info and this node became
2319 6b93ec9d Iustin Pop
        # standalone, even though this should not happen with the
2320 6b93ec9d Iustin Pop
        # new staged way of changing disk configs
2321 6b93ec9d Iustin Pop
        try:
2322 6b93ec9d Iustin Pop
          rd.ReAttachNet(multimaster)
2323 6b93ec9d Iustin Pop
        except errors.BlockDeviceError, err:
2324 6b93ec9d Iustin Pop
          return (False, "Can't change network configuration: %s" % str(err))
2325 6b93ec9d Iustin Pop
    if all_connected:
2326 6b93ec9d Iustin Pop
      break
2327 6b93ec9d Iustin Pop
    time.sleep(sleep_time)
2328 6b93ec9d Iustin Pop
    sleep_time = min(5, sleep_time * 1.5)
2329 6b93ec9d Iustin Pop
  if not all_connected:
2330 6b93ec9d Iustin Pop
    return (False, "Timeout in disk reconnecting")
2331 6b93ec9d Iustin Pop
  if multimaster:
2332 6b93ec9d Iustin Pop
    # change to primary mode
2333 6b93ec9d Iustin Pop
    for rd in bdevs:
2334 6b93ec9d Iustin Pop
      rd.Open()
2335 6b93ec9d Iustin Pop
  if multimaster:
2336 6b93ec9d Iustin Pop
    msg = "multi-master and primary"
2337 6b93ec9d Iustin Pop
  else:
2338 6b93ec9d Iustin Pop
    msg = "single-master"
2339 6b93ec9d Iustin Pop
  return (True, "Disks are now configured as %s" % msg)
2340 6b93ec9d Iustin Pop
2341 6b93ec9d Iustin Pop
2342 6b93ec9d Iustin Pop
def DrbdWaitSync(nodes_ip, disks):
2343 6b93ec9d Iustin Pop
  """Wait until DRBDs have synchronized.
2344 6b93ec9d Iustin Pop

2345 6b93ec9d Iustin Pop
  """
2346 6b93ec9d Iustin Pop
  status, bdevs = _FindDisks(nodes_ip, disks)
2347 6b93ec9d Iustin Pop
  if not status:
2348 6b93ec9d Iustin Pop
    return status, bdevs
2349 6b93ec9d Iustin Pop
2350 6b93ec9d Iustin Pop
  min_resync = 100
2351 6b93ec9d Iustin Pop
  alldone = True
2352 6b93ec9d Iustin Pop
  failure = False
2353 6b93ec9d Iustin Pop
  for rd in bdevs:
2354 6b93ec9d Iustin Pop
    stats = rd.GetProcStatus()
2355 6b93ec9d Iustin Pop
    if not (stats.is_connected or stats.is_in_resync):
2356 6b93ec9d Iustin Pop
      failure = True
2357 6b93ec9d Iustin Pop
      break
2358 6b93ec9d Iustin Pop
    alldone = alldone and (not stats.is_in_resync)
2359 6b93ec9d Iustin Pop
    if stats.sync_percent is not None:
2360 6b93ec9d Iustin Pop
      min_resync = min(min_resync, stats.sync_percent)
2361 6b93ec9d Iustin Pop
  return (not failure, (alldone, min_resync))
2362 6b93ec9d Iustin Pop
2363 6b93ec9d Iustin Pop
2364 a8083063 Iustin Pop
class HooksRunner(object):
2365 a8083063 Iustin Pop
  """Hook runner.
2366 a8083063 Iustin Pop

2367 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
2368 10c2650b Iustin Pop
  on the master side.
2369 a8083063 Iustin Pop

2370 a8083063 Iustin Pop
  """
2371 a8083063 Iustin Pop
  RE_MASK = re.compile("^[a-zA-Z0-9_-]+$")
2372 a8083063 Iustin Pop
2373 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
2374 a8083063 Iustin Pop
    """Constructor for hooks runner.
2375 a8083063 Iustin Pop

2376 10c2650b Iustin Pop
    @type hooks_base_dir: str or None
2377 10c2650b Iustin Pop
    @param hooks_base_dir: if not None, this overrides the
2378 10c2650b Iustin Pop
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
2379 a8083063 Iustin Pop

2380 a8083063 Iustin Pop
    """
2381 a8083063 Iustin Pop
    if hooks_base_dir is None:
2382 a8083063 Iustin Pop
      hooks_base_dir = constants.HOOKS_BASE_DIR
2383 a8083063 Iustin Pop
    self._BASE_DIR = hooks_base_dir
2384 a8083063 Iustin Pop
2385 a8083063 Iustin Pop
  @staticmethod
2386 a8083063 Iustin Pop
  def ExecHook(script, env):
2387 a8083063 Iustin Pop
    """Exec one hook script.
2388 a8083063 Iustin Pop

2389 10c2650b Iustin Pop
    @type script: str
2390 10c2650b Iustin Pop
    @param script: the full path to the script
2391 10c2650b Iustin Pop
    @type env: dict
2392 10c2650b Iustin Pop
    @param env: the environment with which to exec the script
2393 10c2650b Iustin Pop
    @rtype: tuple (success, message)
2394 10c2650b Iustin Pop
    @return: a tuple of success and message, where success
2395 10c2650b Iustin Pop
        indicates the succes of the operation, and message
2396 10c2650b Iustin Pop
        which will contain the error details in case we
2397 10c2650b Iustin Pop
        failed
2398 a8083063 Iustin Pop

2399 a8083063 Iustin Pop
    """
2400 a8083063 Iustin Pop
    # exec the process using subprocess and log the output
2401 a8083063 Iustin Pop
    fdstdin = None
2402 a8083063 Iustin Pop
    try:
2403 a8083063 Iustin Pop
      fdstdin = open("/dev/null", "r")
2404 a8083063 Iustin Pop
      child = subprocess.Popen([script], stdin=fdstdin, stdout=subprocess.PIPE,
2405 a8083063 Iustin Pop
                               stderr=subprocess.STDOUT, close_fds=True,
2406 147af04d Iustin Pop
                               shell=False, cwd="/", env=env)
2407 a8083063 Iustin Pop
      output = ""
2408 a8083063 Iustin Pop
      try:
2409 a8083063 Iustin Pop
        output = child.stdout.read(4096)
2410 a8083063 Iustin Pop
        child.stdout.close()
2411 a8083063 Iustin Pop
      except EnvironmentError, err:
2412 a8083063 Iustin Pop
        output += "Hook script error: %s" % str(err)
2413 a8083063 Iustin Pop
2414 a8083063 Iustin Pop
      while True:
2415 a8083063 Iustin Pop
        try:
2416 a8083063 Iustin Pop
          result = child.wait()
2417 a8083063 Iustin Pop
          break
2418 a8083063 Iustin Pop
        except EnvironmentError, err:
2419 a8083063 Iustin Pop
          if err.errno == errno.EINTR:
2420 a8083063 Iustin Pop
            continue
2421 a8083063 Iustin Pop
          raise
2422 a8083063 Iustin Pop
    finally:
2423 a8083063 Iustin Pop
      # try not to leak fds
2424 a8083063 Iustin Pop
      for fd in (fdstdin, ):
2425 a8083063 Iustin Pop
        if fd is not None:
2426 a8083063 Iustin Pop
          try:
2427 a8083063 Iustin Pop
            fd.close()
2428 a8083063 Iustin Pop
          except EnvironmentError, err:
2429 a8083063 Iustin Pop
            # just log the error
2430 18682bca Iustin Pop
            #logging.exception("Error while closing fd %s", fd)
2431 a8083063 Iustin Pop
            pass
2432 a8083063 Iustin Pop
2433 a8083063 Iustin Pop
    return result == 0, output
2434 a8083063 Iustin Pop
2435 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
2436 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
2437 a8083063 Iustin Pop

2438 10c2650b Iustin Pop
    @type hpath: str
2439 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
2440 10c2650b Iustin Pop
        holds the scripts
2441 10c2650b Iustin Pop
    @type phase: str
2442 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
2443 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
2444 10c2650b Iustin Pop
    @type env: dict
2445 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
2446 10c2650b Iustin Pop
    @rtype: list
2447 10c2650b Iustin Pop
    @return: list of 3-element tuples:
2448 10c2650b Iustin Pop
      - script path
2449 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
2450 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
2451 10c2650b Iustin Pop
      - output of the script
2452 10c2650b Iustin Pop

2453 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
2454 10c2650b Iustin Pop
        parameters
2455 a8083063 Iustin Pop

2456 a8083063 Iustin Pop
    """
2457 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
2458 a8083063 Iustin Pop
      suffix = "pre"
2459 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
2460 a8083063 Iustin Pop
      suffix = "post"
2461 a8083063 Iustin Pop
    else:
2462 3ecf6786 Iustin Pop
      raise errors.ProgrammerError("Unknown hooks phase: '%s'" % phase)
2463 a8083063 Iustin Pop
    rr = []
2464 a8083063 Iustin Pop
2465 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
2466 a8083063 Iustin Pop
    dir_name = "%s/%s" % (self._BASE_DIR, subdir)
2467 a8083063 Iustin Pop
    try:
2468 eedbda4b Michael Hanselmann
      dir_contents = utils.ListVisibleFiles(dir_name)
2469 a8083063 Iustin Pop
    except OSError, err:
2470 10c2650b Iustin Pop
      # FIXME: must log output in case of failures
2471 a8083063 Iustin Pop
      return rr
2472 a8083063 Iustin Pop
2473 a8083063 Iustin Pop
    # we use the standard python sort order,
2474 a8083063 Iustin Pop
    # so 00name is the recommended naming scheme
2475 a8083063 Iustin Pop
    dir_contents.sort()
2476 a8083063 Iustin Pop
    for relname in dir_contents:
2477 a8083063 Iustin Pop
      fname = os.path.join(dir_name, relname)
2478 a8083063 Iustin Pop
      if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and
2479 a8083063 Iustin Pop
          self.RE_MASK.match(relname) is not None):
2480 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
2481 a8083063 Iustin Pop
        output = ""
2482 a8083063 Iustin Pop
      else:
2483 a8083063 Iustin Pop
        result, output = self.ExecHook(fname, env)
2484 a8083063 Iustin Pop
        if not result:
2485 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
2486 a8083063 Iustin Pop
        else:
2487 a8083063 Iustin Pop
          rrval = constants.HKR_SUCCESS
2488 a8083063 Iustin Pop
      rr.append(("%s/%s" % (subdir, relname), rrval, output))
2489 a8083063 Iustin Pop
2490 a8083063 Iustin Pop
    return rr
2491 3f78eef2 Iustin Pop
2492 3f78eef2 Iustin Pop
2493 8d528b7c Iustin Pop
class IAllocatorRunner(object):
2494 8d528b7c Iustin Pop
  """IAllocator runner.
2495 8d528b7c Iustin Pop

2496 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
2497 8d528b7c Iustin Pop
  the master side.
2498 8d528b7c Iustin Pop

2499 8d528b7c Iustin Pop
  """
2500 8d528b7c Iustin Pop
  def Run(self, name, idata):
2501 8d528b7c Iustin Pop
    """Run an iallocator script.
2502 8d528b7c Iustin Pop

2503 10c2650b Iustin Pop
    @type name: str
2504 10c2650b Iustin Pop
    @param name: the iallocator script name
2505 10c2650b Iustin Pop
    @type idata: str
2506 10c2650b Iustin Pop
    @param idata: the allocator input data
2507 10c2650b Iustin Pop

2508 10c2650b Iustin Pop
    @rtype: tuple
2509 10c2650b Iustin Pop
    @return: four element tuple of:
2510 8d528b7c Iustin Pop
       - run status (one of the IARUN_ constants)
2511 8d528b7c Iustin Pop
       - stdout
2512 8d528b7c Iustin Pop
       - stderr
2513 10c2650b Iustin Pop
       - fail reason (as from L{utils.RunResult})
2514 8d528b7c Iustin Pop

2515 8d528b7c Iustin Pop
    """
2516 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
2517 8d528b7c Iustin Pop
                                  os.path.isfile)
2518 8d528b7c Iustin Pop
    if alloc_script is None:
2519 8d528b7c Iustin Pop
      return (constants.IARUN_NOTFOUND, None, None, None)
2520 8d528b7c Iustin Pop
2521 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
2522 8d528b7c Iustin Pop
    try:
2523 8d528b7c Iustin Pop
      os.write(fd, idata)
2524 8d528b7c Iustin Pop
      os.close(fd)
2525 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
2526 8d528b7c Iustin Pop
      if result.failed:
2527 8d528b7c Iustin Pop
        return (constants.IARUN_FAILURE, result.stdout, result.stderr,
2528 8d528b7c Iustin Pop
                result.fail_reason)
2529 8d528b7c Iustin Pop
    finally:
2530 8d528b7c Iustin Pop
      os.unlink(fin_name)
2531 8d528b7c Iustin Pop
2532 8d528b7c Iustin Pop
    return (constants.IARUN_SUCCESS, result.stdout, result.stderr, None)
2533 8d528b7c Iustin Pop
2534 8d528b7c Iustin Pop
2535 3f78eef2 Iustin Pop
class DevCacheManager(object):
2536 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
2537 3f78eef2 Iustin Pop

2538 3f78eef2 Iustin Pop
  """
2539 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
2540 3f78eef2 Iustin Pop
  _ROOT_DIR = constants.BDEV_CACHE_DIR
2541 3f78eef2 Iustin Pop
2542 3f78eef2 Iustin Pop
  @classmethod
2543 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
2544 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
2545 3f78eef2 Iustin Pop

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

2549 10c2650b Iustin Pop
    @type dev_path: str
2550 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
2551 10c2650b Iustin Pop
    @rtype: str
2552 10c2650b Iustin Pop
    @return: the converted path name
2553 3f78eef2 Iustin Pop

2554 3f78eef2 Iustin Pop
    """
2555 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
2556 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
2557 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
2558 3f78eef2 Iustin Pop
    fpath = "%s/bdev_%s" % (cls._ROOT_DIR, dev_path)
2559 3f78eef2 Iustin Pop
    return fpath
2560 3f78eef2 Iustin Pop
2561 3f78eef2 Iustin Pop
  @classmethod
2562 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
2563 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
2564 3f78eef2 Iustin Pop

2565 10c2650b Iustin Pop
    @type dev_path: str
2566 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
2567 10c2650b Iustin Pop
    @type owner: str
2568 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
2569 10c2650b Iustin Pop
    @type on_primary: bool
2570 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
2571 10c2650b Iustin Pop
        node nor not
2572 10c2650b Iustin Pop
    @type iv_name: str
2573 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
2574 c41eea6e Iustin Pop
        device, as in objects.Disk.iv_name
2575 10c2650b Iustin Pop

2576 10c2650b Iustin Pop
    @rtype: None
2577 10c2650b Iustin Pop

2578 3f78eef2 Iustin Pop
    """
2579 cf5a8306 Iustin Pop
    if dev_path is None:
2580 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
2581 cf5a8306 Iustin Pop
      return
2582 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
2583 3f78eef2 Iustin Pop
    if on_primary:
2584 3f78eef2 Iustin Pop
      state = "primary"
2585 3f78eef2 Iustin Pop
    else:
2586 3f78eef2 Iustin Pop
      state = "secondary"
2587 3f78eef2 Iustin Pop
    if iv_name is None:
2588 3f78eef2 Iustin Pop
      iv_name = "not_visible"
2589 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
2590 3f78eef2 Iustin Pop
    try:
2591 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
2592 3f78eef2 Iustin Pop
    except EnvironmentError, err:
2593 18682bca Iustin Pop
      logging.exception("Can't update bdev cache for %s", dev_path)
2594 3f78eef2 Iustin Pop
2595 3f78eef2 Iustin Pop
  @classmethod
2596 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
2597 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
2598 3f78eef2 Iustin Pop

2599 10c2650b Iustin Pop
    This is just a wrapper over L{utils.RemoveFile} with a converted
2600 10c2650b Iustin Pop
    path name and logging.
2601 10c2650b Iustin Pop

2602 10c2650b Iustin Pop
    @type dev_path: str
2603 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
2604 10c2650b Iustin Pop

2605 10c2650b Iustin Pop
    @rtype: None
2606 10c2650b Iustin Pop

2607 3f78eef2 Iustin Pop
    """
2608 cf5a8306 Iustin Pop
    if dev_path is None:
2609 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
2610 cf5a8306 Iustin Pop
      return
2611 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
2612 3f78eef2 Iustin Pop
    try:
2613 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
2614 3f78eef2 Iustin Pop
    except EnvironmentError, err:
2615 18682bca Iustin Pop
      logging.exception("Can't update bdev cache for %s", dev_path)