Statistics
| Branch: | Tag: | Revision:

root / lib / backend.py @ 59305197

History | View | Annotate | Download (69.6 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 12bce260 Michael Hanselmann
  assert len(data) == 2
82 12bce260 Michael Hanselmann
  (encoding, content) = data
83 12bce260 Michael Hanselmann
  if encoding == constants.RPC_ENCODING_NONE:
84 12bce260 Michael Hanselmann
    return content
85 12bce260 Michael Hanselmann
  elif encoding == constants.RPC_ENCODING_ZLIB_BASE64:
86 12bce260 Michael Hanselmann
    return zlib.decompress(base64.b64decode(content))
87 12bce260 Michael Hanselmann
  else:
88 12bce260 Michael Hanselmann
    raise AssertionError("Unknown data encoding")
89 12bce260 Michael Hanselmann
90 12bce260 Michael Hanselmann
91 76ab5558 Michael Hanselmann
def _CleanDirectory(path, exclude=[]):
92 76ab5558 Michael Hanselmann
  """Removes all regular files in a directory.
93 76ab5558 Michael Hanselmann

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

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

119 10c2650b Iustin Pop
  @rtype: None
120 24fc781f Michael Hanselmann

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

439 10c2650b Iustin Pop
  @type vg_name: str
440 10c2650b Iustin Pop
  @param vg_name: the volume group whose LVs we should list
441 10c2650b Iustin Pop
  @rtype: dict
442 10c2650b Iustin Pop
  @return:
443 10c2650b Iustin Pop
      dictionary of all partions (key) with value being a tuple of
444 10c2650b Iustin Pop
      their size (in MiB), inactive and online status::
445 10c2650b Iustin Pop

446 10c2650b Iustin Pop
        {'test1': ('20.06', True, True)}
447 10c2650b Iustin Pop

448 10c2650b Iustin Pop
      in case of errors, a string is returned with the error
449 10c2650b Iustin Pop
      details.
450 a8083063 Iustin Pop

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

480 10c2650b Iustin Pop
  @rtype: dict
481 10c2650b Iustin Pop
  @return: dictionary with keys volume name and values the
482 10c2650b Iustin Pop
      size of the volume
483 a8083063 Iustin Pop

484 a8083063 Iustin Pop
  """
485 a8083063 Iustin Pop
  return utils.ListVolumeGroups()
486 a8083063 Iustin Pop
487 a8083063 Iustin Pop
488 dcb93971 Michael Hanselmann
def NodeVolumes():
489 dcb93971 Michael Hanselmann
  """List all volumes on this node.
490 dcb93971 Michael Hanselmann

491 10c2650b Iustin Pop
  @rtype: list
492 10c2650b Iustin Pop
  @return:
493 10c2650b Iustin Pop
    A list of dictionaries, each having four keys:
494 10c2650b Iustin Pop
      - name: the logical volume name,
495 10c2650b Iustin Pop
      - size: the size of the logical volume
496 10c2650b Iustin Pop
      - dev: the physical device on which the LV lives
497 10c2650b Iustin Pop
      - vg: the volume group to which it belongs
498 10c2650b Iustin Pop

499 10c2650b Iustin Pop
    In case of errors, we return an empty list and log the
500 10c2650b Iustin Pop
    error.
501 10c2650b Iustin Pop

502 10c2650b Iustin Pop
    Note that since a logical volume can live on multiple physical
503 10c2650b Iustin Pop
    volumes, the resulting list might include a logical volume
504 10c2650b Iustin Pop
    multiple times.
505 10c2650b Iustin Pop

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

536 b1206984 Iustin Pop
  @rtype: boolean
537 b1206984 Iustin Pop
  @return: C{True} if all of them exist, C{False} otherwise
538 a8083063 Iustin Pop

539 a8083063 Iustin Pop
  """
540 a8083063 Iustin Pop
  for bridge in bridges_list:
541 a8083063 Iustin Pop
    if not utils.BridgeExists(bridge):
542 a8083063 Iustin Pop
      return False
543 a8083063 Iustin Pop
544 a8083063 Iustin Pop
  return True
545 a8083063 Iustin Pop
546 a8083063 Iustin Pop
547 e69d05fd Iustin Pop
def GetInstanceList(hypervisor_list):
548 2f8598a5 Alexander Schreiber
  """Provides a list of instances.
549 a8083063 Iustin Pop

550 e69d05fd Iustin Pop
  @type hypervisor_list: list
551 e69d05fd Iustin Pop
  @param hypervisor_list: the list of hypervisors to query information
552 e69d05fd Iustin Pop

553 e69d05fd Iustin Pop
  @rtype: list
554 e69d05fd Iustin Pop
  @return: a list of all running instances on the current node
555 10c2650b Iustin Pop
    - instance1.example.com
556 10c2650b Iustin Pop
    - instance2.example.com
557 a8083063 Iustin Pop

558 098c0958 Michael Hanselmann
  """
559 e69d05fd Iustin Pop
  results = []
560 e69d05fd Iustin Pop
  for hname in hypervisor_list:
561 e69d05fd Iustin Pop
    try:
562 e69d05fd Iustin Pop
      names = hypervisor.GetHypervisor(hname).ListInstances()
563 e69d05fd Iustin Pop
      results.extend(names)
564 e69d05fd Iustin Pop
    except errors.HypervisorError, err:
565 e69d05fd Iustin Pop
      logging.exception("Error enumerating instances for hypevisor %s", hname)
566 e69d05fd Iustin Pop
      # FIXME: should we somehow not propagate this to the master?
567 e69d05fd Iustin Pop
      raise
568 a8083063 Iustin Pop
569 e69d05fd Iustin Pop
  return results
570 a8083063 Iustin Pop
571 a8083063 Iustin Pop
572 e69d05fd Iustin Pop
def GetInstanceInfo(instance, hname):
573 2f8598a5 Alexander Schreiber
  """Gives back the informations about an instance as a dictionary.
574 a8083063 Iustin Pop

575 e69d05fd Iustin Pop
  @type instance: string
576 e69d05fd Iustin Pop
  @param instance: the instance name
577 e69d05fd Iustin Pop
  @type hname: string
578 e69d05fd Iustin Pop
  @param hname: the hypervisor type of the instance
579 a8083063 Iustin Pop

580 e69d05fd Iustin Pop
  @rtype: dict
581 e69d05fd Iustin Pop
  @return: dictionary with the following keys:
582 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
583 e69d05fd Iustin Pop
      - state: xen state of instance (string)
584 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
585 a8083063 Iustin Pop

586 098c0958 Michael Hanselmann
  """
587 a8083063 Iustin Pop
  output = {}
588 a8083063 Iustin Pop
589 e69d05fd Iustin Pop
  iinfo = hypervisor.GetHypervisor(hname).GetInstanceInfo(instance)
590 a8083063 Iustin Pop
  if iinfo is not None:
591 a8083063 Iustin Pop
    output['memory'] = iinfo[2]
592 a8083063 Iustin Pop
    output['state'] = iinfo[4]
593 a8083063 Iustin Pop
    output['time'] = iinfo[5]
594 a8083063 Iustin Pop
595 a8083063 Iustin Pop
  return output
596 a8083063 Iustin Pop
597 a8083063 Iustin Pop
598 e69d05fd Iustin Pop
def GetAllInstancesInfo(hypervisor_list):
599 a8083063 Iustin Pop
  """Gather data about all instances.
600 a8083063 Iustin Pop

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

605 e69d05fd Iustin Pop
  @type hypervisor_list: list
606 e69d05fd Iustin Pop
  @param hypervisor_list: list of hypervisors to query for instance data
607 e69d05fd Iustin Pop

608 955db481 Guido Trotter
  @rtype: dict
609 e69d05fd Iustin Pop
  @return: dictionary of instance: data, with data having the following keys:
610 e69d05fd Iustin Pop
      - memory: memory size of instance (int)
611 e69d05fd Iustin Pop
      - state: xen state of instance (string)
612 e69d05fd Iustin Pop
      - time: cpu time of instance (float)
613 10c2650b Iustin Pop
      - vcpus: the number of vcpus
614 a8083063 Iustin Pop

615 098c0958 Michael Hanselmann
  """
616 a8083063 Iustin Pop
  output = {}
617 a8083063 Iustin Pop
618 e69d05fd Iustin Pop
  for hname in hypervisor_list:
619 e69d05fd Iustin Pop
    iinfo = hypervisor.GetHypervisor(hname).GetAllInstancesInfo()
620 e69d05fd Iustin Pop
    if iinfo:
621 e69d05fd Iustin Pop
      for name, inst_id, memory, vcpus, state, times in iinfo:
622 f23b5ae8 Iustin Pop
        value = {
623 e69d05fd Iustin Pop
          'memory': memory,
624 e69d05fd Iustin Pop
          'vcpus': vcpus,
625 e69d05fd Iustin Pop
          'state': state,
626 e69d05fd Iustin Pop
          'time': times,
627 e69d05fd Iustin Pop
          }
628 f23b5ae8 Iustin Pop
        if name in output and output[name] != value:
629 f23b5ae8 Iustin Pop
          raise errors.HypervisorError("Instance %s running duplicate"
630 f23b5ae8 Iustin Pop
                                       " with different parameters" % name)
631 f23b5ae8 Iustin Pop
        output[name] = value
632 a8083063 Iustin Pop
633 a8083063 Iustin Pop
  return output
634 a8083063 Iustin Pop
635 a8083063 Iustin Pop
636 d15a9ad3 Guido Trotter
def AddOSToInstance(instance):
637 2f8598a5 Alexander Schreiber
  """Add an OS to an instance.
638 a8083063 Iustin Pop

639 d15a9ad3 Guido Trotter
  @type instance: L{objects.Instance}
640 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
641 10c2650b Iustin Pop
  @rtype: boolean
642 10c2650b Iustin Pop
  @return: the success of the operation
643 a8083063 Iustin Pop

644 a8083063 Iustin Pop
  """
645 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
646 a8083063 Iustin Pop
647 58f6e5ca Guido Trotter
  create_env = OSEnvironment(instance)
648 a8083063 Iustin Pop
649 a8083063 Iustin Pop
  logfile = "%s/add-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
650 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
651 decd5f45 Iustin Pop
652 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.create_script], env=create_env,
653 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile,)
654 decd5f45 Iustin Pop
  if result.failed:
655 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s, logfile: %s,"
656 d868edb4 Iustin Pop
                  " output: %s", result.cmd, result.fail_reason, logfile,
657 18682bca Iustin Pop
                  result.output)
658 decd5f45 Iustin Pop
    return False
659 decd5f45 Iustin Pop
660 decd5f45 Iustin Pop
  return True
661 decd5f45 Iustin Pop
662 decd5f45 Iustin Pop
663 d15a9ad3 Guido Trotter
def RunRenameInstance(instance, old_name):
664 decd5f45 Iustin Pop
  """Run the OS rename script for an instance.
665 decd5f45 Iustin Pop

666 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
667 d15a9ad3 Guido Trotter
  @param instance: Instance whose OS is to be installed
668 d15a9ad3 Guido Trotter
  @type old_name: string
669 d15a9ad3 Guido Trotter
  @param old_name: previous instance name
670 10c2650b Iustin Pop
  @rtype: boolean
671 10c2650b Iustin Pop
  @return: the success of the operation
672 decd5f45 Iustin Pop

673 decd5f45 Iustin Pop
  """
674 decd5f45 Iustin Pop
  inst_os = OSFromDisk(instance.os)
675 decd5f45 Iustin Pop
676 ff38b6c0 Guido Trotter
  rename_env = OSEnvironment(instance)
677 ff38b6c0 Guido Trotter
  rename_env['OLD_INSTANCE_NAME'] = old_name
678 decd5f45 Iustin Pop
679 decd5f45 Iustin Pop
  logfile = "%s/rename-%s-%s-%s-%d.log" % (constants.LOG_OS_DIR, instance.os,
680 decd5f45 Iustin Pop
                                           old_name,
681 decd5f45 Iustin Pop
                                           instance.name, int(time.time()))
682 a8083063 Iustin Pop
683 d868edb4 Iustin Pop
  result = utils.RunCmd([inst_os.rename_script], env=rename_env,
684 d868edb4 Iustin Pop
                        cwd=inst_os.path, output=logfile)
685 a8083063 Iustin Pop
686 a8083063 Iustin Pop
  if result.failed:
687 18682bca Iustin Pop
    logging.error("os create command '%s' returned error: %s output: %s",
688 d868edb4 Iustin Pop
                  result.cmd, result.fail_reason, result.output)
689 a8083063 Iustin Pop
    return False
690 a8083063 Iustin Pop
691 a8083063 Iustin Pop
  return True
692 a8083063 Iustin Pop
693 a8083063 Iustin Pop
694 a8083063 Iustin Pop
def _GetVGInfo(vg_name):
695 a8083063 Iustin Pop
  """Get informations about the volume group.
696 a8083063 Iustin Pop

697 10c2650b Iustin Pop
  @type vg_name: str
698 10c2650b Iustin Pop
  @param vg_name: the volume group which we query
699 10c2650b Iustin Pop
  @rtype: dict
700 10c2650b Iustin Pop
  @return:
701 10c2650b Iustin Pop
    A dictionary with the following keys:
702 10c2650b Iustin Pop
      - C{vg_size} is the total size of the volume group in MiB
703 10c2650b Iustin Pop
      - C{vg_free} is the free size of the volume group in MiB
704 10c2650b Iustin Pop
      - C{pv_count} are the number of physical disks in that VG
705 a8083063 Iustin Pop

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

709 a8083063 Iustin Pop
  """
710 f4d377e7 Iustin Pop
  retdic = dict.fromkeys(["vg_size", "vg_free", "pv_count"])
711 f4d377e7 Iustin Pop
712 a8083063 Iustin Pop
  retval = utils.RunCmd(["vgs", "-ovg_size,vg_free,pv_count", "--noheadings",
713 a8083063 Iustin Pop
                         "--nosuffix", "--units=m", "--separator=:", vg_name])
714 a8083063 Iustin Pop
715 a8083063 Iustin Pop
  if retval.failed:
716 18682bca Iustin Pop
    logging.error("volume group %s not present", vg_name)
717 f4d377e7 Iustin Pop
    return retdic
718 d87ae7d2 Iustin Pop
  valarr = retval.stdout.strip().rstrip(':').split(':')
719 f4d377e7 Iustin Pop
  if len(valarr) == 3:
720 f4d377e7 Iustin Pop
    try:
721 f4d377e7 Iustin Pop
      retdic = {
722 f4d377e7 Iustin Pop
        "vg_size": int(round(float(valarr[0]), 0)),
723 f4d377e7 Iustin Pop
        "vg_free": int(round(float(valarr[1]), 0)),
724 f4d377e7 Iustin Pop
        "pv_count": int(valarr[2]),
725 f4d377e7 Iustin Pop
        }
726 f4d377e7 Iustin Pop
    except ValueError, err:
727 18682bca Iustin Pop
      logging.exception("Fail to parse vgs output")
728 f4d377e7 Iustin Pop
  else:
729 18682bca Iustin Pop
    logging.error("vgs output has the wrong number of fields (expected"
730 18682bca Iustin Pop
                  " three): %s", str(valarr))
731 a8083063 Iustin Pop
  return retdic
732 a8083063 Iustin Pop
733 a8083063 Iustin Pop
734 a8083063 Iustin Pop
def _GatherBlockDevs(instance):
735 a8083063 Iustin Pop
  """Set up an instance's block device(s).
736 a8083063 Iustin Pop

737 a8083063 Iustin Pop
  This is run on the primary node at instance startup. The block
738 a8083063 Iustin Pop
  devices must be already assembled.
739 a8083063 Iustin Pop

740 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
741 10c2650b Iustin Pop
  @param instance: the instance whose disks we shoul assemble
742 10c2650b Iustin Pop
  @rtype: list of L{bdev.BlockDev}
743 10c2650b Iustin Pop
  @return: list of the block devices
744 10c2650b Iustin Pop

745 a8083063 Iustin Pop
  """
746 a8083063 Iustin Pop
  block_devices = []
747 a8083063 Iustin Pop
  for disk in instance.disks:
748 a8083063 Iustin Pop
    device = _RecursiveFindBD(disk)
749 a8083063 Iustin Pop
    if device is None:
750 a8083063 Iustin Pop
      raise errors.BlockDeviceError("Block device '%s' is not set up." %
751 a8083063 Iustin Pop
                                    str(disk))
752 a8083063 Iustin Pop
    device.Open()
753 a8083063 Iustin Pop
    block_devices.append((disk, device))
754 a8083063 Iustin Pop
  return block_devices
755 a8083063 Iustin Pop
756 a8083063 Iustin Pop
757 a8083063 Iustin Pop
def StartInstance(instance, extra_args):
758 a8083063 Iustin Pop
  """Start an instance.
759 a8083063 Iustin Pop

760 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
761 e69d05fd Iustin Pop
  @param instance: the instance object
762 e69d05fd Iustin Pop
  @rtype: boolean
763 e69d05fd Iustin Pop
  @return: whether the startup was successful or not
764 a8083063 Iustin Pop

765 098c0958 Michael Hanselmann
  """
766 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
767 a8083063 Iustin Pop
768 a8083063 Iustin Pop
  if instance.name in running_instances:
769 a8083063 Iustin Pop
    return True
770 a8083063 Iustin Pop
771 a8083063 Iustin Pop
  block_devices = _GatherBlockDevs(instance)
772 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
773 a8083063 Iustin Pop
774 a8083063 Iustin Pop
  try:
775 a8083063 Iustin Pop
    hyper.StartInstance(instance, block_devices, extra_args)
776 a8083063 Iustin Pop
  except errors.HypervisorError, err:
777 18682bca Iustin Pop
    logging.exception("Failed to start instance")
778 a8083063 Iustin Pop
    return False
779 a8083063 Iustin Pop
780 a8083063 Iustin Pop
  return True
781 a8083063 Iustin Pop
782 a8083063 Iustin Pop
783 a8083063 Iustin Pop
def ShutdownInstance(instance):
784 a8083063 Iustin Pop
  """Shut an instance down.
785 a8083063 Iustin Pop

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

788 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
789 e69d05fd Iustin Pop
  @param instance: the instance object
790 e69d05fd Iustin Pop
  @rtype: boolean
791 e69d05fd Iustin Pop
  @return: whether the startup was successful or not
792 a8083063 Iustin Pop

793 098c0958 Michael Hanselmann
  """
794 e69d05fd Iustin Pop
  hv_name = instance.hypervisor
795 e69d05fd Iustin Pop
  running_instances = GetInstanceList([hv_name])
796 a8083063 Iustin Pop
797 a8083063 Iustin Pop
  if instance.name not in running_instances:
798 a8083063 Iustin Pop
    return True
799 a8083063 Iustin Pop
800 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(hv_name)
801 a8083063 Iustin Pop
  try:
802 a8083063 Iustin Pop
    hyper.StopInstance(instance)
803 a8083063 Iustin Pop
  except errors.HypervisorError, err:
804 18682bca Iustin Pop
    logging.error("Failed to stop instance")
805 a8083063 Iustin Pop
    return False
806 a8083063 Iustin Pop
807 a8083063 Iustin Pop
  # test every 10secs for 2min
808 a8083063 Iustin Pop
  shutdown_ok = False
809 a8083063 Iustin Pop
810 a8083063 Iustin Pop
  time.sleep(1)
811 a8083063 Iustin Pop
  for dummy in range(11):
812 e69d05fd Iustin Pop
    if instance.name not in GetInstanceList([hv_name]):
813 a8083063 Iustin Pop
      break
814 a8083063 Iustin Pop
    time.sleep(10)
815 a8083063 Iustin Pop
  else:
816 a8083063 Iustin Pop
    # the shutdown did not succeed
817 18682bca Iustin Pop
    logging.error("shutdown of '%s' unsuccessful, using destroy", instance)
818 a8083063 Iustin Pop
819 a8083063 Iustin Pop
    try:
820 a8083063 Iustin Pop
      hyper.StopInstance(instance, force=True)
821 a8083063 Iustin Pop
    except errors.HypervisorError, err:
822 18682bca Iustin Pop
      logging.exception("Failed to stop instance")
823 a8083063 Iustin Pop
      return False
824 a8083063 Iustin Pop
825 a8083063 Iustin Pop
    time.sleep(1)
826 e69d05fd Iustin Pop
    if instance.name in GetInstanceList([hv_name]):
827 18682bca Iustin Pop
      logging.error("could not shutdown instance '%s' even by destroy",
828 18682bca Iustin Pop
                    instance.name)
829 a8083063 Iustin Pop
      return False
830 a8083063 Iustin Pop
831 a8083063 Iustin Pop
  return True
832 a8083063 Iustin Pop
833 a8083063 Iustin Pop
834 007a2f3e Alexander Schreiber
def RebootInstance(instance, reboot_type, extra_args):
835 007a2f3e Alexander Schreiber
  """Reboot an instance.
836 007a2f3e Alexander Schreiber

837 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
838 10c2650b Iustin Pop
  @param instance: the instance object to reboot
839 10c2650b Iustin Pop
  @type reboot_type: str
840 10c2650b Iustin Pop
  @param reboot_type: the type of reboot, one the following
841 10c2650b Iustin Pop
    constants:
842 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_SOFT}: only reboot the
843 10c2650b Iustin Pop
        instance OS, do not recreate the VM
844 10c2650b Iustin Pop
      - L{constants.INSTANCE_REBOOT_HARD}: tear down and
845 10c2650b Iustin Pop
        restart the VM (at the hypervisor level)
846 10c2650b Iustin Pop
      - the other reboot type (L{constants.INSTANCE_REBOOT_HARD})
847 10c2650b Iustin Pop
        is not accepted here, since that mode is handled
848 10c2650b Iustin Pop
        differently
849 10c2650b Iustin Pop
  @rtype: boolean
850 10c2650b Iustin Pop
  @return: the success of the operation
851 007a2f3e Alexander Schreiber

852 007a2f3e Alexander Schreiber
  """
853 e69d05fd Iustin Pop
  running_instances = GetInstanceList([instance.hypervisor])
854 007a2f3e Alexander Schreiber
855 007a2f3e Alexander Schreiber
  if instance.name not in running_instances:
856 18682bca Iustin Pop
    logging.error("Cannot reboot instance that is not running")
857 007a2f3e Alexander Schreiber
    return False
858 007a2f3e Alexander Schreiber
859 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
860 007a2f3e Alexander Schreiber
  if reboot_type == constants.INSTANCE_REBOOT_SOFT:
861 007a2f3e Alexander Schreiber
    try:
862 007a2f3e Alexander Schreiber
      hyper.RebootInstance(instance)
863 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
864 18682bca Iustin Pop
      logging.exception("Failed to soft reboot instance")
865 007a2f3e Alexander Schreiber
      return False
866 007a2f3e Alexander Schreiber
  elif reboot_type == constants.INSTANCE_REBOOT_HARD:
867 007a2f3e Alexander Schreiber
    try:
868 007a2f3e Alexander Schreiber
      ShutdownInstance(instance)
869 007a2f3e Alexander Schreiber
      StartInstance(instance, extra_args)
870 007a2f3e Alexander Schreiber
    except errors.HypervisorError, err:
871 18682bca Iustin Pop
      logging.exception("Failed to hard reboot instance")
872 007a2f3e Alexander Schreiber
      return False
873 007a2f3e Alexander Schreiber
  else:
874 007a2f3e Alexander Schreiber
    raise errors.ParameterError("reboot_type invalid")
875 007a2f3e Alexander Schreiber
876 007a2f3e Alexander Schreiber
  return True
877 007a2f3e Alexander Schreiber
878 007a2f3e Alexander Schreiber
879 2a10865c Iustin Pop
def MigrateInstance(instance, target, live):
880 2a10865c Iustin Pop
  """Migrates an instance to another node.
881 2a10865c Iustin Pop

882 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
883 9f0e6b37 Iustin Pop
  @param instance: the instance definition
884 9f0e6b37 Iustin Pop
  @type target: string
885 9f0e6b37 Iustin Pop
  @param target: the target node name
886 9f0e6b37 Iustin Pop
  @type live: boolean
887 9f0e6b37 Iustin Pop
  @param live: whether the migration should be done live or not (the
888 9f0e6b37 Iustin Pop
      interpretation of this parameter is left to the hypervisor)
889 9f0e6b37 Iustin Pop
  @rtype: tuple
890 9f0e6b37 Iustin Pop
  @return: a tuple of (success, msg) where:
891 9f0e6b37 Iustin Pop
      - succes is a boolean denoting the success/failure of the operation
892 9f0e6b37 Iustin Pop
      - msg is a string with details in case of failure
893 9f0e6b37 Iustin Pop

894 2a10865c Iustin Pop
  """
895 e69d05fd Iustin Pop
  hyper = hypervisor.GetHypervisor(instance.hypervisor_name)
896 2a10865c Iustin Pop
897 2a10865c Iustin Pop
  try:
898 9f0e6b37 Iustin Pop
    hyper.MigrateInstance(instance.name, target, live)
899 2a10865c Iustin Pop
  except errors.HypervisorError, err:
900 2a10865c Iustin Pop
    msg = "Failed to migrate instance: %s" % str(err)
901 18682bca Iustin Pop
    logging.error(msg)
902 2a10865c Iustin Pop
    return (False, msg)
903 2a10865c Iustin Pop
  return (True, "Migration successfull")
904 2a10865c Iustin Pop
905 2a10865c Iustin Pop
906 3f78eef2 Iustin Pop
def CreateBlockDevice(disk, size, owner, on_primary, info):
907 a8083063 Iustin Pop
  """Creates a block device for an instance.
908 a8083063 Iustin Pop

909 b1206984 Iustin Pop
  @type disk: L{objects.Disk}
910 b1206984 Iustin Pop
  @param disk: the object describing the disk we should create
911 b1206984 Iustin Pop
  @type size: int
912 b1206984 Iustin Pop
  @param size: the size of the physical underlying device, in MiB
913 b1206984 Iustin Pop
  @type owner: str
914 b1206984 Iustin Pop
  @param owner: the name of the instance for which disk is created,
915 b1206984 Iustin Pop
      used for device cache data
916 b1206984 Iustin Pop
  @type on_primary: boolean
917 b1206984 Iustin Pop
  @param on_primary:  indicates if it is the primary node or not
918 b1206984 Iustin Pop
  @type info: string
919 b1206984 Iustin Pop
  @param info: string that will be sent to the physical device
920 b1206984 Iustin Pop
      creation, used for example to set (LVM) tags on LVs
921 b1206984 Iustin Pop

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

926 a8083063 Iustin Pop
  """
927 a8083063 Iustin Pop
  clist = []
928 a8083063 Iustin Pop
  if disk.children:
929 a8083063 Iustin Pop
    for child in disk.children:
930 3f78eef2 Iustin Pop
      crdev = _RecursiveAssembleBD(child, owner, on_primary)
931 a8083063 Iustin Pop
      if on_primary or disk.AssembleOnSecondary():
932 a8083063 Iustin Pop
        # we need the children open in case the device itself has to
933 a8083063 Iustin Pop
        # be assembled
934 a8083063 Iustin Pop
        crdev.Open()
935 a8083063 Iustin Pop
      clist.append(crdev)
936 a8083063 Iustin Pop
  try:
937 a8083063 Iustin Pop
    device = bdev.FindDevice(disk.dev_type, disk.physical_id, clist)
938 a8083063 Iustin Pop
    if device is not None:
939 18682bca Iustin Pop
      logging.info("removing existing device %s", disk)
940 a8083063 Iustin Pop
      device.Remove()
941 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
942 a8083063 Iustin Pop
    pass
943 a8083063 Iustin Pop
944 a8083063 Iustin Pop
  device = bdev.Create(disk.dev_type, disk.physical_id,
945 a8083063 Iustin Pop
                       clist, size)
946 a8083063 Iustin Pop
  if device is None:
947 a8083063 Iustin Pop
    raise ValueError("Can't create child device for %s, %s" %
948 a8083063 Iustin Pop
                     (disk, size))
949 a8083063 Iustin Pop
  if on_primary or disk.AssembleOnSecondary():
950 cf5a8306 Iustin Pop
    if not device.Assemble():
951 20a0c9ef Guido Trotter
      errorstring = "Can't assemble device after creation"
952 18682bca Iustin Pop
      logging.error(errorstring)
953 20a0c9ef Guido Trotter
      raise errors.BlockDeviceError("%s, very unusual event - check the node"
954 20a0c9ef Guido Trotter
                                    " daemon logs" % errorstring)
955 e31c43f7 Michael Hanselmann
    device.SetSyncSpeed(constants.SYNC_SPEED)
956 a8083063 Iustin Pop
    if on_primary or disk.OpenOnSecondary():
957 a8083063 Iustin Pop
      device.Open(force=True)
958 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(device.dev_path, owner,
959 3f78eef2 Iustin Pop
                                on_primary, disk.iv_name)
960 a0c3fea1 Michael Hanselmann
961 a0c3fea1 Michael Hanselmann
  device.SetInfo(info)
962 a0c3fea1 Michael Hanselmann
963 a8083063 Iustin Pop
  physical_id = device.unique_id
964 a8083063 Iustin Pop
  return physical_id
965 a8083063 Iustin Pop
966 a8083063 Iustin Pop
967 a8083063 Iustin Pop
def RemoveBlockDevice(disk):
968 a8083063 Iustin Pop
  """Remove a block device.
969 a8083063 Iustin Pop

970 10c2650b Iustin Pop
  @note: This is intended to be called recursively.
971 10c2650b Iustin Pop

972 10c2650b Iustin Pop
  @type disk: L{objects.disk}
973 10c2650b Iustin Pop
  @param disk: the disk object we should remove
974 10c2650b Iustin Pop
  @rtype: boolean
975 10c2650b Iustin Pop
  @return: the success of the operation
976 a8083063 Iustin Pop

977 a8083063 Iustin Pop
  """
978 a8083063 Iustin Pop
  try:
979 a8083063 Iustin Pop
    # since we are removing the device, allow a partial match
980 a8083063 Iustin Pop
    # this allows removal of broken mirrors
981 a8083063 Iustin Pop
    rdev = _RecursiveFindBD(disk, allow_partial=True)
982 a8083063 Iustin Pop
  except errors.BlockDeviceError, err:
983 a8083063 Iustin Pop
    # probably can't attach
984 18682bca Iustin Pop
    logging.info("Can't attach to device %s in remove", disk)
985 a8083063 Iustin Pop
    rdev = None
986 a8083063 Iustin Pop
  if rdev is not None:
987 3f78eef2 Iustin Pop
    r_path = rdev.dev_path
988 a8083063 Iustin Pop
    result = rdev.Remove()
989 3f78eef2 Iustin Pop
    if result:
990 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
991 a8083063 Iustin Pop
  else:
992 a8083063 Iustin Pop
    result = True
993 a8083063 Iustin Pop
  if disk.children:
994 a8083063 Iustin Pop
    for child in disk.children:
995 a8083063 Iustin Pop
      result = result and RemoveBlockDevice(child)
996 a8083063 Iustin Pop
  return result
997 a8083063 Iustin Pop
998 a8083063 Iustin Pop
999 3f78eef2 Iustin Pop
def _RecursiveAssembleBD(disk, owner, as_primary):
1000 a8083063 Iustin Pop
  """Activate a block device for an instance.
1001 a8083063 Iustin Pop

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

1004 10c2650b Iustin Pop
  @note: this function is called recursively.
1005 a8083063 Iustin Pop

1006 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1007 10c2650b Iustin Pop
  @param disk: the disk we try to assemble
1008 10c2650b Iustin Pop
  @type owner: str
1009 10c2650b Iustin Pop
  @param owner: the name of the instance which owns the disk
1010 10c2650b Iustin Pop
  @type as_primary: boolean
1011 10c2650b Iustin Pop
  @param as_primary: if we should make the block device
1012 10c2650b Iustin Pop
      read/write
1013 a8083063 Iustin Pop

1014 10c2650b Iustin Pop
  @return: the assembled device or None (in case no device
1015 10c2650b Iustin Pop
      was assembled)
1016 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: in case there is an error
1017 10c2650b Iustin Pop
      during the activation of the children or the device
1018 10c2650b Iustin Pop
      itself
1019 a8083063 Iustin Pop

1020 a8083063 Iustin Pop
  """
1021 a8083063 Iustin Pop
  children = []
1022 a8083063 Iustin Pop
  if disk.children:
1023 fc1dc9d7 Iustin Pop
    mcn = disk.ChildrenNeeded()
1024 fc1dc9d7 Iustin Pop
    if mcn == -1:
1025 fc1dc9d7 Iustin Pop
      mcn = 0 # max number of Nones allowed
1026 fc1dc9d7 Iustin Pop
    else:
1027 fc1dc9d7 Iustin Pop
      mcn = len(disk.children) - mcn # max number of Nones
1028 a8083063 Iustin Pop
    for chld_disk in disk.children:
1029 fc1dc9d7 Iustin Pop
      try:
1030 fc1dc9d7 Iustin Pop
        cdev = _RecursiveAssembleBD(chld_disk, owner, as_primary)
1031 fc1dc9d7 Iustin Pop
      except errors.BlockDeviceError, err:
1032 7803d4d3 Iustin Pop
        if children.count(None) >= mcn:
1033 fc1dc9d7 Iustin Pop
          raise
1034 fc1dc9d7 Iustin Pop
        cdev = None
1035 18682bca Iustin Pop
        logging.debug("Error in child activation: %s", str(err))
1036 fc1dc9d7 Iustin Pop
      children.append(cdev)
1037 a8083063 Iustin Pop
1038 a8083063 Iustin Pop
  if as_primary or disk.AssembleOnSecondary():
1039 a8083063 Iustin Pop
    r_dev = bdev.AttachOrAssemble(disk.dev_type, disk.physical_id, children)
1040 e31c43f7 Michael Hanselmann
    r_dev.SetSyncSpeed(constants.SYNC_SPEED)
1041 a8083063 Iustin Pop
    result = r_dev
1042 a8083063 Iustin Pop
    if as_primary or disk.OpenOnSecondary():
1043 a8083063 Iustin Pop
      r_dev.Open()
1044 3f78eef2 Iustin Pop
    DevCacheManager.UpdateCache(r_dev.dev_path, owner,
1045 3f78eef2 Iustin Pop
                                as_primary, disk.iv_name)
1046 3f78eef2 Iustin Pop
1047 a8083063 Iustin Pop
  else:
1048 a8083063 Iustin Pop
    result = True
1049 a8083063 Iustin Pop
  return result
1050 a8083063 Iustin Pop
1051 a8083063 Iustin Pop
1052 3f78eef2 Iustin Pop
def AssembleBlockDevice(disk, owner, as_primary):
1053 a8083063 Iustin Pop
  """Activate a block device for an instance.
1054 a8083063 Iustin Pop

1055 a8083063 Iustin Pop
  This is a wrapper over _RecursiveAssembleBD.
1056 a8083063 Iustin Pop

1057 b1206984 Iustin Pop
  @rtype: str or boolean
1058 b1206984 Iustin Pop
  @return: a C{/dev/...} path for primary nodes, and
1059 b1206984 Iustin Pop
      C{True} for secondary nodes
1060 a8083063 Iustin Pop

1061 a8083063 Iustin Pop
  """
1062 3f78eef2 Iustin Pop
  result = _RecursiveAssembleBD(disk, owner, as_primary)
1063 a8083063 Iustin Pop
  if isinstance(result, bdev.BlockDev):
1064 a8083063 Iustin Pop
    result = result.dev_path
1065 a8083063 Iustin Pop
  return result
1066 a8083063 Iustin Pop
1067 a8083063 Iustin Pop
1068 a8083063 Iustin Pop
def ShutdownBlockDevice(disk):
1069 a8083063 Iustin Pop
  """Shut down a block device.
1070 a8083063 Iustin Pop

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

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

1078 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1079 10c2650b Iustin Pop
  @param disk: the description of the disk we should
1080 10c2650b Iustin Pop
      shutdown
1081 10c2650b Iustin Pop
  @rtype: boolean
1082 10c2650b Iustin Pop
  @return: the success of the operation
1083 10c2650b Iustin Pop

1084 a8083063 Iustin Pop
  """
1085 a8083063 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1086 a8083063 Iustin Pop
  if r_dev is not None:
1087 3f78eef2 Iustin Pop
    r_path = r_dev.dev_path
1088 a8083063 Iustin Pop
    result = r_dev.Shutdown()
1089 3f78eef2 Iustin Pop
    if result:
1090 3f78eef2 Iustin Pop
      DevCacheManager.RemoveCache(r_path)
1091 a8083063 Iustin Pop
  else:
1092 a8083063 Iustin Pop
    result = True
1093 a8083063 Iustin Pop
  if disk.children:
1094 a8083063 Iustin Pop
    for child in disk.children:
1095 a8083063 Iustin Pop
      result = result and ShutdownBlockDevice(child)
1096 a8083063 Iustin Pop
  return result
1097 a8083063 Iustin Pop
1098 a8083063 Iustin Pop
1099 153d9724 Iustin Pop
def MirrorAddChildren(parent_cdev, new_cdevs):
1100 153d9724 Iustin Pop
  """Extend a mirrored block device.
1101 a8083063 Iustin Pop

1102 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1103 10c2650b Iustin Pop
  @param parent_cdev: the disk to which we should add children
1104 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1105 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should add
1106 10c2650b Iustin Pop
  @rtype: boolean
1107 10c2650b Iustin Pop
  @return: the success of the operation
1108 10c2650b Iustin Pop

1109 a8083063 Iustin Pop
  """
1110 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev, allow_partial=True)
1111 153d9724 Iustin Pop
  if parent_bdev is None:
1112 18682bca Iustin Pop
    logging.error("Can't find parent device")
1113 a8083063 Iustin Pop
    return False
1114 153d9724 Iustin Pop
  new_bdevs = [_RecursiveFindBD(disk) for disk in new_cdevs]
1115 153d9724 Iustin Pop
  if new_bdevs.count(None) > 0:
1116 18682bca Iustin Pop
    logging.error("Can't find new device(s) to add: %s:%s",
1117 18682bca Iustin Pop
                  new_bdevs, new_cdevs)
1118 a8083063 Iustin Pop
    return False
1119 153d9724 Iustin Pop
  parent_bdev.AddChildren(new_bdevs)
1120 a8083063 Iustin Pop
  return True
1121 a8083063 Iustin Pop
1122 a8083063 Iustin Pop
1123 153d9724 Iustin Pop
def MirrorRemoveChildren(parent_cdev, new_cdevs):
1124 153d9724 Iustin Pop
  """Shrink a mirrored block device.
1125 a8083063 Iustin Pop

1126 10c2650b Iustin Pop
  @type parent_cdev: L{objects.Disk}
1127 10c2650b Iustin Pop
  @param parent_cdev: the disk from which we should remove children
1128 10c2650b Iustin Pop
  @type new_cdevs: list of L{objects.Disk}
1129 10c2650b Iustin Pop
  @param new_cdevs: the list of children which we should remove
1130 10c2650b Iustin Pop
  @rtype: boolean
1131 10c2650b Iustin Pop
  @return: the success of the operation
1132 10c2650b Iustin Pop

1133 a8083063 Iustin Pop
  """
1134 153d9724 Iustin Pop
  parent_bdev = _RecursiveFindBD(parent_cdev)
1135 153d9724 Iustin Pop
  if parent_bdev is None:
1136 18682bca Iustin Pop
    logging.error("Can't find parent in remove children: %s", parent_cdev)
1137 a8083063 Iustin Pop
    return False
1138 e739bd57 Iustin Pop
  devs = []
1139 e739bd57 Iustin Pop
  for disk in new_cdevs:
1140 e739bd57 Iustin Pop
    rpath = disk.StaticDevPath()
1141 e739bd57 Iustin Pop
    if rpath is None:
1142 e739bd57 Iustin Pop
      bd = _RecursiveFindBD(disk)
1143 e739bd57 Iustin Pop
      if bd is None:
1144 18682bca Iustin Pop
        logging.error("Can't find dynamic device %s while removing children",
1145 18682bca Iustin Pop
                      disk)
1146 e739bd57 Iustin Pop
        return False
1147 e739bd57 Iustin Pop
      else:
1148 e739bd57 Iustin Pop
        devs.append(bd.dev_path)
1149 e739bd57 Iustin Pop
    else:
1150 e739bd57 Iustin Pop
      devs.append(rpath)
1151 e739bd57 Iustin Pop
  parent_bdev.RemoveChildren(devs)
1152 a8083063 Iustin Pop
  return True
1153 a8083063 Iustin Pop
1154 a8083063 Iustin Pop
1155 a8083063 Iustin Pop
def GetMirrorStatus(disks):
1156 a8083063 Iustin Pop
  """Get the mirroring status of a list of devices.
1157 a8083063 Iustin Pop

1158 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
1159 10c2650b Iustin Pop
  @param disks: the list of disks which we should query
1160 10c2650b Iustin Pop
  @rtype: disk
1161 10c2650b Iustin Pop
  @return:
1162 10c2650b Iustin Pop
      a list of (mirror_done, estimated_time) tuples, which
1163 10c2650b Iustin Pop
      are the result of L{bdev.BlockDevice.CombinedSyncStatus}
1164 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if any of the disks cannot be
1165 10c2650b Iustin Pop
      found
1166 a8083063 Iustin Pop

1167 a8083063 Iustin Pop
  """
1168 a8083063 Iustin Pop
  stats = []
1169 a8083063 Iustin Pop
  for dsk in disks:
1170 a8083063 Iustin Pop
    rbd = _RecursiveFindBD(dsk)
1171 a8083063 Iustin Pop
    if rbd is None:
1172 3ecf6786 Iustin Pop
      raise errors.BlockDeviceError("Can't find device %s" % str(dsk))
1173 a8083063 Iustin Pop
    stats.append(rbd.CombinedSyncStatus())
1174 a8083063 Iustin Pop
  return stats
1175 a8083063 Iustin Pop
1176 a8083063 Iustin Pop
1177 a8083063 Iustin Pop
def _RecursiveFindBD(disk, allow_partial=False):
1178 a8083063 Iustin Pop
  """Check if a device is activated.
1179 a8083063 Iustin Pop

1180 a8083063 Iustin Pop
  If so, return informations about the real device.
1181 a8083063 Iustin Pop

1182 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1183 10c2650b Iustin Pop
  @param disk: the disk object we need to find
1184 10c2650b Iustin Pop
  @type allow_partial: boolean
1185 10c2650b Iustin Pop
  @param allow_partial: if true, don't abort the find if a
1186 10c2650b Iustin Pop
      child of the device can't be found; this is intended
1187 10c2650b Iustin Pop
      to be used when repairing mirrors
1188 a8083063 Iustin Pop

1189 10c2650b Iustin Pop
  @return: None if the device can't be found,
1190 10c2650b Iustin Pop
      otherwise the device instance
1191 a8083063 Iustin Pop

1192 a8083063 Iustin Pop
  """
1193 a8083063 Iustin Pop
  children = []
1194 a8083063 Iustin Pop
  if disk.children:
1195 a8083063 Iustin Pop
    for chdisk in disk.children:
1196 a8083063 Iustin Pop
      children.append(_RecursiveFindBD(chdisk))
1197 a8083063 Iustin Pop
1198 a8083063 Iustin Pop
  return bdev.FindDevice(disk.dev_type, disk.physical_id, children)
1199 a8083063 Iustin Pop
1200 a8083063 Iustin Pop
1201 a8083063 Iustin Pop
def FindBlockDevice(disk):
1202 a8083063 Iustin Pop
  """Check if a device is activated.
1203 a8083063 Iustin Pop

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

1206 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1207 10c2650b Iustin Pop
  @param disk: the disk to find
1208 10c2650b Iustin Pop
  @rtype: None or tuple
1209 10c2650b Iustin Pop
  @return: None if the disk cannot be found, otherwise a
1210 10c2650b Iustin Pop
      tuple (device_path, major, minor, sync_percent,
1211 10c2650b Iustin Pop
      estimated_time, is_degraded)
1212 a8083063 Iustin Pop

1213 a8083063 Iustin Pop
  """
1214 a8083063 Iustin Pop
  rbd = _RecursiveFindBD(disk)
1215 a8083063 Iustin Pop
  if rbd is None:
1216 a8083063 Iustin Pop
    return rbd
1217 0834c866 Iustin Pop
  return (rbd.dev_path, rbd.major, rbd.minor) + rbd.GetSyncStatus()
1218 a8083063 Iustin Pop
1219 a8083063 Iustin Pop
1220 a8083063 Iustin Pop
def UploadFile(file_name, data, mode, uid, gid, atime, mtime):
1221 a8083063 Iustin Pop
  """Write a file to the filesystem.
1222 a8083063 Iustin Pop

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

1226 10c2650b Iustin Pop
  @type file_name: str
1227 10c2650b Iustin Pop
  @param file_name: the target file name
1228 10c2650b Iustin Pop
  @type data: str
1229 10c2650b Iustin Pop
  @param data: the new contents of the file
1230 10c2650b Iustin Pop
  @type mode: int
1231 10c2650b Iustin Pop
  @param mode: the mode to give the file (can be None)
1232 10c2650b Iustin Pop
  @type uid: int
1233 10c2650b Iustin Pop
  @param uid: the owner of the file (can be -1 for default)
1234 10c2650b Iustin Pop
  @type gid: int
1235 10c2650b Iustin Pop
  @param gid: the group of the file (can be -1 for default)
1236 10c2650b Iustin Pop
  @type atime: float
1237 10c2650b Iustin Pop
  @param atime: the atime to set on the file (can be None)
1238 10c2650b Iustin Pop
  @type mtime: float
1239 10c2650b Iustin Pop
  @param mtime: the mtime to set on the file (can be None)
1240 10c2650b Iustin Pop
  @rtype: boolean
1241 10c2650b Iustin Pop
  @return: the success of the operation; errors are logged
1242 10c2650b Iustin Pop
      in the node daemon log
1243 10c2650b Iustin Pop

1244 a8083063 Iustin Pop
  """
1245 a8083063 Iustin Pop
  if not os.path.isabs(file_name):
1246 18682bca Iustin Pop
    logging.error("Filename passed to UploadFile is not absolute: '%s'",
1247 18682bca Iustin Pop
                  file_name)
1248 a8083063 Iustin Pop
    return False
1249 a8083063 Iustin Pop
1250 97628462 Iustin Pop
  allowed_files = [
1251 97628462 Iustin Pop
    constants.CLUSTER_CONF_FILE,
1252 97628462 Iustin Pop
    constants.ETC_HOSTS,
1253 97628462 Iustin Pop
    constants.SSH_KNOWN_HOSTS_FILE,
1254 90fae627 Guido Trotter
    constants.VNC_PASSWORD_FILE,
1255 97628462 Iustin Pop
    ]
1256 afee8008 Michael Hanselmann
1257 553f1c1d Michael Hanselmann
  if file_name not in allowed_files:
1258 18682bca Iustin Pop
    logging.error("Filename passed to UploadFile not in allowed"
1259 18682bca Iustin Pop
                 " upload targets: '%s'", file_name)
1260 a8083063 Iustin Pop
    return False
1261 a8083063 Iustin Pop
1262 12bce260 Michael Hanselmann
  raw_data = _Decompress(data)
1263 12bce260 Michael Hanselmann
1264 12bce260 Michael Hanselmann
  utils.WriteFile(file_name, data=raw_data, mode=mode, uid=uid, gid=gid,
1265 41a57aab Michael Hanselmann
                  atime=atime, mtime=mtime)
1266 a8083063 Iustin Pop
  return True
1267 a8083063 Iustin Pop
1268 386b57af Iustin Pop
1269 03d1dba2 Michael Hanselmann
def WriteSsconfFiles(values):
1270 89b14f05 Iustin Pop
  """Update all ssconf files.
1271 89b14f05 Iustin Pop

1272 89b14f05 Iustin Pop
  Wrapper around the SimpleStore.WriteFiles.
1273 89b14f05 Iustin Pop

1274 89b14f05 Iustin Pop
  """
1275 89b14f05 Iustin Pop
  ssconf.SimpleStore().WriteFiles(values)
1276 6ddc95ec Michael Hanselmann
1277 6ddc95ec Michael Hanselmann
1278 a8083063 Iustin Pop
def _ErrnoOrStr(err):
1279 a8083063 Iustin Pop
  """Format an EnvironmentError exception.
1280 a8083063 Iustin Pop

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

1285 10c2650b Iustin Pop
  @type err: L{EnvironmentError}
1286 10c2650b Iustin Pop
  @param err: the exception to format
1287 a8083063 Iustin Pop

1288 a8083063 Iustin Pop
  """
1289 a8083063 Iustin Pop
  if hasattr(err, 'errno'):
1290 a8083063 Iustin Pop
    detail = errno.errorcode[err.errno]
1291 a8083063 Iustin Pop
  else:
1292 a8083063 Iustin Pop
    detail = str(err)
1293 a8083063 Iustin Pop
  return detail
1294 a8083063 Iustin Pop
1295 5d0fe286 Iustin Pop
1296 c26dabd7 Guido Trotter
def _OSOndiskVersion(name, os_dir):
1297 2f8598a5 Alexander Schreiber
  """Compute and return the API version of a given OS.
1298 a8083063 Iustin Pop

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

1302 10c2650b Iustin Pop
  @type name: str
1303 10c2650b Iustin Pop
  @param name: the OS name we should look for
1304 10c2650b Iustin Pop
  @type os_dir: str
1305 10c2650b Iustin Pop
  @param os_dir: the directory inwhich we should look for the OS
1306 10c2650b Iustin Pop
  @rtype: int or None
1307 10c2650b Iustin Pop
  @return:
1308 10c2650b Iustin Pop
      Either an integer denoting the version or None in the
1309 10c2650b Iustin Pop
      case when this is not a valid OS name.
1310 10c2650b Iustin Pop
  @raise errors.InvalidOS: if the OS cannot be found
1311 a8083063 Iustin Pop

1312 a8083063 Iustin Pop
  """
1313 a8083063 Iustin Pop
  api_file = os.path.sep.join([os_dir, "ganeti_api_version"])
1314 a8083063 Iustin Pop
1315 a8083063 Iustin Pop
  try:
1316 a8083063 Iustin Pop
    st = os.stat(api_file)
1317 a8083063 Iustin Pop
  except EnvironmentError, err:
1318 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "'ganeti_api_version' file not"
1319 3ecf6786 Iustin Pop
                           " found (%s)" % _ErrnoOrStr(err))
1320 a8083063 Iustin Pop
1321 a8083063 Iustin Pop
  if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1322 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "'ganeti_api_version' file is not"
1323 3ecf6786 Iustin Pop
                           " a regular file")
1324 a8083063 Iustin Pop
1325 a8083063 Iustin Pop
  try:
1326 a8083063 Iustin Pop
    f = open(api_file)
1327 a8083063 Iustin Pop
    try:
1328 082a7f91 Guido Trotter
      api_versions = f.readlines()
1329 a8083063 Iustin Pop
    finally:
1330 a8083063 Iustin Pop
      f.close()
1331 a8083063 Iustin Pop
  except EnvironmentError, err:
1332 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "error while reading the"
1333 3ecf6786 Iustin Pop
                           " API version (%s)" % _ErrnoOrStr(err))
1334 a8083063 Iustin Pop
1335 082a7f91 Guido Trotter
  api_versions = [version.strip() for version in api_versions]
1336 a8083063 Iustin Pop
  try:
1337 082a7f91 Guido Trotter
    api_versions = [int(version) for version in api_versions]
1338 a8083063 Iustin Pop
  except (TypeError, ValueError), err:
1339 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir,
1340 305a7297 Guido Trotter
                           "API version is not integer (%s)" % str(err))
1341 a8083063 Iustin Pop
1342 082a7f91 Guido Trotter
  return api_versions
1343 a8083063 Iustin Pop
1344 386b57af Iustin Pop
1345 7c3d51d4 Guido Trotter
def DiagnoseOS(top_dirs=None):
1346 a8083063 Iustin Pop
  """Compute the validity for all OSes.
1347 a8083063 Iustin Pop

1348 10c2650b Iustin Pop
  @type top_dirs: list
1349 10c2650b Iustin Pop
  @param top_dirs: the list of directories in which to
1350 10c2650b Iustin Pop
      search (if not given defaults to
1351 10c2650b Iustin Pop
      L{constants.OS_SEARCH_PATH})
1352 10c2650b Iustin Pop
  @rtype: list of L{objects.OS}
1353 10c2650b Iustin Pop
  @return: an OS object for each name in all the given
1354 10c2650b Iustin Pop
      directories
1355 a8083063 Iustin Pop

1356 a8083063 Iustin Pop
  """
1357 7c3d51d4 Guido Trotter
  if top_dirs is None:
1358 7c3d51d4 Guido Trotter
    top_dirs = constants.OS_SEARCH_PATH
1359 a8083063 Iustin Pop
1360 a8083063 Iustin Pop
  result = []
1361 65fe4693 Iustin Pop
  for dir_name in top_dirs:
1362 65fe4693 Iustin Pop
    if os.path.isdir(dir_name):
1363 7c3d51d4 Guido Trotter
      try:
1364 65fe4693 Iustin Pop
        f_names = utils.ListVisibleFiles(dir_name)
1365 7c3d51d4 Guido Trotter
      except EnvironmentError, err:
1366 18682bca Iustin Pop
        logging.exception("Can't list the OS directory %s", dir_name)
1367 7c3d51d4 Guido Trotter
        break
1368 7c3d51d4 Guido Trotter
      for name in f_names:
1369 7c3d51d4 Guido Trotter
        try:
1370 65fe4693 Iustin Pop
          os_inst = OSFromDisk(name, base_dir=dir_name)
1371 7c3d51d4 Guido Trotter
          result.append(os_inst)
1372 7c3d51d4 Guido Trotter
        except errors.InvalidOS, err:
1373 8fa42c7c Guido Trotter
          result.append(objects.OS.FromInvalidOS(err))
1374 a8083063 Iustin Pop
1375 a8083063 Iustin Pop
  return result
1376 a8083063 Iustin Pop
1377 a8083063 Iustin Pop
1378 56bcd3f4 Guido Trotter
def OSFromDisk(name, base_dir=None):
1379 a8083063 Iustin Pop
  """Create an OS instance from disk.
1380 a8083063 Iustin Pop

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

1385 8ee4dc80 Guido Trotter
  @type base_dir: string
1386 8ee4dc80 Guido Trotter
  @keyword base_dir: Base directory containing OS installations.
1387 8ee4dc80 Guido Trotter
                     Defaults to a search in all the OS_SEARCH_PATH dirs.
1388 10c2650b Iustin Pop
  @rtype: L{objects.OS}
1389 10c2650b Iustin Pop
  @return: the OS instance if we find a valid one
1390 10c2650b Iustin Pop
  @raise errors.InvalidOS: if we don't find a valid OS
1391 7c3d51d4 Guido Trotter

1392 a8083063 Iustin Pop
  """
1393 56bcd3f4 Guido Trotter
  if base_dir is None:
1394 57c177af Iustin Pop
    os_dir = utils.FindFile(name, constants.OS_SEARCH_PATH, os.path.isdir)
1395 c34c0cfd Iustin Pop
    if os_dir is None:
1396 c34c0cfd Iustin Pop
      raise errors.InvalidOS(name, None, "OS dir not found in search path")
1397 c34c0cfd Iustin Pop
  else:
1398 c34c0cfd Iustin Pop
    os_dir = os.path.sep.join([base_dir, name])
1399 a8083063 Iustin Pop
1400 082a7f91 Guido Trotter
  api_versions = _OSOndiskVersion(name, os_dir)
1401 a8083063 Iustin Pop
1402 082a7f91 Guido Trotter
  if constants.OS_API_VERSION not in api_versions:
1403 305a7297 Guido Trotter
    raise errors.InvalidOS(name, os_dir, "API version mismatch"
1404 305a7297 Guido Trotter
                           " (found %s want %s)"
1405 082a7f91 Guido Trotter
                           % (api_versions, constants.OS_API_VERSION))
1406 a8083063 Iustin Pop
1407 a8083063 Iustin Pop
  # OS Scripts dictionary, we will populate it with the actual script names
1408 62dbbe7e Guido Trotter
  os_scripts = dict.fromkeys(constants.OS_SCRIPTS)
1409 a8083063 Iustin Pop
1410 a8083063 Iustin Pop
  for script in os_scripts:
1411 a8083063 Iustin Pop
    os_scripts[script] = os.path.sep.join([os_dir, script])
1412 a8083063 Iustin Pop
1413 a8083063 Iustin Pop
    try:
1414 a8083063 Iustin Pop
      st = os.stat(os_scripts[script])
1415 a8083063 Iustin Pop
    except EnvironmentError, err:
1416 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' script missing (%s)" %
1417 3ecf6786 Iustin Pop
                             (script, _ErrnoOrStr(err)))
1418 a8083063 Iustin Pop
1419 a8083063 Iustin Pop
    if stat.S_IMODE(st.st_mode) & stat.S_IXUSR != stat.S_IXUSR:
1420 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' script not executable" %
1421 305a7297 Guido Trotter
                             script)
1422 a8083063 Iustin Pop
1423 a8083063 Iustin Pop
    if not stat.S_ISREG(stat.S_IFMT(st.st_mode)):
1424 305a7297 Guido Trotter
      raise errors.InvalidOS(name, os_dir, "'%s' is not a regular file" %
1425 305a7297 Guido Trotter
                             script)
1426 a8083063 Iustin Pop
1427 a8083063 Iustin Pop
1428 8fa42c7c Guido Trotter
  return objects.OS(name=name, path=os_dir, status=constants.OS_VALID_STATUS,
1429 62dbbe7e Guido Trotter
                    create_script=os_scripts[constants.OS_SCRIPT_CREATE],
1430 62dbbe7e Guido Trotter
                    export_script=os_scripts[constants.OS_SCRIPT_EXPORT],
1431 62dbbe7e Guido Trotter
                    import_script=os_scripts[constants.OS_SCRIPT_IMPORT],
1432 62dbbe7e Guido Trotter
                    rename_script=os_scripts[constants.OS_SCRIPT_RENAME],
1433 082a7f91 Guido Trotter
                    api_versions=api_versions)
1434 a8083063 Iustin Pop
1435 2266edb2 Guido Trotter
def OSEnvironment(instance, debug=0):
1436 2266edb2 Guido Trotter
  """Calculate the environment for an os script.
1437 2266edb2 Guido Trotter

1438 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1439 2266edb2 Guido Trotter
  @param instance: target instance for the os script run
1440 2266edb2 Guido Trotter
  @type debug: integer
1441 10c2650b Iustin Pop
  @param debug: debug level (0 or 1, for OS Api 10)
1442 2266edb2 Guido Trotter
  @rtype: dict
1443 2266edb2 Guido Trotter
  @return: dict of environment variables
1444 10c2650b Iustin Pop
  @raise errors.BlockDeviceError: if the block device
1445 10c2650b Iustin Pop
      cannot be found
1446 2266edb2 Guido Trotter

1447 2266edb2 Guido Trotter
  """
1448 2266edb2 Guido Trotter
  result = {}
1449 2266edb2 Guido Trotter
  result['OS_API_VERSION'] = '%d' % constants.OS_API_VERSION
1450 2266edb2 Guido Trotter
  result['INSTANCE_NAME'] = instance.name
1451 2266edb2 Guido Trotter
  result['HYPERVISOR'] = instance.hypervisor
1452 2266edb2 Guido Trotter
  result['DISK_COUNT'] = '%d' % len(instance.disks)
1453 2266edb2 Guido Trotter
  result['NIC_COUNT'] = '%d' % len(instance.nics)
1454 2266edb2 Guido Trotter
  result['DEBUG_LEVEL'] = '%d' % debug
1455 2266edb2 Guido Trotter
  for idx, disk in enumerate(instance.disks):
1456 2266edb2 Guido Trotter
    real_disk = _RecursiveFindBD(disk)
1457 2266edb2 Guido Trotter
    if real_disk is None:
1458 2266edb2 Guido Trotter
      raise errors.BlockDeviceError("Block device '%s' is not set up" %
1459 2266edb2 Guido Trotter
                                    str(disk))
1460 2266edb2 Guido Trotter
    real_disk.Open()
1461 2266edb2 Guido Trotter
    result['DISK_%d_PATH' % idx] = real_disk.dev_path
1462 2266edb2 Guido Trotter
    # FIXME: When disks will have read-only mode, populate this
1463 2266edb2 Guido Trotter
    result['DISK_%d_ACCESS' % idx] = 'W'
1464 2266edb2 Guido Trotter
    if constants.HV_DISK_TYPE in instance.hvparams:
1465 2266edb2 Guido Trotter
      result['DISK_%d_FRONTEND_TYPE' % idx] = \
1466 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_DISK_TYPE]
1467 2266edb2 Guido Trotter
    if disk.dev_type in constants.LDS_BLOCK:
1468 2266edb2 Guido Trotter
      result['DISK_%d_BACKEND_TYPE' % idx] = 'block'
1469 2266edb2 Guido Trotter
    elif disk.dev_type == constants.LD_FILE:
1470 2266edb2 Guido Trotter
      result['DISK_%d_BACKEND_TYPE' % idx] = \
1471 2266edb2 Guido Trotter
        'file:%s' % disk.physical_id[0]
1472 2266edb2 Guido Trotter
  for idx, nic in enumerate(instance.nics):
1473 2266edb2 Guido Trotter
    result['NIC_%d_MAC' % idx] = nic.mac
1474 2266edb2 Guido Trotter
    if nic.ip:
1475 2266edb2 Guido Trotter
      result['NIC_%d_IP' % idx] = nic.ip
1476 2266edb2 Guido Trotter
    result['NIC_%d_BRIDGE' % idx] = nic.bridge
1477 2266edb2 Guido Trotter
    if constants.HV_NIC_TYPE in instance.hvparams:
1478 2266edb2 Guido Trotter
      result['NIC_%d_FRONTEND_TYPE' % idx] = \
1479 2266edb2 Guido Trotter
        instance.hvparams[constants.HV_NIC_TYPE]
1480 2266edb2 Guido Trotter
1481 2266edb2 Guido Trotter
  return result
1482 a8083063 Iustin Pop
1483 594609c0 Iustin Pop
def GrowBlockDevice(disk, amount):
1484 594609c0 Iustin Pop
  """Grow a stack of block devices.
1485 594609c0 Iustin Pop

1486 594609c0 Iustin Pop
  This function is called recursively, with the childrens being the
1487 10c2650b Iustin Pop
  first ones to resize.
1488 594609c0 Iustin Pop

1489 10c2650b Iustin Pop
  @type disk: L{objects.Disk}
1490 10c2650b Iustin Pop
  @param disk: the disk to be grown
1491 10c2650b Iustin Pop
  @rtype: (status, result)
1492 10c2650b Iustin Pop
  @return: a tuple with the status of the operation
1493 10c2650b Iustin Pop
      (True/False), and the errors message if status
1494 10c2650b Iustin Pop
      is False
1495 594609c0 Iustin Pop

1496 594609c0 Iustin Pop
  """
1497 594609c0 Iustin Pop
  r_dev = _RecursiveFindBD(disk)
1498 594609c0 Iustin Pop
  if r_dev is None:
1499 594609c0 Iustin Pop
    return False, "Cannot find block device %s" % (disk,)
1500 594609c0 Iustin Pop
1501 594609c0 Iustin Pop
  try:
1502 594609c0 Iustin Pop
    r_dev.Grow(amount)
1503 594609c0 Iustin Pop
  except errors.BlockDeviceError, err:
1504 594609c0 Iustin Pop
    return False, str(err)
1505 594609c0 Iustin Pop
1506 594609c0 Iustin Pop
  return True, None
1507 594609c0 Iustin Pop
1508 594609c0 Iustin Pop
1509 a8083063 Iustin Pop
def SnapshotBlockDevice(disk):
1510 a8083063 Iustin Pop
  """Create a snapshot copy of a block device.
1511 a8083063 Iustin Pop

1512 a8083063 Iustin Pop
  This function is called recursively, and the snapshot is actually created
1513 a8083063 Iustin Pop
  just for the leaf lvm backend device.
1514 a8083063 Iustin Pop

1515 e9e9263d Guido Trotter
  @type disk: L{objects.Disk}
1516 e9e9263d Guido Trotter
  @param disk: the disk to be snapshotted
1517 e9e9263d Guido Trotter
  @rtype: string
1518 e9e9263d Guido Trotter
  @return: snapshot disk path
1519 a8083063 Iustin Pop

1520 098c0958 Michael Hanselmann
  """
1521 a8083063 Iustin Pop
  if disk.children:
1522 a8083063 Iustin Pop
    if len(disk.children) == 1:
1523 a8083063 Iustin Pop
      # only one child, let's recurse on it
1524 a8083063 Iustin Pop
      return SnapshotBlockDevice(disk.children[0])
1525 a8083063 Iustin Pop
    else:
1526 a8083063 Iustin Pop
      # more than one child, choose one that matches
1527 a8083063 Iustin Pop
      for child in disk.children:
1528 a8083063 Iustin Pop
        if child.size == disk.size:
1529 a8083063 Iustin Pop
          # return implies breaking the loop
1530 a8083063 Iustin Pop
          return SnapshotBlockDevice(child)
1531 fe96220b Iustin Pop
  elif disk.dev_type == constants.LD_LV:
1532 a8083063 Iustin Pop
    r_dev = _RecursiveFindBD(disk)
1533 a8083063 Iustin Pop
    if r_dev is not None:
1534 a8083063 Iustin Pop
      # let's stay on the safe side and ask for the full size, for now
1535 a8083063 Iustin Pop
      return r_dev.Snapshot(disk.size)
1536 a8083063 Iustin Pop
    else:
1537 a8083063 Iustin Pop
      return None
1538 a8083063 Iustin Pop
  else:
1539 3ecf6786 Iustin Pop
    raise errors.ProgrammerError("Cannot snapshot non-lvm block device"
1540 f4bc1f2c Michael Hanselmann
                                 " '%s' of type '%s'" %
1541 3ecf6786 Iustin Pop
                                 (disk.unique_id, disk.dev_type))
1542 a8083063 Iustin Pop
1543 a8083063 Iustin Pop
1544 74c47259 Iustin Pop
def ExportSnapshot(disk, dest_node, instance, cluster_name, idx):
1545 a8083063 Iustin Pop
  """Export a block device snapshot to a remote node.
1546 a8083063 Iustin Pop

1547 74c47259 Iustin Pop
  @type disk: L{objects.Disk}
1548 74c47259 Iustin Pop
  @param disk: the description of the disk to export
1549 74c47259 Iustin Pop
  @type dest_node: str
1550 74c47259 Iustin Pop
  @param dest_node: the destination node to export to
1551 74c47259 Iustin Pop
  @type instance: L{objects.Instance}
1552 74c47259 Iustin Pop
  @param instance: the instance object to whom the disk belongs
1553 74c47259 Iustin Pop
  @type cluster_name: str
1554 74c47259 Iustin Pop
  @param cluster_name: the cluster name, needed for SSH hostalias
1555 74c47259 Iustin Pop
  @type idx: int
1556 74c47259 Iustin Pop
  @param idx: the index of the disk in the instance's disk list,
1557 74c47259 Iustin Pop
      used to export to the OS scripts environment
1558 10c2650b Iustin Pop
  @rtype: boolean
1559 74c47259 Iustin Pop
  @return: the success of the operation
1560 a8083063 Iustin Pop

1561 098c0958 Michael Hanselmann
  """
1562 0607699d Guido Trotter
  export_env = OSEnvironment(instance)
1563 d324e3fc Guido Trotter
1564 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1565 a8083063 Iustin Pop
  export_script = inst_os.export_script
1566 a8083063 Iustin Pop
1567 a8083063 Iustin Pop
  logfile = "%s/exp-%s-%s-%s.log" % (constants.LOG_OS_DIR, inst_os.name,
1568 a8083063 Iustin Pop
                                     instance.name, int(time.time()))
1569 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
1570 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
1571 0607699d Guido Trotter
  real_disk = _RecursiveFindBD(disk)
1572 0607699d Guido Trotter
  if real_disk is None:
1573 a8083063 Iustin Pop
    raise errors.BlockDeviceError("Block device '%s' is not set up" %
1574 a8083063 Iustin Pop
                                  str(disk))
1575 0607699d Guido Trotter
  real_disk.Open()
1576 0607699d Guido Trotter
1577 0607699d Guido Trotter
  export_env['EXPORT_DEVICE'] = real_disk.dev_path
1578 74c47259 Iustin Pop
  export_env['EXPORT_INDEX'] = str(idx)
1579 a8083063 Iustin Pop
1580 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1581 a8083063 Iustin Pop
  destfile = disk.physical_id[1]
1582 a8083063 Iustin Pop
1583 a8083063 Iustin Pop
  # the target command is built out of three individual commands,
1584 a8083063 Iustin Pop
  # which are joined by pipes; we check each individual command for
1585 a8083063 Iustin Pop
  # valid parameters
1586 0607699d Guido Trotter
  expcmd = utils.BuildShellCmd("cd %s; %s 2>%s", inst_os.path,
1587 0607699d Guido Trotter
                               export_script, logfile)
1588 a8083063 Iustin Pop
1589 a8083063 Iustin Pop
  comprcmd = "gzip"
1590 a8083063 Iustin Pop
1591 72f0f7fd Iustin Pop
  destcmd = utils.BuildShellCmd("mkdir -p %s && cat > %s/%s",
1592 00003458 Guido Trotter
                                destdir, destdir, destfile)
1593 62c9ec92 Iustin Pop
  remotecmd = _GetSshRunner(cluster_name).BuildCmd(dest_node,
1594 62c9ec92 Iustin Pop
                                                   constants.GANETI_RUNAS,
1595 62c9ec92 Iustin Pop
                                                   destcmd)
1596 a8083063 Iustin Pop
1597 a8083063 Iustin Pop
  # all commands have been checked, so we're safe to combine them
1598 72f0f7fd Iustin Pop
  command = '|'.join([expcmd, comprcmd, utils.ShellQuoteArgs(remotecmd)])
1599 a8083063 Iustin Pop
1600 0607699d Guido Trotter
  result = utils.RunCmd(command, env=export_env)
1601 a8083063 Iustin Pop
1602 a8083063 Iustin Pop
  if result.failed:
1603 18682bca Iustin Pop
    logging.error("os snapshot export command '%s' returned error: %s"
1604 18682bca Iustin Pop
                  " output: %s", command, result.fail_reason, result.output)
1605 a8083063 Iustin Pop
    return False
1606 a8083063 Iustin Pop
1607 a8083063 Iustin Pop
  return True
1608 a8083063 Iustin Pop
1609 a8083063 Iustin Pop
1610 a8083063 Iustin Pop
def FinalizeExport(instance, snap_disks):
1611 a8083063 Iustin Pop
  """Write out the export configuration information.
1612 a8083063 Iustin Pop

1613 10c2650b Iustin Pop
  @type instance: L{objects.Instance}
1614 10c2650b Iustin Pop
  @param instance: the instance which we export, used for
1615 10c2650b Iustin Pop
      saving configuration
1616 10c2650b Iustin Pop
  @type snap_disks: list of L{objects.Disk}
1617 10c2650b Iustin Pop
  @param snap_disks: list of snapshot block devices, which
1618 10c2650b Iustin Pop
      will be used to get the actual name of the dump file
1619 a8083063 Iustin Pop

1620 10c2650b Iustin Pop
  @rtype: boolean
1621 10c2650b Iustin Pop
  @return: the success of the operation
1622 a8083063 Iustin Pop

1623 098c0958 Michael Hanselmann
  """
1624 a8083063 Iustin Pop
  destdir = os.path.join(constants.EXPORT_DIR, instance.name + ".new")
1625 a8083063 Iustin Pop
  finaldestdir = os.path.join(constants.EXPORT_DIR, instance.name)
1626 a8083063 Iustin Pop
1627 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1628 a8083063 Iustin Pop
1629 a8083063 Iustin Pop
  config.add_section(constants.INISECT_EXP)
1630 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'version', '0')
1631 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'timestamp', '%d' % int(time.time()))
1632 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'source', instance.primary_node)
1633 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'os', instance.os)
1634 a8083063 Iustin Pop
  config.set(constants.INISECT_EXP, 'compression', 'gzip')
1635 a8083063 Iustin Pop
1636 a8083063 Iustin Pop
  config.add_section(constants.INISECT_INS)
1637 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'name', instance.name)
1638 51de46bf Iustin Pop
  config.set(constants.INISECT_INS, 'memory', '%d' %
1639 51de46bf Iustin Pop
             instance.beparams[constants.BE_MEMORY])
1640 51de46bf Iustin Pop
  config.set(constants.INISECT_INS, 'vcpus', '%d' %
1641 51de46bf Iustin Pop
             instance.beparams[constants.BE_VCPUS])
1642 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_template', instance.disk_template)
1643 66f93869 Manuel Franceschini
1644 66f93869 Manuel Franceschini
  nic_count = 0
1645 a8083063 Iustin Pop
  for nic_count, nic in enumerate(instance.nics):
1646 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_mac' %
1647 a8083063 Iustin Pop
               nic_count, '%s' % nic.mac)
1648 a8083063 Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_ip' % nic_count, '%s' % nic.ip)
1649 38206f3c Iustin Pop
    config.set(constants.INISECT_INS, 'nic%d_bridge' % nic_count,
1650 38206f3c Iustin Pop
               '%s' % nic.bridge)
1651 a8083063 Iustin Pop
  # TODO: redundant: on load can read nics until it doesn't exist
1652 a8083063 Iustin Pop
  config.set(constants.INISECT_INS, 'nic_count' , '%d' % nic_count)
1653 a8083063 Iustin Pop
1654 726d7d68 Iustin Pop
  disk_total = 0
1655 a8083063 Iustin Pop
  for disk_count, disk in enumerate(snap_disks):
1656 19d7f90a Guido Trotter
    if disk:
1657 726d7d68 Iustin Pop
      disk_total += 1
1658 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_ivname' % disk_count,
1659 19d7f90a Guido Trotter
                 ('%s' % disk.iv_name))
1660 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_dump' % disk_count,
1661 19d7f90a Guido Trotter
                 ('%s' % disk.physical_id[1]))
1662 19d7f90a Guido Trotter
      config.set(constants.INISECT_INS, 'disk%d_size' % disk_count,
1663 19d7f90a Guido Trotter
                 ('%d' % disk.size))
1664 a8083063 Iustin Pop
1665 726d7d68 Iustin Pop
  config.set(constants.INISECT_INS, 'disk_count' , '%d' % disk_total)
1666 a8083063 Iustin Pop
1667 726d7d68 Iustin Pop
  utils.WriteFile(os.path.join(destdir, constants.EXPORT_CONF_FILE),
1668 726d7d68 Iustin Pop
                  data=config.Dumps())
1669 a8083063 Iustin Pop
  shutil.rmtree(finaldestdir, True)
1670 a8083063 Iustin Pop
  shutil.move(destdir, finaldestdir)
1671 a8083063 Iustin Pop
1672 a8083063 Iustin Pop
  return True
1673 a8083063 Iustin Pop
1674 a8083063 Iustin Pop
1675 a8083063 Iustin Pop
def ExportInfo(dest):
1676 a8083063 Iustin Pop
  """Get export configuration information.
1677 a8083063 Iustin Pop

1678 10c2650b Iustin Pop
  @type dest: str
1679 10c2650b Iustin Pop
  @param dest: directory containing the export
1680 a8083063 Iustin Pop

1681 10c2650b Iustin Pop
  @rtype: L{objects.SerializableConfigParser}
1682 10c2650b Iustin Pop
  @return: a serializable config file containing the
1683 10c2650b Iustin Pop
      export info
1684 a8083063 Iustin Pop

1685 a8083063 Iustin Pop
  """
1686 a8083063 Iustin Pop
  cff = os.path.join(dest, constants.EXPORT_CONF_FILE)
1687 a8083063 Iustin Pop
1688 a8083063 Iustin Pop
  config = objects.SerializableConfigParser()
1689 a8083063 Iustin Pop
  config.read(cff)
1690 a8083063 Iustin Pop
1691 a8083063 Iustin Pop
  if (not config.has_section(constants.INISECT_EXP) or
1692 a8083063 Iustin Pop
      not config.has_section(constants.INISECT_INS)):
1693 a8083063 Iustin Pop
    return None
1694 a8083063 Iustin Pop
1695 a8083063 Iustin Pop
  return config
1696 a8083063 Iustin Pop
1697 a8083063 Iustin Pop
1698 6c0af70e Guido Trotter
def ImportOSIntoInstance(instance, src_node, src_images, cluster_name):
1699 a8083063 Iustin Pop
  """Import an os image into an instance.
1700 a8083063 Iustin Pop

1701 b1206984 Iustin Pop
  @type instance: L{objects.Instance}
1702 6c0af70e Guido Trotter
  @param instance: instance to import the disks into
1703 6c0af70e Guido Trotter
  @type src_node: string
1704 6c0af70e Guido Trotter
  @param src_node: source node for the disk images
1705 6c0af70e Guido Trotter
  @type src_images: list of string
1706 6c0af70e Guido Trotter
  @param src_images: absolute paths of the disk images
1707 6c0af70e Guido Trotter
  @rtype: list of boolean
1708 6c0af70e Guido Trotter
  @return: each boolean represent the success of importing the n-th disk
1709 a8083063 Iustin Pop

1710 a8083063 Iustin Pop
  """
1711 6c0af70e Guido Trotter
  import_env = OSEnvironment(instance)
1712 a8083063 Iustin Pop
  inst_os = OSFromDisk(instance.os)
1713 a8083063 Iustin Pop
  import_script = inst_os.import_script
1714 a8083063 Iustin Pop
1715 a8083063 Iustin Pop
  logfile = "%s/import-%s-%s-%s.log" % (constants.LOG_OS_DIR, instance.os,
1716 a8083063 Iustin Pop
                                        instance.name, int(time.time()))
1717 a8083063 Iustin Pop
  if not os.path.exists(constants.LOG_OS_DIR):
1718 a8083063 Iustin Pop
    os.mkdir(constants.LOG_OS_DIR, 0750)
1719 a8083063 Iustin Pop
1720 a8083063 Iustin Pop
  comprcmd = "gunzip"
1721 d868edb4 Iustin Pop
  impcmd = utils.BuildShellCmd("(cd %s; %s >%s 2>&1)", inst_os.path,
1722 d868edb4 Iustin Pop
                               import_script, logfile)
1723 a8083063 Iustin Pop
1724 6c0af70e Guido Trotter
  final_result = []
1725 6c0af70e Guido Trotter
  for idx, image in enumerate(src_images):
1726 6c0af70e Guido Trotter
    if image:
1727 6c0af70e Guido Trotter
      destcmd = utils.BuildShellCmd('cat %s', image)
1728 6c0af70e Guido Trotter
      remotecmd = _GetSshRunner(cluster_name).BuildCmd(src_node,
1729 6c0af70e Guido Trotter
                                                       constants.GANETI_RUNAS,
1730 6c0af70e Guido Trotter
                                                       destcmd)
1731 6c0af70e Guido Trotter
      command = '|'.join([utils.ShellQuoteArgs(remotecmd), comprcmd, impcmd])
1732 6c0af70e Guido Trotter
      import_env['IMPORT_DEVICE'] = import_env['DISK_%d_PATH' % idx]
1733 74c47259 Iustin Pop
      import_env['IMPORT_INDEX'] = str(idx)
1734 6c0af70e Guido Trotter
      result = utils.RunCmd(command, env=import_env)
1735 6c0af70e Guido Trotter
      if result.failed:
1736 726d7d68 Iustin Pop
        logging.error("Disk import command '%s' returned error: %s"
1737 726d7d68 Iustin Pop
                      " output: %s", command, result.fail_reason,
1738 726d7d68 Iustin Pop
                      result.output)
1739 6c0af70e Guido Trotter
        final_result.append(False)
1740 6c0af70e Guido Trotter
      else:
1741 6c0af70e Guido Trotter
        final_result.append(True)
1742 6c0af70e Guido Trotter
    else:
1743 6c0af70e Guido Trotter
      final_result.append(True)
1744 a8083063 Iustin Pop
1745 6c0af70e Guido Trotter
  return final_result
1746 a8083063 Iustin Pop
1747 a8083063 Iustin Pop
1748 a8083063 Iustin Pop
def ListExports():
1749 a8083063 Iustin Pop
  """Return a list of exports currently available on this machine.
1750 098c0958 Michael Hanselmann

1751 10c2650b Iustin Pop
  @rtype: list
1752 10c2650b Iustin Pop
  @return: list of the exports
1753 10c2650b Iustin Pop

1754 a8083063 Iustin Pop
  """
1755 a8083063 Iustin Pop
  if os.path.isdir(constants.EXPORT_DIR):
1756 eedbda4b Michael Hanselmann
    return utils.ListVisibleFiles(constants.EXPORT_DIR)
1757 a8083063 Iustin Pop
  else:
1758 a8083063 Iustin Pop
    return []
1759 a8083063 Iustin Pop
1760 a8083063 Iustin Pop
1761 a8083063 Iustin Pop
def RemoveExport(export):
1762 a8083063 Iustin Pop
  """Remove an existing export from the node.
1763 a8083063 Iustin Pop

1764 10c2650b Iustin Pop
  @type export: str
1765 10c2650b Iustin Pop
  @param export: the name of the export to remove
1766 10c2650b Iustin Pop
  @rtype: boolean
1767 10c2650b Iustin Pop
  @return: the success of the operation
1768 a8083063 Iustin Pop

1769 098c0958 Michael Hanselmann
  """
1770 a8083063 Iustin Pop
  target = os.path.join(constants.EXPORT_DIR, export)
1771 a8083063 Iustin Pop
1772 a8083063 Iustin Pop
  shutil.rmtree(target)
1773 a8083063 Iustin Pop
  # TODO: catch some of the relevant exceptions and provide a pretty
1774 a8083063 Iustin Pop
  # error message if rmtree fails.
1775 a8083063 Iustin Pop
1776 a8083063 Iustin Pop
  return True
1777 a8083063 Iustin Pop
1778 a8083063 Iustin Pop
1779 f3e513ad Iustin Pop
def RenameBlockDevices(devlist):
1780 f3e513ad Iustin Pop
  """Rename a list of block devices.
1781 f3e513ad Iustin Pop

1782 10c2650b Iustin Pop
  @type devlist: list of tuples
1783 10c2650b Iustin Pop
  @param devlist: list of tuples of the form  (disk,
1784 10c2650b Iustin Pop
      new_logical_id, new_physical_id); disk is an
1785 10c2650b Iustin Pop
      L{objects.Disk} object describing the current disk,
1786 10c2650b Iustin Pop
      and new logical_id/physical_id is the name we
1787 10c2650b Iustin Pop
      rename it to
1788 10c2650b Iustin Pop
  @rtype: boolean
1789 10c2650b Iustin Pop
  @return: True if all renames succeeded, False otherwise
1790 f3e513ad Iustin Pop

1791 f3e513ad Iustin Pop
  """
1792 f3e513ad Iustin Pop
  result = True
1793 f3e513ad Iustin Pop
  for disk, unique_id in devlist:
1794 f3e513ad Iustin Pop
    dev = _RecursiveFindBD(disk)
1795 f3e513ad Iustin Pop
    if dev is None:
1796 f3e513ad Iustin Pop
      result = False
1797 f3e513ad Iustin Pop
      continue
1798 f3e513ad Iustin Pop
    try:
1799 3f78eef2 Iustin Pop
      old_rpath = dev.dev_path
1800 f3e513ad Iustin Pop
      dev.Rename(unique_id)
1801 3f78eef2 Iustin Pop
      new_rpath = dev.dev_path
1802 3f78eef2 Iustin Pop
      if old_rpath != new_rpath:
1803 3f78eef2 Iustin Pop
        DevCacheManager.RemoveCache(old_rpath)
1804 3f78eef2 Iustin Pop
        # FIXME: we should add the new cache information here, like:
1805 3f78eef2 Iustin Pop
        # DevCacheManager.UpdateCache(new_rpath, owner, ...)
1806 3f78eef2 Iustin Pop
        # but we don't have the owner here - maybe parse from existing
1807 3f78eef2 Iustin Pop
        # cache? for now, we only lose lvm data when we rename, which
1808 3f78eef2 Iustin Pop
        # is less critical than DRBD or MD
1809 f3e513ad Iustin Pop
    except errors.BlockDeviceError, err:
1810 18682bca Iustin Pop
      logging.exception("Can't rename device '%s' to '%s'", dev, unique_id)
1811 f3e513ad Iustin Pop
      result = False
1812 f3e513ad Iustin Pop
  return result
1813 f3e513ad Iustin Pop
1814 f3e513ad Iustin Pop
1815 778b75bb Manuel Franceschini
def _TransformFileStorageDir(file_storage_dir):
1816 778b75bb Manuel Franceschini
  """Checks whether given file_storage_dir is valid.
1817 778b75bb Manuel Franceschini

1818 778b75bb Manuel Franceschini
  Checks wheter the given file_storage_dir is within the cluster-wide
1819 778b75bb Manuel Franceschini
  default file_storage_dir stored in SimpleStore. Only paths under that
1820 778b75bb Manuel Franceschini
  directory are allowed.
1821 778b75bb Manuel Franceschini

1822 b1206984 Iustin Pop
  @type file_storage_dir: str
1823 b1206984 Iustin Pop
  @param file_storage_dir: the path to check
1824 d61cbe76 Iustin Pop

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

1827 778b75bb Manuel Franceschini
  """
1828 c657dcc9 Michael Hanselmann
  cfg = _GetConfig()
1829 778b75bb Manuel Franceschini
  file_storage_dir = os.path.normpath(file_storage_dir)
1830 c657dcc9 Michael Hanselmann
  base_file_storage_dir = cfg.GetFileStorageDir()
1831 778b75bb Manuel Franceschini
  if (not os.path.commonprefix([file_storage_dir, base_file_storage_dir]) ==
1832 778b75bb Manuel Franceschini
      base_file_storage_dir):
1833 18682bca Iustin Pop
    logging.error("file storage directory '%s' is not under base file"
1834 18682bca Iustin Pop
                  " storage directory '%s'",
1835 18682bca Iustin Pop
                  file_storage_dir, base_file_storage_dir)
1836 778b75bb Manuel Franceschini
    return None
1837 778b75bb Manuel Franceschini
  return file_storage_dir
1838 778b75bb Manuel Franceschini
1839 778b75bb Manuel Franceschini
1840 778b75bb Manuel Franceschini
def CreateFileStorageDir(file_storage_dir):
1841 778b75bb Manuel Franceschini
  """Create file storage directory.
1842 778b75bb Manuel Franceschini

1843 b1206984 Iustin Pop
  @type file_storage_dir: str
1844 b1206984 Iustin Pop
  @param file_storage_dir: directory to create
1845 778b75bb Manuel Franceschini

1846 b1206984 Iustin Pop
  @rtype: tuple
1847 b1206984 Iustin Pop
  @return: tuple with first element a boolean indicating wheter dir
1848 b1206984 Iustin Pop
      creation was successful or not
1849 778b75bb Manuel Franceschini

1850 778b75bb Manuel Franceschini
  """
1851 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
1852 778b75bb Manuel Franceschini
  result = True,
1853 778b75bb Manuel Franceschini
  if not file_storage_dir:
1854 778b75bb Manuel Franceschini
    result = False,
1855 778b75bb Manuel Franceschini
  else:
1856 778b75bb Manuel Franceschini
    if os.path.exists(file_storage_dir):
1857 778b75bb Manuel Franceschini
      if not os.path.isdir(file_storage_dir):
1858 18682bca Iustin Pop
        logging.error("'%s' is not a directory", file_storage_dir)
1859 778b75bb Manuel Franceschini
        result = False,
1860 778b75bb Manuel Franceschini
    else:
1861 778b75bb Manuel Franceschini
      try:
1862 778b75bb Manuel Franceschini
        os.makedirs(file_storage_dir, 0750)
1863 778b75bb Manuel Franceschini
      except OSError, err:
1864 18682bca Iustin Pop
        logging.error("Cannot create file storage directory '%s': %s",
1865 18682bca Iustin Pop
                      file_storage_dir, err)
1866 778b75bb Manuel Franceschini
        result = False,
1867 778b75bb Manuel Franceschini
  return result
1868 778b75bb Manuel Franceschini
1869 778b75bb Manuel Franceschini
1870 778b75bb Manuel Franceschini
def RemoveFileStorageDir(file_storage_dir):
1871 778b75bb Manuel Franceschini
  """Remove file storage directory.
1872 778b75bb Manuel Franceschini

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

1875 10c2650b Iustin Pop
  @type file_storage_dir: str
1876 10c2650b Iustin Pop
  @param file_storage_dir: the directory we should cleanup
1877 10c2650b Iustin Pop
  @rtype: tuple (success,)
1878 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
1879 10c2650b Iustin Pop
      whether the operation was successfull
1880 778b75bb Manuel Franceschini

1881 778b75bb Manuel Franceschini
  """
1882 778b75bb Manuel Franceschini
  file_storage_dir = _TransformFileStorageDir(file_storage_dir)
1883 778b75bb Manuel Franceschini
  result = True,
1884 778b75bb Manuel Franceschini
  if not file_storage_dir:
1885 778b75bb Manuel Franceschini
    result = False,
1886 778b75bb Manuel Franceschini
  else:
1887 778b75bb Manuel Franceschini
    if os.path.exists(file_storage_dir):
1888 778b75bb Manuel Franceschini
      if not os.path.isdir(file_storage_dir):
1889 18682bca Iustin Pop
        logging.error("'%s' is not a directory", file_storage_dir)
1890 778b75bb Manuel Franceschini
        result = False,
1891 778b75bb Manuel Franceschini
      # deletes dir only if empty, otherwise we want to return False
1892 778b75bb Manuel Franceschini
      try:
1893 778b75bb Manuel Franceschini
        os.rmdir(file_storage_dir)
1894 778b75bb Manuel Franceschini
      except OSError, err:
1895 18682bca Iustin Pop
        logging.exception("Cannot remove file storage directory '%s'",
1896 18682bca Iustin Pop
                          file_storage_dir)
1897 778b75bb Manuel Franceschini
        result = False,
1898 778b75bb Manuel Franceschini
  return result
1899 778b75bb Manuel Franceschini
1900 778b75bb Manuel Franceschini
1901 778b75bb Manuel Franceschini
def RenameFileStorageDir(old_file_storage_dir, new_file_storage_dir):
1902 778b75bb Manuel Franceschini
  """Rename the file storage directory.
1903 778b75bb Manuel Franceschini

1904 10c2650b Iustin Pop
  @type old_file_storage_dir: str
1905 10c2650b Iustin Pop
  @param old_file_storage_dir: the current path
1906 10c2650b Iustin Pop
  @type new_file_storage_dir: str
1907 10c2650b Iustin Pop
  @param new_file_storage_dir: the name we should rename to
1908 10c2650b Iustin Pop
  @rtype: tuple (success,)
1909 10c2650b Iustin Pop
  @return: tuple of one element, C{success}, denoting
1910 10c2650b Iustin Pop
      whether the operation was successful
1911 778b75bb Manuel Franceschini

1912 778b75bb Manuel Franceschini
  """
1913 778b75bb Manuel Franceschini
  old_file_storage_dir = _TransformFileStorageDir(old_file_storage_dir)
1914 778b75bb Manuel Franceschini
  new_file_storage_dir = _TransformFileStorageDir(new_file_storage_dir)
1915 778b75bb Manuel Franceschini
  result = True,
1916 778b75bb Manuel Franceschini
  if not old_file_storage_dir or not new_file_storage_dir:
1917 778b75bb Manuel Franceschini
    result = False,
1918 778b75bb Manuel Franceschini
  else:
1919 778b75bb Manuel Franceschini
    if not os.path.exists(new_file_storage_dir):
1920 778b75bb Manuel Franceschini
      if os.path.isdir(old_file_storage_dir):
1921 778b75bb Manuel Franceschini
        try:
1922 778b75bb Manuel Franceschini
          os.rename(old_file_storage_dir, new_file_storage_dir)
1923 778b75bb Manuel Franceschini
        except OSError, err:
1924 18682bca Iustin Pop
          logging.exception("Cannot rename '%s' to '%s'",
1925 18682bca Iustin Pop
                            old_file_storage_dir, new_file_storage_dir)
1926 778b75bb Manuel Franceschini
          result =  False,
1927 778b75bb Manuel Franceschini
      else:
1928 18682bca Iustin Pop
        logging.error("'%s' is not a directory", old_file_storage_dir)
1929 778b75bb Manuel Franceschini
        result = False,
1930 778b75bb Manuel Franceschini
    else:
1931 778b75bb Manuel Franceschini
      if os.path.exists(old_file_storage_dir):
1932 18682bca Iustin Pop
        logging.error("Cannot rename '%s' to '%s'. Both locations exist.",
1933 18682bca Iustin Pop
                      old_file_storage_dir, new_file_storage_dir)
1934 778b75bb Manuel Franceschini
        result = False,
1935 778b75bb Manuel Franceschini
  return result
1936 778b75bb Manuel Franceschini
1937 778b75bb Manuel Franceschini
1938 dc31eae3 Michael Hanselmann
def _IsJobQueueFile(file_name):
1939 dc31eae3 Michael Hanselmann
  """Checks whether the given filename is in the queue directory.
1940 ca52cdeb Michael Hanselmann

1941 10c2650b Iustin Pop
  @type file_name: str
1942 10c2650b Iustin Pop
  @param file_name: the file name we should check
1943 10c2650b Iustin Pop
  @rtype: boolean
1944 10c2650b Iustin Pop
  @return: whether the file is under the queue directory
1945 10c2650b Iustin Pop

1946 ca52cdeb Michael Hanselmann
  """
1947 ca52cdeb Michael Hanselmann
  queue_dir = os.path.normpath(constants.QUEUE_DIR)
1948 dc31eae3 Michael Hanselmann
  result = (os.path.commonprefix([queue_dir, file_name]) == queue_dir)
1949 dc31eae3 Michael Hanselmann
1950 dc31eae3 Michael Hanselmann
  if not result:
1951 ca52cdeb Michael Hanselmann
    logging.error("'%s' is not a file in the queue directory",
1952 ca52cdeb Michael Hanselmann
                  file_name)
1953 dc31eae3 Michael Hanselmann
1954 dc31eae3 Michael Hanselmann
  return result
1955 dc31eae3 Michael Hanselmann
1956 dc31eae3 Michael Hanselmann
1957 dc31eae3 Michael Hanselmann
def JobQueueUpdate(file_name, content):
1958 dc31eae3 Michael Hanselmann
  """Updates a file in the queue directory.
1959 dc31eae3 Michael Hanselmann

1960 10c2650b Iustin Pop
  This is just a wrapper over L{utils.WriteFile}, with proper
1961 10c2650b Iustin Pop
  checking.
1962 10c2650b Iustin Pop

1963 10c2650b Iustin Pop
  @type file_name: str
1964 10c2650b Iustin Pop
  @param file_name: the job file name
1965 10c2650b Iustin Pop
  @type content: str
1966 10c2650b Iustin Pop
  @param content: the new job contents
1967 10c2650b Iustin Pop
  @rtype: boolean
1968 10c2650b Iustin Pop
  @return: the success of the operation
1969 10c2650b Iustin Pop

1970 dc31eae3 Michael Hanselmann
  """
1971 dc31eae3 Michael Hanselmann
  if not _IsJobQueueFile(file_name):
1972 ca52cdeb Michael Hanselmann
    return False
1973 ca52cdeb Michael Hanselmann
1974 ca52cdeb Michael Hanselmann
  # Write and replace the file atomically
1975 12bce260 Michael Hanselmann
  utils.WriteFile(file_name, data=_Decompress(content))
1976 ca52cdeb Michael Hanselmann
1977 ca52cdeb Michael Hanselmann
  return True
1978 ca52cdeb Michael Hanselmann
1979 ca52cdeb Michael Hanselmann
1980 af5ebcb1 Michael Hanselmann
def JobQueueRename(old, new):
1981 af5ebcb1 Michael Hanselmann
  """Renames a job queue file.
1982 af5ebcb1 Michael Hanselmann

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

1985 10c2650b Iustin Pop
  @type old: str
1986 10c2650b Iustin Pop
  @param old: the old (actual) file name
1987 10c2650b Iustin Pop
  @type new: str
1988 10c2650b Iustin Pop
  @param new: the desired file name
1989 10c2650b Iustin Pop
  @rtype: boolean
1990 10c2650b Iustin Pop
  @return: the success of the operation
1991 10c2650b Iustin Pop

1992 af5ebcb1 Michael Hanselmann
  """
1993 af5ebcb1 Michael Hanselmann
  if not (_IsJobQueueFile(old) and _IsJobQueueFile(new)):
1994 af5ebcb1 Michael Hanselmann
    return False
1995 af5ebcb1 Michael Hanselmann
1996 af5ebcb1 Michael Hanselmann
  os.rename(old, new)
1997 af5ebcb1 Michael Hanselmann
1998 af5ebcb1 Michael Hanselmann
  return True
1999 af5ebcb1 Michael Hanselmann
2000 af5ebcb1 Michael Hanselmann
2001 5d672980 Iustin Pop
def JobQueueSetDrainFlag(drain_flag):
2002 5d672980 Iustin Pop
  """Set the drain flag for the queue.
2003 5d672980 Iustin Pop

2004 5d672980 Iustin Pop
  This will set or unset the queue drain flag.
2005 5d672980 Iustin Pop

2006 10c2650b Iustin Pop
  @type drain_flag: boolean
2007 5d672980 Iustin Pop
  @param drain_flag: if True, will set the drain flag, otherwise reset it.
2008 10c2650b Iustin Pop
  @rtype: boolean
2009 10c2650b Iustin Pop
  @return: always True
2010 10c2650b Iustin Pop
  @warning: the function always returns True
2011 5d672980 Iustin Pop

2012 5d672980 Iustin Pop
  """
2013 5d672980 Iustin Pop
  if drain_flag:
2014 5d672980 Iustin Pop
    utils.WriteFile(constants.JOB_QUEUE_DRAIN_FILE, data="", close=True)
2015 5d672980 Iustin Pop
  else:
2016 5d672980 Iustin Pop
    utils.RemoveFile(constants.JOB_QUEUE_DRAIN_FILE)
2017 5d672980 Iustin Pop
2018 5d672980 Iustin Pop
  return True
2019 5d672980 Iustin Pop
2020 5d672980 Iustin Pop
2021 d61cbe76 Iustin Pop
def CloseBlockDevices(disks):
2022 d61cbe76 Iustin Pop
  """Closes the given block devices.
2023 d61cbe76 Iustin Pop

2024 10c2650b Iustin Pop
  This means they will be switched to secondary mode (in case of
2025 10c2650b Iustin Pop
  DRBD).
2026 10c2650b Iustin Pop

2027 10c2650b Iustin Pop
  @type disks: list of L{objects.Disk}
2028 10c2650b Iustin Pop
  @param disks: the list of disks to be closed
2029 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2030 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2031 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2032 10c2650b Iustin Pop
      which will contain the error details in case we
2033 10c2650b Iustin Pop
      failed
2034 d61cbe76 Iustin Pop

2035 d61cbe76 Iustin Pop
  """
2036 d61cbe76 Iustin Pop
  bdevs = []
2037 d61cbe76 Iustin Pop
  for cf in disks:
2038 d61cbe76 Iustin Pop
    rd = _RecursiveFindBD(cf)
2039 d61cbe76 Iustin Pop
    if rd is None:
2040 d61cbe76 Iustin Pop
      return (False, "Can't find device %s" % cf)
2041 d61cbe76 Iustin Pop
    bdevs.append(rd)
2042 d61cbe76 Iustin Pop
2043 d61cbe76 Iustin Pop
  msg = []
2044 d61cbe76 Iustin Pop
  for rd in bdevs:
2045 d61cbe76 Iustin Pop
    try:
2046 d61cbe76 Iustin Pop
      rd.Close()
2047 d61cbe76 Iustin Pop
    except errors.BlockDeviceError, err:
2048 d61cbe76 Iustin Pop
      msg.append(str(err))
2049 d61cbe76 Iustin Pop
  if msg:
2050 d61cbe76 Iustin Pop
    return (False, "Can't make devices secondary: %s" % ",".join(msg))
2051 d61cbe76 Iustin Pop
  else:
2052 d61cbe76 Iustin Pop
    return (True, "All devices secondary")
2053 d61cbe76 Iustin Pop
2054 d61cbe76 Iustin Pop
2055 6217e295 Iustin Pop
def ValidateHVParams(hvname, hvparams):
2056 6217e295 Iustin Pop
  """Validates the given hypervisor parameters.
2057 6217e295 Iustin Pop

2058 6217e295 Iustin Pop
  @type hvname: string
2059 6217e295 Iustin Pop
  @param hvname: the hypervisor name
2060 6217e295 Iustin Pop
  @type hvparams: dict
2061 6217e295 Iustin Pop
  @param hvparams: the hypervisor parameters to be validated
2062 10c2650b Iustin Pop
  @rtype: tuple (success, message)
2063 10c2650b Iustin Pop
  @return: a tuple of success and message, where success
2064 10c2650b Iustin Pop
      indicates the succes of the operation, and message
2065 10c2650b Iustin Pop
      which will contain the error details in case we
2066 10c2650b Iustin Pop
      failed
2067 6217e295 Iustin Pop

2068 6217e295 Iustin Pop
  """
2069 6217e295 Iustin Pop
  try:
2070 6217e295 Iustin Pop
    hv_type = hypervisor.GetHypervisor(hvname)
2071 6217e295 Iustin Pop
    hv_type.ValidateParameters(hvparams)
2072 6217e295 Iustin Pop
    return (True, "Validation passed")
2073 6217e295 Iustin Pop
  except errors.HypervisorError, err:
2074 6217e295 Iustin Pop
    return (False, str(err))
2075 6217e295 Iustin Pop
2076 6217e295 Iustin Pop
2077 56aa9fd5 Iustin Pop
def DemoteFromMC():
2078 56aa9fd5 Iustin Pop
  """Demotes the current node from master candidate role.
2079 56aa9fd5 Iustin Pop

2080 56aa9fd5 Iustin Pop
  """
2081 56aa9fd5 Iustin Pop
  # try to ensure we're not the master by mistake
2082 56aa9fd5 Iustin Pop
  master, myself = ssconf.GetMasterAndMyself()
2083 56aa9fd5 Iustin Pop
  if master == myself:
2084 56aa9fd5 Iustin Pop
    return (False, "ssconf status shows I'm the master node, will not demote")
2085 56aa9fd5 Iustin Pop
  pid_file = utils.DaemonPidFileName(constants.MASTERD_PID)
2086 56aa9fd5 Iustin Pop
  if utils.IsProcessAlive(utils.ReadPidFile(pid_file)):
2087 56aa9fd5 Iustin Pop
    return (False, "The master daemon is running, will not demote")
2088 56aa9fd5 Iustin Pop
  try:
2089 56aa9fd5 Iustin Pop
    utils.CreateBackup(constants.CLUSTER_CONF_FILE)
2090 56aa9fd5 Iustin Pop
  except EnvironmentError, err:
2091 56aa9fd5 Iustin Pop
    if err.errno != errno.ENOENT:
2092 56aa9fd5 Iustin Pop
      return (False, "Error while backing up cluster file: %s" % str(err))
2093 56aa9fd5 Iustin Pop
  utils.RemoveFile(constants.CLUSTER_CONF_FILE)
2094 56aa9fd5 Iustin Pop
  return (True, "Done")
2095 56aa9fd5 Iustin Pop
2096 56aa9fd5 Iustin Pop
2097 a8083063 Iustin Pop
class HooksRunner(object):
2098 a8083063 Iustin Pop
  """Hook runner.
2099 a8083063 Iustin Pop

2100 10c2650b Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not
2101 10c2650b Iustin Pop
  on the master side.
2102 a8083063 Iustin Pop

2103 a8083063 Iustin Pop
  """
2104 a8083063 Iustin Pop
  RE_MASK = re.compile("^[a-zA-Z0-9_-]+$")
2105 a8083063 Iustin Pop
2106 a8083063 Iustin Pop
  def __init__(self, hooks_base_dir=None):
2107 a8083063 Iustin Pop
    """Constructor for hooks runner.
2108 a8083063 Iustin Pop

2109 10c2650b Iustin Pop
    @type hooks_base_dir: str or None
2110 10c2650b Iustin Pop
    @param hooks_base_dir: if not None, this overrides the
2111 10c2650b Iustin Pop
        L{constants.HOOKS_BASE_DIR} (useful for unittests)
2112 a8083063 Iustin Pop

2113 a8083063 Iustin Pop
    """
2114 a8083063 Iustin Pop
    if hooks_base_dir is None:
2115 a8083063 Iustin Pop
      hooks_base_dir = constants.HOOKS_BASE_DIR
2116 a8083063 Iustin Pop
    self._BASE_DIR = hooks_base_dir
2117 a8083063 Iustin Pop
2118 a8083063 Iustin Pop
  @staticmethod
2119 a8083063 Iustin Pop
  def ExecHook(script, env):
2120 a8083063 Iustin Pop
    """Exec one hook script.
2121 a8083063 Iustin Pop

2122 10c2650b Iustin Pop
    @type script: str
2123 10c2650b Iustin Pop
    @param script: the full path to the script
2124 10c2650b Iustin Pop
    @type env: dict
2125 10c2650b Iustin Pop
    @param env: the environment with which to exec the script
2126 10c2650b Iustin Pop
    @rtype: tuple (success, message)
2127 10c2650b Iustin Pop
    @return: a tuple of success and message, where success
2128 10c2650b Iustin Pop
        indicates the succes of the operation, and message
2129 10c2650b Iustin Pop
        which will contain the error details in case we
2130 10c2650b Iustin Pop
        failed
2131 a8083063 Iustin Pop

2132 a8083063 Iustin Pop
    """
2133 a8083063 Iustin Pop
    # exec the process using subprocess and log the output
2134 a8083063 Iustin Pop
    fdstdin = None
2135 a8083063 Iustin Pop
    try:
2136 a8083063 Iustin Pop
      fdstdin = open("/dev/null", "r")
2137 a8083063 Iustin Pop
      child = subprocess.Popen([script], stdin=fdstdin, stdout=subprocess.PIPE,
2138 a8083063 Iustin Pop
                               stderr=subprocess.STDOUT, close_fds=True,
2139 147af04d Iustin Pop
                               shell=False, cwd="/", env=env)
2140 a8083063 Iustin Pop
      output = ""
2141 a8083063 Iustin Pop
      try:
2142 a8083063 Iustin Pop
        output = child.stdout.read(4096)
2143 a8083063 Iustin Pop
        child.stdout.close()
2144 a8083063 Iustin Pop
      except EnvironmentError, err:
2145 a8083063 Iustin Pop
        output += "Hook script error: %s" % str(err)
2146 a8083063 Iustin Pop
2147 a8083063 Iustin Pop
      while True:
2148 a8083063 Iustin Pop
        try:
2149 a8083063 Iustin Pop
          result = child.wait()
2150 a8083063 Iustin Pop
          break
2151 a8083063 Iustin Pop
        except EnvironmentError, err:
2152 a8083063 Iustin Pop
          if err.errno == errno.EINTR:
2153 a8083063 Iustin Pop
            continue
2154 a8083063 Iustin Pop
          raise
2155 a8083063 Iustin Pop
    finally:
2156 a8083063 Iustin Pop
      # try not to leak fds
2157 a8083063 Iustin Pop
      for fd in (fdstdin, ):
2158 a8083063 Iustin Pop
        if fd is not None:
2159 a8083063 Iustin Pop
          try:
2160 a8083063 Iustin Pop
            fd.close()
2161 a8083063 Iustin Pop
          except EnvironmentError, err:
2162 a8083063 Iustin Pop
            # just log the error
2163 18682bca Iustin Pop
            #logging.exception("Error while closing fd %s", fd)
2164 a8083063 Iustin Pop
            pass
2165 a8083063 Iustin Pop
2166 a8083063 Iustin Pop
    return result == 0, output
2167 a8083063 Iustin Pop
2168 a8083063 Iustin Pop
  def RunHooks(self, hpath, phase, env):
2169 a8083063 Iustin Pop
    """Run the scripts in the hooks directory.
2170 a8083063 Iustin Pop

2171 10c2650b Iustin Pop
    @type hpath: str
2172 10c2650b Iustin Pop
    @param hpath: the path to the hooks directory which
2173 10c2650b Iustin Pop
        holds the scripts
2174 10c2650b Iustin Pop
    @type phase: str
2175 10c2650b Iustin Pop
    @param phase: either L{constants.HOOKS_PHASE_PRE} or
2176 10c2650b Iustin Pop
        L{constants.HOOKS_PHASE_POST}
2177 10c2650b Iustin Pop
    @type env: dict
2178 10c2650b Iustin Pop
    @param env: dictionary with the environment for the hook
2179 10c2650b Iustin Pop
    @rtype: list
2180 10c2650b Iustin Pop
    @return: list of 3-element tuples:
2181 10c2650b Iustin Pop
      - script path
2182 10c2650b Iustin Pop
      - script result, either L{constants.HKR_SUCCESS} or
2183 10c2650b Iustin Pop
        L{constants.HKR_FAIL}
2184 10c2650b Iustin Pop
      - output of the script
2185 10c2650b Iustin Pop

2186 10c2650b Iustin Pop
    @raise errors.ProgrammerError: for invalid input
2187 10c2650b Iustin Pop
        parameters
2188 a8083063 Iustin Pop

2189 a8083063 Iustin Pop
    """
2190 a8083063 Iustin Pop
    if phase == constants.HOOKS_PHASE_PRE:
2191 a8083063 Iustin Pop
      suffix = "pre"
2192 a8083063 Iustin Pop
    elif phase == constants.HOOKS_PHASE_POST:
2193 a8083063 Iustin Pop
      suffix = "post"
2194 a8083063 Iustin Pop
    else:
2195 3ecf6786 Iustin Pop
      raise errors.ProgrammerError("Unknown hooks phase: '%s'" % phase)
2196 a8083063 Iustin Pop
    rr = []
2197 a8083063 Iustin Pop
2198 a8083063 Iustin Pop
    subdir = "%s-%s.d" % (hpath, suffix)
2199 a8083063 Iustin Pop
    dir_name = "%s/%s" % (self._BASE_DIR, subdir)
2200 a8083063 Iustin Pop
    try:
2201 eedbda4b Michael Hanselmann
      dir_contents = utils.ListVisibleFiles(dir_name)
2202 a8083063 Iustin Pop
    except OSError, err:
2203 10c2650b Iustin Pop
      # FIXME: must log output in case of failures
2204 a8083063 Iustin Pop
      return rr
2205 a8083063 Iustin Pop
2206 a8083063 Iustin Pop
    # we use the standard python sort order,
2207 a8083063 Iustin Pop
    # so 00name is the recommended naming scheme
2208 a8083063 Iustin Pop
    dir_contents.sort()
2209 a8083063 Iustin Pop
    for relname in dir_contents:
2210 a8083063 Iustin Pop
      fname = os.path.join(dir_name, relname)
2211 a8083063 Iustin Pop
      if not (os.path.isfile(fname) and os.access(fname, os.X_OK) and
2212 a8083063 Iustin Pop
          self.RE_MASK.match(relname) is not None):
2213 a8083063 Iustin Pop
        rrval = constants.HKR_SKIP
2214 a8083063 Iustin Pop
        output = ""
2215 a8083063 Iustin Pop
      else:
2216 a8083063 Iustin Pop
        result, output = self.ExecHook(fname, env)
2217 a8083063 Iustin Pop
        if not result:
2218 a8083063 Iustin Pop
          rrval = constants.HKR_FAIL
2219 a8083063 Iustin Pop
        else:
2220 a8083063 Iustin Pop
          rrval = constants.HKR_SUCCESS
2221 a8083063 Iustin Pop
      rr.append(("%s/%s" % (subdir, relname), rrval, output))
2222 a8083063 Iustin Pop
2223 a8083063 Iustin Pop
    return rr
2224 3f78eef2 Iustin Pop
2225 3f78eef2 Iustin Pop
2226 8d528b7c Iustin Pop
class IAllocatorRunner(object):
2227 8d528b7c Iustin Pop
  """IAllocator runner.
2228 8d528b7c Iustin Pop

2229 8d528b7c Iustin Pop
  This class is instantiated on the node side (ganeti-noded) and not on
2230 8d528b7c Iustin Pop
  the master side.
2231 8d528b7c Iustin Pop

2232 8d528b7c Iustin Pop
  """
2233 8d528b7c Iustin Pop
  def Run(self, name, idata):
2234 8d528b7c Iustin Pop
    """Run an iallocator script.
2235 8d528b7c Iustin Pop

2236 10c2650b Iustin Pop
    @type name: str
2237 10c2650b Iustin Pop
    @param name: the iallocator script name
2238 10c2650b Iustin Pop
    @type idata: str
2239 10c2650b Iustin Pop
    @param idata: the allocator input data
2240 10c2650b Iustin Pop

2241 10c2650b Iustin Pop
    @rtype: tuple
2242 10c2650b Iustin Pop
    @return: four element tuple of:
2243 8d528b7c Iustin Pop
       - run status (one of the IARUN_ constants)
2244 8d528b7c Iustin Pop
       - stdout
2245 8d528b7c Iustin Pop
       - stderr
2246 10c2650b Iustin Pop
       - fail reason (as from L{utils.RunResult})
2247 8d528b7c Iustin Pop

2248 8d528b7c Iustin Pop
    """
2249 8d528b7c Iustin Pop
    alloc_script = utils.FindFile(name, constants.IALLOCATOR_SEARCH_PATH,
2250 8d528b7c Iustin Pop
                                  os.path.isfile)
2251 8d528b7c Iustin Pop
    if alloc_script is None:
2252 8d528b7c Iustin Pop
      return (constants.IARUN_NOTFOUND, None, None, None)
2253 8d528b7c Iustin Pop
2254 8d528b7c Iustin Pop
    fd, fin_name = tempfile.mkstemp(prefix="ganeti-iallocator.")
2255 8d528b7c Iustin Pop
    try:
2256 8d528b7c Iustin Pop
      os.write(fd, idata)
2257 8d528b7c Iustin Pop
      os.close(fd)
2258 8d528b7c Iustin Pop
      result = utils.RunCmd([alloc_script, fin_name])
2259 8d528b7c Iustin Pop
      if result.failed:
2260 8d528b7c Iustin Pop
        return (constants.IARUN_FAILURE, result.stdout, result.stderr,
2261 8d528b7c Iustin Pop
                result.fail_reason)
2262 8d528b7c Iustin Pop
    finally:
2263 8d528b7c Iustin Pop
      os.unlink(fin_name)
2264 8d528b7c Iustin Pop
2265 8d528b7c Iustin Pop
    return (constants.IARUN_SUCCESS, result.stdout, result.stderr, None)
2266 8d528b7c Iustin Pop
2267 8d528b7c Iustin Pop
2268 3f78eef2 Iustin Pop
class DevCacheManager(object):
2269 c99a3cc0 Manuel Franceschini
  """Simple class for managing a cache of block device information.
2270 3f78eef2 Iustin Pop

2271 3f78eef2 Iustin Pop
  """
2272 3f78eef2 Iustin Pop
  _DEV_PREFIX = "/dev/"
2273 3f78eef2 Iustin Pop
  _ROOT_DIR = constants.BDEV_CACHE_DIR
2274 3f78eef2 Iustin Pop
2275 3f78eef2 Iustin Pop
  @classmethod
2276 3f78eef2 Iustin Pop
  def _ConvertPath(cls, dev_path):
2277 3f78eef2 Iustin Pop
    """Converts a /dev/name path to the cache file name.
2278 3f78eef2 Iustin Pop

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

2282 10c2650b Iustin Pop
    @type dev_path: str
2283 10c2650b Iustin Pop
    @param dev_path: the C{/dev/} path name
2284 10c2650b Iustin Pop
    @rtype: str
2285 10c2650b Iustin Pop
    @return: the converted path name
2286 3f78eef2 Iustin Pop

2287 3f78eef2 Iustin Pop
    """
2288 3f78eef2 Iustin Pop
    if dev_path.startswith(cls._DEV_PREFIX):
2289 3f78eef2 Iustin Pop
      dev_path = dev_path[len(cls._DEV_PREFIX):]
2290 3f78eef2 Iustin Pop
    dev_path = dev_path.replace("/", "_")
2291 3f78eef2 Iustin Pop
    fpath = "%s/bdev_%s" % (cls._ROOT_DIR, dev_path)
2292 3f78eef2 Iustin Pop
    return fpath
2293 3f78eef2 Iustin Pop
2294 3f78eef2 Iustin Pop
  @classmethod
2295 3f78eef2 Iustin Pop
  def UpdateCache(cls, dev_path, owner, on_primary, iv_name):
2296 3f78eef2 Iustin Pop
    """Updates the cache information for a given device.
2297 3f78eef2 Iustin Pop

2298 10c2650b Iustin Pop
    @type dev_path: str
2299 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
2300 10c2650b Iustin Pop
    @type owner: str
2301 10c2650b Iustin Pop
    @param owner: the owner (instance name) of the device
2302 10c2650b Iustin Pop
    @type on_primary: bool
2303 10c2650b Iustin Pop
    @param on_primary: whether this is the primary
2304 10c2650b Iustin Pop
        node nor not
2305 10c2650b Iustin Pop
    @type iv_name: str
2306 10c2650b Iustin Pop
    @param iv_name: the instance-visible name of the
2307 10c2650b Iustin Pop
        device, as in L{objects.Disk.iv_name}
2308 10c2650b Iustin Pop

2309 10c2650b Iustin Pop
    @rtype: None
2310 10c2650b Iustin Pop

2311 3f78eef2 Iustin Pop
    """
2312 cf5a8306 Iustin Pop
    if dev_path is None:
2313 18682bca Iustin Pop
      logging.error("DevCacheManager.UpdateCache got a None dev_path")
2314 cf5a8306 Iustin Pop
      return
2315 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
2316 3f78eef2 Iustin Pop
    if on_primary:
2317 3f78eef2 Iustin Pop
      state = "primary"
2318 3f78eef2 Iustin Pop
    else:
2319 3f78eef2 Iustin Pop
      state = "secondary"
2320 3f78eef2 Iustin Pop
    if iv_name is None:
2321 3f78eef2 Iustin Pop
      iv_name = "not_visible"
2322 3f78eef2 Iustin Pop
    fdata = "%s %s %s\n" % (str(owner), state, iv_name)
2323 3f78eef2 Iustin Pop
    try:
2324 3f78eef2 Iustin Pop
      utils.WriteFile(fpath, data=fdata)
2325 3f78eef2 Iustin Pop
    except EnvironmentError, err:
2326 18682bca Iustin Pop
      logging.exception("Can't update bdev cache for %s", dev_path)
2327 3f78eef2 Iustin Pop
2328 3f78eef2 Iustin Pop
  @classmethod
2329 3f78eef2 Iustin Pop
  def RemoveCache(cls, dev_path):
2330 3f78eef2 Iustin Pop
    """Remove data for a dev_path.
2331 3f78eef2 Iustin Pop

2332 10c2650b Iustin Pop
    This is just a wrapper over L{utils.RemoveFile} with a converted
2333 10c2650b Iustin Pop
    path name and logging.
2334 10c2650b Iustin Pop

2335 10c2650b Iustin Pop
    @type dev_path: str
2336 10c2650b Iustin Pop
    @param dev_path: the pathname of the device
2337 10c2650b Iustin Pop

2338 10c2650b Iustin Pop
    @rtype: None
2339 10c2650b Iustin Pop

2340 3f78eef2 Iustin Pop
    """
2341 cf5a8306 Iustin Pop
    if dev_path is None:
2342 18682bca Iustin Pop
      logging.error("DevCacheManager.RemoveCache got a None dev_path")
2343 cf5a8306 Iustin Pop
      return
2344 3f78eef2 Iustin Pop
    fpath = cls._ConvertPath(dev_path)
2345 3f78eef2 Iustin Pop
    try:
2346 3f78eef2 Iustin Pop
      utils.RemoveFile(fpath)
2347 3f78eef2 Iustin Pop
    except EnvironmentError, err:
2348 18682bca Iustin Pop
      logging.exception("Can't update bdev cache for %s", dev_path)